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
98template <typename InstTy>
99static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
100 Value *&Init, Value *&OtherOp);
101
102/// Returns the bitwidth of the given scalar or pointer type. For vector types,
103/// returns the element type's bitwidth.
104static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
105 if (unsigned BitWidth = Ty->getScalarSizeInBits())
106 return BitWidth;
107
108 return DL.getPointerTypeSizeInBits(Ty);
109}
110
111// Given the provided Value and, potentially, a context instruction, return
112// the preferred context instruction (if any).
113static const Instruction *safeCtxI(const Value *V, const Instruction *CtxI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CtxI && CtxI->getParent())
117 return CtxI;
118
119 // If the value is really an already-inserted instruction, then use that.
120 CtxI = dyn_cast<Instruction>(V);
121 if (CtxI && CtxI->getParent())
122 return CtxI;
123
124 return nullptr;
125}
126
128 const APInt &DemandedElts,
129 APInt &DemandedLHS, APInt &DemandedRHS) {
130 if (isa<ScalableVectorType>(Shuf->getType())) {
131 assert(DemandedElts == APInt(1,1));
132 DemandedLHS = DemandedRHS = DemandedElts;
133 return true;
134 }
135
136 int NumElts =
137 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
138 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
139 DemandedElts, DemandedLHS, DemandedRHS);
140}
141
142static void computeKnownBits(const Value *V, const APInt &DemandedElts,
143 KnownBits &Known, const SimplifyQuery &Q,
144 unsigned Depth);
145
147 const SimplifyQuery &Q, unsigned Depth) {
148 // Since the number of lanes in a scalable vector is unknown at compile time,
149 // we track one bit which is implicitly broadcast to all lanes. This means
150 // that all lanes in a scalable vector are considered demanded.
151 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
152 APInt DemandedElts =
153 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
154 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
155}
156
158 const DataLayout &DL, AssumptionCache *AC,
159 const Instruction *CtxI, const DominatorTree *DT,
160 bool UseInstrInfo, unsigned Depth) {
162 SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
163 Depth);
164}
165
167 AssumptionCache *AC, const Instruction *CtxI,
168 const DominatorTree *DT, bool UseInstrInfo,
169 unsigned Depth) {
170 return computeKnownBits(
171 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
172}
173
176 const SimplifyQuery &SQ) {
177 // Look for an inverted mask: (X & ~M) op (Y & M).
178 {
179 Value *M;
180 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
182 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CtxI, SQ.DT)
185 }
186
187 // X op (Y & ~X)
189 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT)
192
193 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
194 // for constant Y.
195 Value *Y;
196 if (match(RHS,
198 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT) &&
199 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT);
200 return IsNoUndef ? NoCommonBitsSetResult::Known
202 }
203
204 // Peek through extends to find a 'not' of the other side:
205 // (ext Y) op ext(~Y)
206 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
208 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT)
211
212 // Look for: (A & B) op ~(A | B)
213 {
214 Value *A, *B;
215 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
217 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CtxI, SQ.DT) &&
218 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CtxI, SQ.DT);
219 return IsNoUndef ? NoCommonBitsSetResult::Known
221 }
222 }
223
224 // Look for: (X << V) op (Y >> (BitWidth - V))
225 // or (X >> V) op (Y << (BitWidth - V))
226 {
227 const Value *V;
228 const APInt *R;
229 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
231 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
232 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
233 R->uge(LHS->getType()->getScalarSizeInBits()))
235 }
236
238}
239
242 const WithCache<const Value *> &RHSCache,
243 const SimplifyQuery &SQ) {
244 const Value *LHS = LHSCache.getValue();
245 const Value *RHS = RHSCache.getValue();
246
247 assert(LHS->getType() == RHS->getType() &&
248 "LHS and RHS should have the same type");
249 assert(LHS->getType()->isIntOrIntVectorTy() &&
250 "LHS and RHS should be integers");
251
253 if (Result == NoCommonBitsSetResult::Known)
255
256 NoCommonBitsSetResult CommuteResult =
258 if (CommuteResult == NoCommonBitsSetResult::Known)
260
262 RHSCache.getKnownBits(SQ)))
264
268
270}
271
273 const WithCache<const Value *> &RHSCache,
274 const SimplifyQuery &SQ) {
275 NoCommonBitsSetResult Result =
276 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
277 return Result == NoCommonBitsSetResult::Known;
278}
279
281 return !I->user_empty() &&
282 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
283}
284
286 return !I->user_empty() && all_of(I->users(), [](const User *U) {
287 CmpPredicate P;
288 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
289 });
290}
291
293 bool OrZero, AssumptionCache *AC,
294 const Instruction *CtxI,
295 const DominatorTree *DT, bool UseInstrInfo,
296 unsigned Depth) {
297 return ::isKnownToBeAPowerOfTwo(
298 V, OrZero, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
299 Depth);
300}
301
302static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
303 const SimplifyQuery &Q, unsigned Depth);
304
306 unsigned Depth) {
307 return computeKnownBits(V, SQ, Depth).isNonNegative();
308}
309
311 const SimplifyQuery &SQ, unsigned Depth) {
312 if (auto *CI = dyn_cast<ConstantInt>(V.getValue()))
313 return CI->getValue().isStrictlyPositive();
314
315 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
316 // this updated.
317 KnownBits Known = Depth == 0 ? V.getKnownBits(SQ)
318 : computeKnownBits(V.getValue(), SQ, Depth);
319 return Known.isNonNegative() &&
320 (Known.isNonZero() || isKnownNonZero(V.getValue(), SQ, Depth));
321}
322
324 const SimplifyQuery &SQ, unsigned Depth) {
325 if (Depth == 0)
326 return V.getKnownBits(SQ).isNegative();
327 return computeKnownBits(V.getValue(), SQ, Depth).isNegative();
328}
329
330static bool isKnownNonEqual(const Value *V1, const Value *V2,
331 const APInt &DemandedElts, const SimplifyQuery &Q,
332 unsigned Depth);
333
335 const Value *RHS);
336
337bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
338 const SimplifyQuery &Q, unsigned Depth) {
339 // We don't support looking through casts.
340 if (V1 == V2 || V1->getType() != V2->getType())
341 return false;
342 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
343 APInt DemandedElts =
344 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
345 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
346}
347
348bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
349 const SimplifyQuery &SQ, unsigned Depth) {
350 KnownBits Known(Mask.getBitWidth());
352 return Mask.isSubsetOf(Known.Zero);
353}
354
355static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
356 const SimplifyQuery &Q, unsigned Depth);
357
358static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
359 unsigned Depth = 0) {
360 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
361 APInt DemandedElts =
362 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
363 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
364}
365
366unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
367 AssumptionCache *AC, const Instruction *CtxI,
368 const DominatorTree *DT, bool UseInstrInfo,
369 unsigned Depth) {
370 return ::ComputeNumSignBits(
371 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
372}
373
375 AssumptionCache *AC,
376 const Instruction *CtxI,
377 const DominatorTree *DT,
378 unsigned Depth) {
379 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CtxI, DT, Depth);
380 return V->getType()->getScalarSizeInBits() - SignBits + 1;
381}
382
383/// Try to detect the lerp pattern: a * (b - c) + c * d
384/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
385///
386/// In that particular case, we can use the following chain of reasoning:
387///
388/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
389///
390/// Since that is true for arbitrary a, b, c and d within our constraints, we
391/// can conclude that:
392///
393/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
394///
395/// Considering that any result of the lerp would be less or equal to U, it
396/// would have at least the number of leading 0s as in U.
397///
398/// While being quite a specific situation, it is fairly common in computer
399/// graphics in the shape of alpha blending.
400///
401/// Modifies given KnownOut in-place with the inferred information.
402static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
403 const APInt &DemandedElts,
404 KnownBits &KnownOut,
405 const SimplifyQuery &Q,
406 unsigned Depth) {
407
408 Type *Ty = Op0->getType();
409 const unsigned BitWidth = Ty->getScalarSizeInBits();
410
411 // Only handle scalar types for now
412 if (Ty->isVectorTy())
413 return;
414
415 // Try to match: a * (b - c) + c * d.
416 // When a == 1 => A == nullptr, the same applies to d/D as well.
417 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
418 const Instruction *SubBC = nullptr;
419
420 const auto MatchSubBC = [&]() {
421 // (b - c) can have two forms that interest us:
422 //
423 // 1. sub nuw %b, %c
424 // 2. xor %c, %b
425 //
426 // For the first case, nuw flag guarantees our requirement b >= c.
427 //
428 // The second case might happen when the analysis can infer that b is a mask
429 // for c and we can transform sub operation into xor (that is usually true
430 // for constant b's). Even though xor is symmetrical, canonicalization
431 // ensures that the constant will be the RHS. We have additional checks
432 // later on to ensure that this xor operation is equivalent to subtraction.
434 m_Xor(m_Value(C), m_Value(B))));
435 };
436
437 const auto MatchASubBC = [&]() {
438 // Cases:
439 // - a * (b - c)
440 // - (b - c) * a
441 // - (b - c) <- a implicitly equals 1
442 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
443 };
444
445 const auto MatchCD = [&]() {
446 // Cases:
447 // - d * c
448 // - c * d
449 // - c <- d implicitly equals 1
451 };
452
453 const auto Match = [&](const Value *LHS, const Value *RHS) {
454 // We do use m_Specific(C) in MatchCD, so we have to make sure that
455 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
456 // has to evaluate first and return true.
457 //
458 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
459 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
460 };
461
462 if (!Match(Op0, Op1) && !Match(Op1, Op0))
463 return;
464
465 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
466 // For some of the values we use the convention of leaving
467 // it nullptr to signify an implicit constant 1.
468 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
470 };
471
472 // Check that all operands are non-negative
473 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
474 if (!KnownA.isNonNegative())
475 return;
476
477 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
478 if (!KnownD.isNonNegative())
479 return;
480
481 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
482 if (!KnownB.isNonNegative())
483 return;
484
485 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
486 if (!KnownC.isNonNegative())
487 return;
488
489 // If we matched subtraction as xor, we need to actually check that xor
490 // is semantically equivalent to subtraction.
491 //
492 // For that to be true, b has to be a mask for c or that b's known
493 // ones cover all known and possible ones of c.
494 if (SubBC->getOpcode() == Instruction::Xor &&
495 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
496 return;
497
498 const APInt MaxA = KnownA.getMaxValue();
499 const APInt MaxD = KnownD.getMaxValue();
500 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
501 const APInt MaxB = KnownB.getMaxValue();
502
503 // We can't infer leading zeros info if the upper-bound estimate wraps.
504 bool Overflow;
505 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
506
507 if (Overflow)
508 return;
509
510 // If we know that x <= y and both are positive than x has at least the same
511 // number of leading zeros as y.
512 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
513 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
514}
515
516/// Infer non-negativity for R + (R < 0 ? A : 0), where R = srem X, Y.
517/// A must be a non-negative Y or abs(Y).
518static void computeKnownBitsFromEuclideanRem(const Value *Op0, const Value *Op1,
519 const APInt &DemandedElts,
520 KnownBits &KnownOut,
521 const SimplifyQuery &Q,
522 unsigned Depth) {
523 const Value *Divisor = nullptr, *Cond = nullptr, *Remainder = nullptr,
524 *AdjustmentValue = nullptr;
526 const APInt *Threshold = nullptr;
527 bool TrueIfNegative = false;
528
529 const auto Match = [&](const Value *Rem, const Value *Adjustment) {
530 Remainder = Rem;
531
532 // Match an adjustment added only when this remainder is negative.
533 return match(Rem, m_SRem(m_Value(), m_Value(Divisor))) &&
534 match(Adjustment,
535 m_Select(m_Value(Cond), m_Value(AdjustmentValue), m_Zero())) &&
536 match(Cond, m_ICmp(Pred, m_Specific(Rem), m_APInt(Threshold))) &&
537 isSignBitCheck(Pred, *Threshold, TrueIfNegative) && TrueIfNegative;
538 };
539
540 if (!Match(Op0, Op1) && !Match(Op1, Op0))
541 return;
542
543 // Accept Y itself if non-negative, or abs(Y).
544 // For vectors, only check the demanded elements.
545 bool IsPositiveDivisorCase =
546 Divisor == AdjustmentValue &&
547 computeKnownBits(Divisor, DemandedElts, Q, Depth + 1).isNonNegative();
548 bool IsAbsoluteValueCase =
549 match(AdjustmentValue,
551
552 if (!IsPositiveDivisorCase && !IsAbsoluteValueCase)
553 return;
554
555 // Repeated uses must agree. An undef value could break this relationship.
556 // For vectors, this check is conservative (checks the entire vector, not just
557 // the demanded elements).
558 if (!isGuaranteedNotToBeUndef(Remainder, Q.AC, Q.CtxI, Q.DT, Depth + 1) ||
559 !isGuaranteedNotToBeUndef(Divisor, Q.AC, Q.CtxI, Q.DT, Depth + 1))
560 return;
561
562 // For Y other than signed minimum, adding abs(Y) to a negative remainder
563 // gives a non-negative result without overflow. For signed minimum, the
564 // wrapping addition clears the remainder's sign bit. Poison-producing cases
565 // do not invalidate this deduction.
566 KnownOut.makeNonNegative();
567}
568
569static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
570 bool NSW, bool NUW,
571 const APInt &DemandedElts,
572 KnownBits &KnownOut, KnownBits &Known2,
573 const SimplifyQuery &Q, unsigned Depth) {
574 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
575
576 if (KnownOut.isUnknown() && !NSW && !NUW) {
577 if (Add) {
578 // Independent operand bits give no result, but the Euclidean remainder
579 // pattern can establish non-negativity through the operands'
580 // relationship.
581 computeKnownBitsFromEuclideanRem(Op0, Op1, DemandedElts, KnownOut, Q,
582 Depth);
583 }
584 return;
585 }
586
587 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
588 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
589
590 if (!Add && NSW && !KnownOut.isNonNegative() &&
592 .value_or(false) ||
593 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
594 KnownOut.makeNonNegative();
595
596 if (Add) {
597 // Try to match lerp pattern and combine results
598 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
599
600 // Use the relationship between the remainder and its adjustment.
601 computeKnownBitsFromEuclideanRem(Op0, Op1, DemandedElts, KnownOut, Q,
602 Depth);
603 }
604}
605
606static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
607 bool NUW, const APInt &DemandedElts,
608 KnownBits &Known, KnownBits &Known2,
609 const SimplifyQuery &Q, unsigned Depth) {
610 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
611 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
612
613 bool isKnownNegative = false;
614 bool isKnownNonNegative = false;
615 // If the multiplication is known not to overflow, compute the sign bit.
616 if (NSW) {
617 if (Op0 == Op1) {
618 // The product of a number with itself is non-negative.
619 isKnownNonNegative = true;
620 } else {
621 bool isKnownNonNegativeOp1 = Known.isNonNegative();
622 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
623 bool isKnownNegativeOp1 = Known.isNegative();
624 bool isKnownNegativeOp0 = Known2.isNegative();
625 // The product of two numbers with the same sign is non-negative.
626 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
627 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
628 if (!isKnownNonNegative && NUW) {
629 // mul nuw nsw with a factor > 1 is non-negative.
630 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
631 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
632 KnownBits::sgt(Known2, One).value_or(false);
633 }
634
635 // The product of a negative number and a non-negative number is either
636 // negative or zero.
639 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
640 Known2.isNonZero()) ||
641 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
642 }
643 }
644
645 bool SelfMultiply = Op0 == Op1;
646 if (SelfMultiply)
647 SelfMultiply &=
648 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
649 Known = KnownBits::mul(Known, Known2, SelfMultiply);
650
651 if (SelfMultiply) {
652 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
653 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
654 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
655
656 if (OutValidBits < TyBits) {
657 APInt KnownZeroMask =
658 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
659 Known.Zero |= KnownZeroMask;
660 }
661 }
662
663 // Only make use of no-wrap flags if we failed to compute the sign bit
664 // directly. This matters if the multiplication always overflows, in
665 // which case we prefer to follow the result of the direct computation,
666 // though as the program is invoking undefined behaviour we can choose
667 // whatever we like here.
668 if (isKnownNonNegative && !Known.isNegative())
669 Known.makeNonNegative();
670 else if (isKnownNegative && !Known.isNonNegative())
671 Known.makeNegative();
672}
673
675 KnownBits &Known) {
676 unsigned BitWidth = Known.getBitWidth();
677 unsigned NumRanges = Ranges.getNumOperands() / 2;
678 assert(NumRanges >= 1);
679
680 Known.setAllConflict();
681
682 for (unsigned i = 0; i < NumRanges; ++i) {
684 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
686 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
687 ConstantRange Range(Lower->getValue(), Upper->getValue());
688 // BitWidth must equal the Ranges BitWidth for the correct number of high
689 // bits to be set.
690 assert(BitWidth == Range.getBitWidth() &&
691 "Known bit width must match range bit width!");
692
693 // The first CommonPrefixBits of all values in Range are equal.
694 unsigned CommonPrefixBits =
695 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
696 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
697 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
698 Known.One &= UnsignedMax & Mask;
699 Known.Zero &= ~UnsignedMax & Mask;
700 }
701}
702
703static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
704 // The instruction defining an assumption's condition itself is always
705 // considered ephemeral to that assumption (even if it has other
706 // non-ephemeral users). See r246696's test case for an example.
707 if (is_contained(I->operands(), E))
708 return true;
709
710 const auto *EI = dyn_cast<Instruction>(E);
711 if (!EI)
712 return false;
713
714 if (EI == I)
715 return true;
716
719 Visited.insert(EI);
720 WorkList.push_back(EI);
721 bool ReachesI = false;
722 while (!WorkList.empty()) {
723 const Instruction *V = WorkList.pop_back_val();
724 for (const User *U : V->users()) {
725 const auto *UI = cast<Instruction>(U);
726 if (UI == I) {
727 ReachesI = true;
728 continue;
729 }
730 if (UI->mayHaveSideEffects() || UI->isTerminator())
731 return false;
732 if (Visited.insert(UI).second)
733 WorkList.push_back(UI);
734 }
735 }
736 return ReachesI;
737}
738
739// Is this an intrinsic that cannot be speculated but also cannot trap?
741 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
742 return CI->isAssumeLikeIntrinsic();
743
744 return false;
745}
746
748 const Instruction *CtxI,
749 const DominatorTree *DT,
750 bool AllowEphemerals) {
751 // There are two restrictions on the use of an assume:
752 // 1. The assume must dominate the context (or the control flow must
753 // reach the assume whenever it reaches the context).
754 // 2. The context must not be in the assume's set of ephemeral values
755 // (otherwise we will use the assume to prove that the condition
756 // feeding the assume is trivially true, thus causing the removal of
757 // the assume).
758
759 // If the checked instruction and the assume are the same, it's valid exactly
760 // if ephemeral values are allowed.
761 if (Inv == CtxI)
762 return AllowEphemerals;
763
764 if (Inv->getParent() == CtxI->getParent()) {
765 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
766 // in the BB.
767 if (Inv->comesBefore(CtxI))
768 return true;
769
770 // The context comes first, but they're both in the same block.
771 // Make sure there is nothing in between that might interrupt
772 // the control flow, not even CtxI itself.
773 // We limit the scan distance between the assume and its context instruction
774 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
775 // it can be adjusted if needed (could be turned into a cl::opt).
776 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
778 return false;
779
780 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
781 }
782
783 // Inv and CtxI are in different blocks.
784 if (DT) {
785 if (DT->dominates(Inv, CtxI))
786 return true;
787 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
788 Inv->getParent()->isEntryBlock()) {
789 // We don't have a DT, but this trivially dominates.
790 return true;
791 }
792
793 return false;
794}
795
798 unsigned &NumChecked) {
799 for (const Instruction &I : make_range(Begin, End)) {
800 if (NumChecked++ > MaxInstrsToCheckForFree)
801 return false;
802 if (auto *CB = dyn_cast<CallBase>(&I)) {
803 if (!CB->hasFnAttr(Attribute::NoFree))
804 return false;
805 } else if (I.maySynchronize()) {
806 return false;
807 }
808 }
809 return true;
810}
811
813 const Instruction *CtxI,
814 const DominatorTree *DT) {
815 const BasicBlock *CtxBB = CtxI->getParent();
816 const BasicBlock *AssumeBB = Assume->getParent();
817 unsigned NumChecked = 0;
818 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
819 if (CtxBB == AssumeBB) {
820 if (Assume != CtxI && !Assume->comesBefore(CtxI))
821 return false;
822 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
823 }
824 if (DT && !DT->dominates(Assume, CtxI))
825 return false;
826 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
827 return false;
828 if (pred_empty(CtxBB))
829 return false;
830
831 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
832 // backedges returning to CtxBB are enqueued and checked correctly.
835 while (!Worklist.empty()) {
836 const BasicBlock *CurBB = Worklist.pop_back_val();
837 if (!Visited.insert(CurBB).second)
838 continue;
839
840 if (CurBB == AssumeBB) {
841 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
842 return false;
843 continue;
844 }
845 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
846 "Blocks between Assume and CtxI must be dominated by AssumeBB");
847
848 if (pred_empty(CurBB)) {
849 // Reaching the entry block means there is a path to CtxI that does not
850 // pass through Assume.
851 if (CurBB->isEntryBlock())
852 return false;
853
854 // CurBB is unreachable (for example, emptied by SimplifyCFG but not yet
855 // removed), so nothing in it can execute a free.
856 continue;
857 }
858
859 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
860 // instructions from CtxIter to the end of CtxBB (instructions before
861 // CtxIter were checked above). Otherwise, check the entire block.
862 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
863 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
864 return false;
865 append_range(Worklist, predecessors(CurBB));
866 }
867 return true;
868}
869
870// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
871// we still have enough information about `RHS` to conclude non-zero. For
872// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
873// so the extra compile time may not be worth it, but possibly a second API
874// should be created for use outside of loops.
876 // v u> y implies v != 0.
878 return true;
879
880 // Special-case v != 0 to also handle v != null.
881 if (Pred == ICmpInst::ICMP_NE)
882 return match(RHS, m_Zero());
883
884 // All other predicates - rely on generic ConstantRange handling.
885 const APInt *C;
886 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
887 if (match(RHS, m_APInt(C))) {
889 return !TrueValues.contains(Zero);
890 }
891
893 if (VC == nullptr)
894 return false;
895
896 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
897 ++ElemIdx) {
899 Pred, VC->getElementAsAPInt(ElemIdx));
900 if (TrueValues.contains(Zero))
901 return false;
902 }
903 return true;
904}
905
906static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
907 Value *&ValOut, Instruction *&CtxIOut,
908 const PHINode **PhiOut = nullptr) {
909 ValOut = U->get();
910 if (ValOut == PHI)
911 return;
912 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
913 if (PhiOut)
914 *PhiOut = PHI;
915 Value *V;
916 // If the Use is a select of this phi, compute analysis on other arm to break
917 // recursion.
918 // TODO: Min/Max
919 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
920 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
921 ValOut = V;
922
923 // Same for select, if this phi is 2-operand phi, compute analysis on other
924 // incoming value to break recursion.
925 // TODO: We could handle any number of incoming edges as long as we only have
926 // two unique values.
927 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
928 IncPhi && IncPhi->getNumIncomingValues() == 2) {
929 for (int Idx = 0; Idx < 2; ++Idx) {
930 if (IncPhi->getIncomingValue(Idx) == PHI) {
931 ValOut = IncPhi->getIncomingValue(1 - Idx);
932 if (PhiOut)
933 *PhiOut = IncPhi;
934 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
935 break;
936 }
937 }
938 }
939}
940
941static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
942 // Use of assumptions is context-sensitive. If we don't have a context, we
943 // cannot use them!
944 if (!Q.AC || !Q.CtxI)
945 return false;
946
948 if (!Elem.Assume)
949 continue;
950
951 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
952 assert(I->getFunction() == Q.CtxI->getFunction() &&
953 "Got assumption for the wrong function!");
954
955 if (Elem.Index != AssumptionCache::ExprResultIdx) {
957 I->getOperandBundleAt(Elem.Index)) &&
959 return true;
960 continue;
961 }
962
963 // Warning: This loop can end up being somewhat performance sensitive.
964 // We're running this loop for once for each value queried resulting in a
965 // runtime of ~O(#assumes * #values).
966
967 if (match(I->getArgOperand(0), m_Trunc(m_Specific(V))) &&
969 return true;
970
971 Value *RHS;
974 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
975 continue;
976
978 return true;
979 }
980
981 return false;
982}
983
986 const SimplifyQuery &Q) {
987 if (RHS->getType()->isPointerTy()) {
988 // Handle comparison of pointer to null explicitly, as it will not be
989 // covered by the m_APInt() logic below.
990 if (LHS == V && match(RHS, m_Zero())) {
991 switch (Pred) {
993 Known.setAllZero();
994 break;
997 Known.makeNonNegative();
998 break;
1000 Known.makeNegative();
1001 break;
1002 default:
1003 break;
1004 }
1005 }
1006 return;
1007 }
1008
1009 unsigned BitWidth = Known.getBitWidth();
1010 auto m_V =
1012
1013 Value *Y;
1014 const APInt *Mask, *C;
1015 if (!match(RHS, m_APInt(C)))
1016 return;
1017
1018 uint64_t ShAmt;
1019 switch (Pred) {
1020 case ICmpInst::ICMP_EQ:
1021 // assume(V = C)
1022 if (match(LHS, m_V)) {
1023 Known = Known.unionWith(KnownBits::makeConstant(*C));
1024 // assume(V & Mask = C)
1025 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
1026 // For one bits in Mask, we can propagate bits from C to V.
1027 Known.One |= *C;
1028 if (match(Y, m_APInt(Mask)))
1029 Known.Zero |= ~*C & *Mask;
1030 // assume(V | Mask = C)
1031 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
1032 // For zero bits in Mask, we can propagate bits from C to V.
1033 Known.Zero |= ~*C;
1034 if (match(Y, m_APInt(Mask)))
1035 Known.One |= *C & ~*Mask;
1036 // assume(V << ShAmt = C)
1037 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
1038 ShAmt < BitWidth) {
1039 // For those bits in C that are known, we can propagate them to known
1040 // bits in V shifted to the right by ShAmt.
1041 KnownBits RHSKnown = KnownBits::makeConstant(*C);
1042 RHSKnown >>= ShAmt;
1043 Known = Known.unionWith(RHSKnown);
1044 // assume(V >> ShAmt = C)
1045 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
1046 ShAmt < BitWidth) {
1047 // For those bits in RHS that are known, we can propagate them to known
1048 // bits in V shifted to the right by C.
1049 KnownBits RHSKnown = KnownBits::makeConstant(*C);
1050 RHSKnown <<= ShAmt;
1051 Known = Known.unionWith(RHSKnown);
1052 }
1053 break;
1054 case ICmpInst::ICMP_NE: {
1055 // assume (V & B != 0) where B is a power of 2
1056 const APInt *BPow2;
1057 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
1058 Known.One |= *BPow2;
1059 break;
1060 }
1061 default: {
1062 const APInt *Offset = nullptr;
1063 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
1065 if (Offset)
1066 LHSRange = LHSRange.sub(*Offset);
1067 Known = Known.unionWith(LHSRange.toKnownBits());
1068 }
1070 // X & Y u> C -> X u> C && Y u> C
1071 // X nuw- Y u> C -> X u> C
1072 if (match(LHS, m_c_And(m_V, m_Value())) ||
1073 match(LHS, m_NUWSub(m_V, m_Value())))
1074 Known.One.setHighBits(
1075 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
1076 }
1078 // X | Y u< C -> X u< C && Y u< C
1079 // X nuw+ Y u< C -> X u< C && Y u< C
1080 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1081 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1082 Known.Zero.setHighBits(
1083 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1084 }
1085 }
1086 } break;
1087 }
1088}
1089
1092 const SimplifyQuery &SQ, bool Invert) {
1094 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1095 Value *LHS = Cmp->getOperand(0);
1096 Value *RHS = Cmp->getOperand(1);
1097
1098 // Handle icmp pred (trunc V), C
1099 if (match(LHS, m_Trunc(m_Specific(V)))) {
1100 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1101 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1103 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1104 else
1105 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1106 return;
1107 }
1108
1110}
1111
1113 KnownBits &Known, const SimplifyQuery &SQ,
1114 bool Invert, unsigned Depth) {
1115 Value *A, *B;
1118 KnownBits Known2(Known.getBitWidth());
1119 KnownBits Known3(Known.getBitWidth());
1120 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1121 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1122 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1124 Known2 = Known2.unionWith(Known3);
1125 else
1126 Known2 = Known2.intersectWith(Known3);
1127 Known = Known.unionWith(Known2);
1128 return;
1129 }
1130
1131 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1132 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1133 return;
1134 }
1135
1136 if (match(Cond, m_Trunc(m_Specific(V)))) {
1137 KnownBits DstKnown(1);
1138 if (Invert) {
1139 DstKnown.setAllZero();
1140 } else {
1141 DstKnown.setAllOnes();
1142 }
1144 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1145 return;
1146 }
1147 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1148 return;
1149 }
1150
1152 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1153}
1154
1156 const SimplifyQuery &Q, unsigned Depth) {
1157 // Handle injected condition.
1158 if (Q.CC && Q.CC->AffectedValues.contains(V))
1160
1161 if (!Q.CtxI)
1162 return;
1163
1164 if (Q.DC && Q.DT) {
1165 // Handle dominating conditions.
1166 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1167 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1168 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1169 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1170 /*Invert*/ false, Depth);
1171
1172 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1173 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1174 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1175 /*Invert*/ true, Depth);
1176 }
1177
1178 if (Known.hasConflict())
1179 Known.resetAll();
1180 }
1181
1182 if (!Q.AC)
1183 return;
1184
1185 unsigned BitWidth = Known.getBitWidth();
1186
1187 // Note that the patterns below need to be kept in sync with the code
1188 // in AssumptionCache::updateAffectedValues.
1189
1190 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1191 if (!Elem.Assume)
1192 continue;
1193
1194 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1195 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1196 "Got assumption for the wrong function!");
1197
1198 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1199 auto OBU = I->getOperandBundleAt(Elem.Index);
1200 switch (getBundleAttrFromOBU(OBU)) {
1201 case BundleAttr::Align: {
1202 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1203 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1205 Known.Zero |= (*Alignment - 1) & ~*Offset;
1206 Known.One |= (*Alignment - 1) & *Offset;
1207 }
1208 } break;
1209
1210 case BundleAttr::Range: {
1211 auto [Val, Range] = getAssumeRangeInfo(OBU);
1212 if (Val == V && isValidAssumeForContext(I, Q))
1213 Known = Known.unionWith(Range.toKnownBits());
1214 } break;
1215
1216 default:
1217 break;
1218 }
1219 continue;
1220 }
1221
1222 // Warning: This loop can end up being somewhat performance sensitive.
1223 // We're running this loop for once for each value queried resulting in a
1224 // runtime of ~O(#assumes * #values).
1225
1226 Value *Arg = I->getArgOperand(0);
1227
1228 if (Arg == V && isValidAssumeForContext(I, Q)) {
1229 assert(BitWidth == 1 && "assume operand is not i1?");
1230 (void)BitWidth;
1231 Known.setAllOnes();
1232 return;
1233 }
1234 if (match(Arg, m_Not(m_Specific(V))) &&
1236 assert(BitWidth == 1 && "assume operand is not i1?");
1237 (void)BitWidth;
1238 Known.setAllZero();
1239 return;
1240 }
1241 auto *Trunc = dyn_cast<TruncInst>(Arg);
1242 if (Trunc && Trunc->getOperand(0) == V &&
1244 if (Trunc->hasNoUnsignedWrap()) {
1246 return;
1247 }
1248 Known.One.setBit(0);
1249 return;
1250 }
1251
1252 // The remaining tests are all recursive, so bail out if we hit the limit.
1254 continue;
1255
1256 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1257 if (!Cmp)
1258 continue;
1259
1260 if (!isValidAssumeForContext(I, Q))
1261 continue;
1262
1263 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1264 }
1265
1266 // Conflicting assumption: Undefined behavior will occur on this execution
1267 // path.
1268 if (Known.hasConflict())
1269 Known.resetAll();
1270}
1271
1272/// Compute known bits from a shift operator, including those with a
1273/// non-constant shift amount. Known is the output of this function. Known2 is a
1274/// pre-allocated temporary with the same bit width as Known and on return
1275/// contains the known bit of the shift value source. KF is an
1276/// operator-specific function that, given the known-bits and a shift amount,
1277/// compute the implied known-bits of the shift operator's result respectively
1278/// for that shift amount. The results from calling KF are conservatively
1279/// combined for all permitted shift amounts.
1281 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1282 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1283 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1284 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1285 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1286 // To limit compile-time impact, only query isKnownNonZero() if we know at
1287 // least something about the shift amount.
1288 bool ShAmtNonZero =
1289 Known.isNonZero() ||
1290 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1291 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1292 Known = KF(Known2, Known, ShAmtNonZero);
1293}
1294
1295static KnownBits
1296getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1297 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1298 const SimplifyQuery &Q, unsigned Depth) {
1299 unsigned BitWidth = KnownLHS.getBitWidth();
1300 KnownBits KnownOut(BitWidth);
1301 bool IsAnd = false;
1302 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1303 Value *X = nullptr, *Y = nullptr;
1304
1305 switch (I->getOpcode()) {
1306 case Instruction::And:
1307 KnownOut = KnownLHS & KnownRHS;
1308 IsAnd = true;
1309 // and(x, -x) is common idioms that will clear all but lowest set
1310 // bit. If we have a single known bit in x, we can clear all bits
1311 // above it.
1312 // TODO: instcombine often reassociates independent `and` which can hide
1313 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1314 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1315 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1316 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1317 KnownOut = KnownLHS.blsi();
1318 else
1319 KnownOut = KnownRHS.blsi();
1320 }
1321 break;
1322 case Instruction::Or:
1323 KnownOut = KnownLHS | KnownRHS;
1324 break;
1325 case Instruction::Xor:
1326 KnownOut = KnownLHS ^ KnownRHS;
1327 // xor(x, x-1) is common idioms that will clear all but lowest set
1328 // bit. If we have a single known bit in x, we can clear all bits
1329 // above it.
1330 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1331 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1332 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1333 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1334 if (HasKnownOne &&
1336 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1337 KnownOut = XBits.blsmsk();
1338 }
1339 break;
1340 default:
1341 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1342 }
1343
1344 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1345 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1346 // here we handle the more general case of adding any odd number by
1347 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1348 // TODO: This could be generalized to clearing any bit set in y where the
1349 // following bit is known to be unset in y.
1350 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1354 KnownBits KnownY(BitWidth);
1355 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1356 if (KnownY.countMinTrailingOnes() > 0) {
1357 if (IsAnd)
1358 KnownOut.Zero.setBit(0);
1359 else
1360 KnownOut.One.setBit(0);
1361 }
1362 }
1363 return KnownOut;
1364}
1365
1367 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1368 unsigned Depth,
1369 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1370 KnownBitsFunc) {
1371 APInt DemandedEltsLHS, DemandedEltsRHS;
1373 DemandedElts, DemandedEltsLHS,
1374 DemandedEltsRHS);
1375
1376 const auto ComputeForSingleOpFunc =
1377 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1378 return KnownBitsFunc(
1379 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1380 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1381 };
1382
1383 if (DemandedEltsRHS.isZero())
1384 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1385 if (DemandedEltsLHS.isZero())
1386 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1387
1388 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1389 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1390}
1391
1392// Public so this can be used in `SimplifyDemandedUseBits`.
1394 const KnownBits &KnownLHS,
1395 const KnownBits &KnownRHS,
1396 const SimplifyQuery &SQ,
1397 unsigned Depth) {
1398 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1399 APInt DemandedElts =
1400 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1401
1402 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1403 Depth);
1404}
1405
1407 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1408 // Without vscale_range, we only know that vscale is non-zero.
1409 if (!Attr.isValid())
1411
1412 unsigned AttrMin = Attr.getVScaleRangeMin();
1413 // Minimum is larger than vscale width, result is always poison.
1414 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1415 return ConstantRange::getEmpty(BitWidth);
1416
1417 APInt Min(BitWidth, AttrMin);
1418 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1419 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1421
1422 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1423}
1424
1425/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1426/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1427/// target's VLEN range. Callers must ensure the target is RISC-V.
1428static bool isReadVLENB(const IntrinsicInst &II) {
1429 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1430 if (!MAV)
1431 return false;
1432 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1433 if (!MD || MD->getNumOperands() != 1)
1434 return false;
1435 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1436 return RegName && RegName->getString() == "vlenb";
1437}
1438
1439/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1440/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1441/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1442/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1443/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1444/// attribute, when present, pins the subtarget's VLEN in units of
1445/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1446/// RVVBytesPerBlock.
1448 unsigned Width) {
1449 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1450 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1451
1452 const Function *F = II.getFunction();
1453 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1454 ConstantRange VScale = getVScaleRange(F, Width);
1455 Range = Range.intersectWith(
1457 }
1458 return Range;
1459}
1460
1462 Value *Arm, bool Invert,
1463 const SimplifyQuery &Q, unsigned Depth) {
1464 // If we have a constant arm, we are done.
1465 if (Known.isConstant())
1466 return;
1467
1468 // See what condition implies about the bits of the select arm.
1469 KnownBits CondRes(Known.getBitWidth());
1470 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1471 // If we don't get any information from the condition, no reason to
1472 // proceed.
1473 if (CondRes.isUnknown())
1474 return;
1475
1476 // We can have conflict if the condition is dead. I.e if we have
1477 // (x | 64) < 32 ? (x | 64) : y
1478 // we will have conflict at bit 6 from the condition/the `or`.
1479 // In that case just return. Its not particularly important
1480 // what we do, as this select is going to be simplified soon.
1481 CondRes = CondRes.unionWith(Known);
1482 if (CondRes.hasConflict())
1483 return;
1484
1485 // Finally make sure the information we found is valid. This is relatively
1486 // expensive so it's left for the very end.
1487 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1488 return;
1489
1490 // Finally, we know we get information from the condition and its valid,
1491 // so return it.
1492 Known = std::move(CondRes);
1493}
1494
1495// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1496// Returns the input and lower/upper bounds.
1497static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1498 const APInt *&CLow, const APInt *&CHigh) {
1500 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1501 "Input should be a Select!");
1502
1503 const Value *LHS = nullptr, *RHS = nullptr;
1505 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1506 return false;
1507
1508 if (!match(RHS, m_APInt(CLow)))
1509 return false;
1510
1511 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1513 if (getInverseMinMaxFlavor(SPF) != SPF2)
1514 return false;
1515
1516 if (!match(RHS2, m_APInt(CHigh)))
1517 return false;
1518
1519 if (SPF == SPF_SMIN)
1520 std::swap(CLow, CHigh);
1521
1522 In = LHS2;
1523 return CLow->sle(*CHigh);
1524}
1525
1527 const APInt *&CLow,
1528 const APInt *&CHigh) {
1529 assert((II->getIntrinsicID() == Intrinsic::smin ||
1530 II->getIntrinsicID() == Intrinsic::smax) &&
1531 "Must be smin/smax");
1532
1533 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1534 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1535 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1536 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1537 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1538 return false;
1539
1540 if (II->getIntrinsicID() == Intrinsic::smin)
1541 std::swap(CLow, CHigh);
1542 return CLow->sle(*CHigh);
1543}
1544
1546 KnownBits &Known) {
1547 const APInt *CLow, *CHigh;
1548 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1549 Known = Known.unionWith(
1550 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1551}
1552
1554 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1555 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1556 unsigned Depth) {
1557 // Change the context instruction to the "edge" that flows into the phi. This
1558 // is important because that is where the value is actually "evaluated" even
1559 // though it is used later somewhere else. (see also D69571).
1561 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1562
1563 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1564 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1565
1566 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1567 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1568}
1569
1571 const APInt &DemandedElts,
1573 const SimplifyQuery &Q,
1574 unsigned Depth) {
1575 unsigned BitWidth = Known.getBitWidth();
1576
1577 KnownBits Known2(BitWidth);
1578 switch (I->getOpcode()) {
1579 default: break;
1580 case Instruction::Load:
1581 if (MDNode *MD =
1582 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1584 break;
1585 case Instruction::And:
1586 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1587 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1588
1589 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1590 break;
1591 case Instruction::Or:
1592 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1593 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1594
1595 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1596 break;
1597 case Instruction::Xor:
1598 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1599 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1600
1601 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1602 break;
1603 case Instruction::Mul: {
1606 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1607 DemandedElts, Known, Known2, Q, Depth);
1608 break;
1609 }
1610 case Instruction::UDiv: {
1611 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1612 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1613 Known =
1615 break;
1616 }
1617 case Instruction::SDiv: {
1618 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1619 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1620 Known =
1622 break;
1623 }
1624 case Instruction::Select: {
1625 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1626 KnownBits Res(Known.getBitWidth());
1627 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1628 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1629 return Res;
1630 };
1631 // Only known if known in both the LHS and RHS.
1632 Known =
1633 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1634 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1635 break;
1636 }
1637 case Instruction::FPToSI: {
1638 // fptosi is poison if the rounded value doesn't fit in the result type,
1639 // so we can assume the conversion is well-defined and rounds towards
1640 // zero. +-Inf can never fit in an integer type, so it is always poison,
1641 // like NaN. Negative subnormals and negative zero round to 0. That
1642 // leaves negative normals as the only class that can produce a defined
1643 // negative result.
1644 KnownFPClass SrcFPClass = computeKnownFPClass(
1645 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1646 if (SrcFPClass.isKnownNever(fcNegNormal))
1647 Known.makeNonNegative();
1648 break;
1649 }
1650 case Instruction::FPTrunc:
1651 case Instruction::FPExt:
1652 case Instruction::FPToUI:
1653 case Instruction::SIToFP:
1654 case Instruction::UIToFP:
1655 break; // Can't work with floating point.
1656 case Instruction::PtrToInt:
1657 case Instruction::PtrToAddr:
1658 case Instruction::IntToPtr:
1659 // Fall through and handle them the same as zext/trunc.
1660 [[fallthrough]];
1661 case Instruction::ZExt:
1662 case Instruction::Trunc: {
1663 Type *SrcTy = I->getOperand(0)->getType();
1664
1665 unsigned SrcBitWidth;
1666 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1667 // which fall through here.
1668 Type *ScalarTy = SrcTy->getScalarType();
1669 SrcBitWidth = ScalarTy->isPointerTy() ?
1670 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1671 Q.DL.getTypeSizeInBits(ScalarTy);
1672
1673 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1674 Known = Known.anyextOrTrunc(SrcBitWidth);
1675 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1676 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1677 Inst && Inst->hasNonNeg() && !Known.isNegative())
1678 Known.makeNonNegative();
1679 Known = Known.zextOrTrunc(BitWidth);
1680 break;
1681 }
1682 case Instruction::BitCast: {
1683 Type *SrcTy = I->getOperand(0)->getType();
1684 if (SrcTy->isIntOrPtrTy() &&
1685 // TODO: For now, not handling conversions like:
1686 // (bitcast i64 %x to <2 x i32>)
1687 !I->getType()->isVectorTy()) {
1688 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1689 break;
1690 }
1691
1692 const Value *V;
1693 // Handle bitcast from floating point to integer.
1695 V->getType()->isFPOrFPVectorTy()) {
1696 Type *FPType = V->getType()->getScalarType();
1697 KnownFPClass Result =
1698 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1699
1700 Known = Result.toKnownBits(FPType->getFltSemantics());
1701
1702 break;
1703 }
1704
1705 // Handle cast from vector integer type to scalar or vector integer.
1706 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1707 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1708 !I->getType()->isIntOrIntVectorTy() ||
1709 isa<ScalableVectorType>(I->getType()))
1710 break;
1711
1712 unsigned NumElts = DemandedElts.getBitWidth();
1713 bool IsLE = Q.DL.isLittleEndian();
1714 // Look through a cast from narrow vector elements to wider type.
1715 // Examples: v4i32 -> v2i64, v3i8 -> v24
1716 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1717 if (BitWidth % SubBitWidth == 0) {
1718 // Known bits are automatically intersected across demanded elements of a
1719 // vector. So for example, if a bit is computed as known zero, it must be
1720 // zero across all demanded elements of the vector.
1721 //
1722 // For this bitcast, each demanded element of the output is sub-divided
1723 // across a set of smaller vector elements in the source vector. To get
1724 // the known bits for an entire element of the output, compute the known
1725 // bits for each sub-element sequentially. This is done by shifting the
1726 // one-set-bit demanded elements parameter across the sub-elements for
1727 // consecutive calls to computeKnownBits. We are using the demanded
1728 // elements parameter as a mask operator.
1729 //
1730 // The known bits of each sub-element are then inserted into place
1731 // (dependent on endian) to form the full result of known bits.
1732 unsigned SubScale = BitWidth / SubBitWidth;
1733 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1734 for (unsigned i = 0; i != NumElts; ++i) {
1735 if (DemandedElts[i])
1736 SubDemandedElts.setBit(i * SubScale);
1737 }
1738
1739 KnownBits KnownSrc(SubBitWidth);
1740 for (unsigned i = 0; i != SubScale; ++i) {
1741 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1742 Depth + 1);
1743 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1744 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1745 }
1746 }
1747 // Look through a cast from wider vector elements to narrow type.
1748 // Examples: v2i64 -> v4i32
1749 if (SubBitWidth % BitWidth == 0) {
1750 unsigned SubScale = SubBitWidth / BitWidth;
1751 KnownBits KnownSrc(SubBitWidth);
1752 APInt SubDemandedElts =
1753 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1754 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1755 Depth + 1);
1756
1757 Known.setAllConflict();
1758 for (unsigned i = 0; i != NumElts; ++i) {
1759 if (DemandedElts[i]) {
1760 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1761 unsigned Offset = (Shifts % SubScale) * BitWidth;
1762 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1763 if (Known.isUnknown())
1764 break;
1765 }
1766 }
1767 }
1768 break;
1769 }
1770 case Instruction::SExt: {
1771 // Compute the bits in the result that are not present in the input.
1772 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1773
1774 Known = Known.trunc(SrcBitWidth);
1775 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1776 // If the sign bit of the input is known set or clear, then we know the
1777 // top bits of the result.
1778 Known = Known.sext(BitWidth);
1779 break;
1780 }
1781 case Instruction::Shl: {
1784 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1785 bool ShAmtNonZero) {
1786 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1787 };
1788 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1789 KF);
1790 // X << X is even: X is either zero or shifts by at least one bit. Both
1791 // uses must observe the same value, so X must not be undef.
1792 if (I->getOperand(0) == I->getOperand(1) &&
1793 isGuaranteedNotToBeUndef(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
1794 Depth + 1))
1795 Known.Zero.setBit(0);
1796
1797 // Trailing zeros of a right-shifted constant never decrease.
1798 const APInt *C;
1799 if (match(I->getOperand(0), m_APInt(C)))
1800 Known.Zero.setLowBits(C->countr_zero());
1801
1802 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1803 // lands at bit Y, when BitWidth is a power of 2.
1804 const APInt *YC;
1805 Value *X = I->getOperand(0);
1806 if (isPowerOf2_32(BitWidth) &&
1807 match(I->getOperand(1),
1809 m_SpecificInt(BitWidth - 1)))) &&
1810 YC->ult(BitWidth - 1)) {
1811 unsigned Y = YC->getZExtValue();
1812 Known.One.setBit(Y);
1813 Known.Zero.setBitsFrom(Y + 1);
1814 }
1815 break;
1816 }
1817 case Instruction::LShr: {
1818 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1819 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1820 bool ShAmtNonZero) {
1821 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1822 };
1823 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1824 KF);
1825 // Leading zeros of a left-shifted constant never decrease.
1826 const APInt *C;
1827 if (match(I->getOperand(0), m_APInt(C)))
1828 Known.Zero.setHighBits(C->countl_zero());
1829 break;
1830 }
1831 case Instruction::AShr: {
1832 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1833 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1834 bool ShAmtNonZero) {
1835 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1836 };
1837 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1838 KF);
1839 break;
1840 }
1841 case Instruction::Sub: {
1844 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1845 DemandedElts, Known, Known2, Q, Depth);
1846 break;
1847 }
1848 case Instruction::Add: {
1851 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1852 DemandedElts, Known, Known2, Q, Depth);
1853 break;
1854 }
1855 case Instruction::SRem:
1856 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1857 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1858 Known = KnownBits::srem(Known, Known2);
1859 break;
1860
1861 case Instruction::URem:
1862 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1863 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1864 Known = KnownBits::urem(Known, Known2);
1865 break;
1866 case Instruction::Alloca:
1867 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1868 break;
1869 case Instruction::GetElementPtr: {
1870 // Analyze all of the subscripts of this getelementptr instruction
1871 // to determine if we can prove known low zero bits.
1872 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1873 // Accumulate the constant indices in a separate variable
1874 // to minimize the number of calls to computeForAddSub.
1875 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1876 APInt AccConstIndices(IndexWidth, 0);
1877
1878 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1879 if (IndexWidth == BitWidth) {
1880 // Note that inbounds does *not* guarantee nsw for the addition, as only
1881 // the offset is signed, while the base address is unsigned.
1882 Known = KnownBits::add(Known, IndexBits);
1883 } else {
1884 // If the index width is smaller than the pointer width, only add the
1885 // value to the low bits.
1886 assert(IndexWidth < BitWidth &&
1887 "Index width can't be larger than pointer width");
1888 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1889 }
1890 };
1891
1893 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1894 // TrailZ can only become smaller, short-circuit if we hit zero.
1895 if (Known.isUnknown())
1896 break;
1897
1898 Value *Index = I->getOperand(i);
1899
1900 // Handle case when index is zero.
1901 Constant *CIndex = dyn_cast<Constant>(Index);
1902 if (CIndex && CIndex->isNullValue())
1903 continue;
1904
1905 if (StructType *STy = GTI.getStructTypeOrNull()) {
1906 // Handle struct member offset arithmetic.
1907
1908 assert(CIndex &&
1909 "Access to structure field must be known at compile time");
1910
1911 if (CIndex->getType()->isVectorTy())
1912 Index = CIndex->getSplatValue();
1913
1914 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1915 const StructLayout *SL = Q.DL.getStructLayout(STy);
1916 uint64_t Offset = SL->getElementOffset(Idx);
1917 AccConstIndices += Offset;
1918 continue;
1919 }
1920
1921 // Handle array index arithmetic.
1922 Type *IndexedTy = GTI.getIndexedType();
1923 if (!IndexedTy->isSized()) {
1924 Known.resetAll();
1925 break;
1926 }
1927
1928 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1929 uint64_t StrideInBytes = Stride.getKnownMinValue();
1930 if (!Stride.isScalable()) {
1931 // Fast path for constant offset.
1932 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1933 AccConstIndices +=
1934 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1935 continue;
1936 }
1937 }
1938
1939 KnownBits IndexBits =
1940 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1941 KnownBits ScalingFactor(IndexWidth);
1942 // Multiply by current sizeof type.
1943 // &A[i] == A + i * sizeof(*A[i]).
1944 if (Stride.isScalable()) {
1945 // For scalable types the only thing we know about sizeof is
1946 // that this is a multiple of the minimum size.
1947 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1948 } else {
1949 ScalingFactor =
1950 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1951 }
1952 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1953 }
1954 if (!Known.isUnknown() && !AccConstIndices.isZero())
1955 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1956 break;
1957 }
1958 case Instruction::PHI: {
1959 const PHINode *P = cast<PHINode>(I);
1960 BinaryOperator *BO = nullptr;
1961 Value *Start = nullptr, *Step = nullptr;
1962 KnownBits &KnownStart = Known2;
1963 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1964 // Handle the case of a simple two-predecessor recurrence PHI.
1965 // There's a lot more that could theoretically be done here, but
1966 // this is sufficient to catch some interesting cases.
1967 unsigned Opcode = BO->getOpcode();
1968
1969 switch (Opcode) {
1970 // If this is a shift recurrence, we know the bits being shifted in. We
1971 // can combine that with information about the start value of the
1972 // recurrence to conclude facts about the result. If this is a udiv
1973 // recurrence, we know that the result can never exceed either the
1974 // numerator or the start value, whichever is greater.
1975 case Instruction::LShr:
1976 case Instruction::AShr:
1977 case Instruction::Shl:
1978 case Instruction::UDiv:
1979 if (BO->getOperand(0) != I)
1980 break;
1981 [[fallthrough]];
1982
1983 // For a urem recurrence, the result can never exceed the start value. The
1984 // phi could either be the numerator or the denominator.
1985 case Instruction::URem: {
1986 // We have matched a recurrence of the form:
1987 // %iv = [R, %entry], [%iv.next, %backedge]
1988 // %iv.next = shift_op %iv, L
1989
1990 // Recurse with the phi context to avoid concern about whether facts
1991 // inferred hold at original context instruction. TODO: It may be
1992 // correct to use the original context. IF warranted, explore and
1993 // add sufficient tests to cover.
1995 RecQ.CtxI = P;
1996 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1997 switch (Opcode) {
1998 case Instruction::Shl:
1999 // A shl recurrence will only increase the tailing zeros
2000 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
2001 break;
2002 case Instruction::LShr:
2003 case Instruction::UDiv:
2004 case Instruction::URem:
2005 // lshr, udiv, and urem recurrences will preserve the leading zeros of
2006 // the start value.
2007 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2008 break;
2009 case Instruction::AShr:
2010 // An ashr recurrence will extend the initial sign bit
2011 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2012 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2013 break;
2014 }
2015 break;
2016 }
2017
2018 case Instruction::And: {
2019 // Bits that are zero in the start value stay zero, and bits that are
2020 // one in both the start value and the step stay one.
2021 KnownBits KnownStep(BitWidth);
2022 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
2023 KnownStart, KnownStep, Q, Depth);
2024 Known.Zero |= KnownStart.Zero;
2025 Known.One |= KnownStart.One & KnownStep.One;
2026 break;
2027 }
2028
2029 case Instruction::Or: {
2030 // Bits that are zero in both the start value and the step stay zero,
2031 // and bits that are one in the start value stay one.
2032 KnownBits KnownStep(BitWidth);
2033 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
2034 KnownStart, KnownStep, Q, Depth);
2035 Known.Zero |= KnownStart.Zero & KnownStep.Zero;
2036 Known.One |= KnownStart.One;
2037 break;
2038 }
2039
2040 // Check for operations that have the property that if
2041 // both their operands have low zero bits, the result
2042 // will have low zero bits.
2043 case Instruction::Add:
2044 case Instruction::Sub:
2045 case Instruction::Mul: {
2046 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
2047 // zero bits.
2048 KnownBits KnownStep(BitWidth);
2049 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
2050 KnownStart, KnownStep, Q, Depth);
2051
2052 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
2053 KnownStep.countMinTrailingZeros()));
2054
2055 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
2056 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
2057 break;
2058
2059 switch (Opcode) {
2060 // If initial value of recurrence is nonnegative, and we are adding
2061 // a nonnegative number with nsw, the result can only be nonnegative
2062 // or poison value regardless of the number of times we execute the
2063 // add in phi recurrence. If initial value is negative and we are
2064 // adding a negative number with nsw, the result can only be
2065 // negative or poison value. Similar arguments apply to sub and mul.
2066 //
2067 // (add non-negative, non-negative) --> non-negative
2068 // (add negative, negative) --> negative
2069 case Instruction::Add: {
2070 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2071 Known.makeNonNegative();
2072 else if (KnownStart.isNegative() && KnownStep.isNegative())
2073 Known.makeNegative();
2074 break;
2075 }
2076
2077 // (sub nsw non-negative, negative) --> non-negative
2078 // (sub nsw negative, non-negative) --> negative
2079 case Instruction::Sub: {
2080 if (BO->getOperand(0) != I)
2081 break;
2082 if (KnownStart.isNonNegative() && KnownStep.isNegative())
2083 Known.makeNonNegative();
2084 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
2085 Known.makeNegative();
2086 break;
2087 }
2088
2089 // (mul nsw non-negative, non-negative) --> non-negative
2090 case Instruction::Mul:
2091 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2092 Known.makeNonNegative();
2093 break;
2094
2095 default:
2096 break;
2097 }
2098 break;
2099 }
2100
2101 default:
2102 break;
2103 }
2104 } else {
2105 IntrinsicInst *II = nullptr;
2106 GEPOperator *GEP = nullptr;
2107 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
2108 // %iv = [<Start>, %entry], [%iv.next, %backedge]
2109 //
2110 // %iv.next = <II>(%iv, <Step>)
2111 // or
2112 // %iv.next = <II>(<Step>, %iv)
2113 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
2114 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
2115 KnownBits KnownStep(BitWidth);
2117 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2118
2119 if (IntrinsicID == Intrinsic::umin) {
2120 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2121 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2122 KnownStep.countMinLeadingOnes()));
2123 } else {
2124 // umax
2125 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2126 KnownStep.countMinLeadingZeros()));
2127 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2128 }
2129 }
2130 } else if (Known.isUnknown() && I->getType()->isPointerTy() &&
2132 GEP->getPointerOperand() == P) {
2133 // Handle a pointer induction variable, whose step is a getelementptr:
2134 // %p = phi ptr [ %start, %preheader ], [ %next, %latch ]
2135 // %next = getelementptr <ty>, ptr %p, <indices>
2136 // Every value %p takes is %start plus a whole number of steps, and
2137 // tz(a + b) >= min(tz(a), tz(b)), so the trailing zeros of %p - and
2138 // hence its alignment - are at least the smaller of those of %start and
2139 // of the step.
2140
2141 // Evaluate the start value on its own incoming edge.
2142 unsigned StartIdx = P->getIncomingValue(0) == Start ? 0 : 1;
2144 RecQ.CtxI = P->getIncomingBlock(StartIdx)->getTerminator();
2145 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
2146 Known.Zero.setLowBits(
2147 std::min(KnownStart.countMinTrailingZeros(),
2148 Log2(GEP->getMaxPreservedAlignment(Q.DL))));
2149 }
2150 }
2151
2152 // Unreachable blocks may have zero-operand PHI nodes.
2153 if (P->getNumIncomingValues() == 0)
2154 break;
2155
2156 // Otherwise take the unions of the known bit sets of the operands,
2157 // taking conservative care to avoid excessive recursion.
2158 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2159 // Skip if every incoming value references to ourself.
2160 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2161 break;
2162
2163 Known.setAllConflict();
2164 for (const Use &U : P->operands()) {
2165 Value *IncValue;
2166 const PHINode *CtxPhi;
2167 Instruction *CtxI;
2168 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2169 // Skip direct self references.
2170 if (IncValue == P)
2171 continue;
2172
2173 // Change the context instruction to the "edge" that flows into the
2174 // phi. This is important because that is where the value is actually
2175 // "evaluated" even though it is used later somewhere else. (see also
2176 // D69571).
2178
2179 Known2 = KnownBits(BitWidth);
2180
2181 // Recurse, but cap the recursion to one level, because we don't
2182 // want to waste time spinning around in loops.
2183 // TODO: See if we can base recursion limiter on number of incoming phi
2184 // edges so we don't overly clamp analysis.
2185 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2187
2188 // See if we can further use a conditional branch into the phi
2189 // to help us determine the range of the value.
2190 if (!Known2.isConstant()) {
2192 Value *RHSValue = nullptr;
2193 BasicBlock *TrueSucc, *FalseSucc;
2194 if (match(
2195 RecQ.CtxI,
2196 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_Value(RHSValue)),
2197 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2198 // Check for cases of duplicate successors.
2199 if ((TrueSucc == CtxPhi->getParent()) !=
2200 (FalseSucc == CtxPhi->getParent())) {
2201 // If we're using the false successor, invert the predicate.
2202 if (FalseSucc == CtxPhi->getParent())
2204 // Get the knownbits implied by the incoming phi condition.
2205 KnownBits RHSKnown = computeKnownBits(
2206 RHSValue, DemandedElts, RecQ, MaxAnalysisRecursionDepth - 1);
2207 if (!RHSKnown.isUnknown()) {
2209 RHSKnown, /*IsSigned=*/ICmpInst::isSigned(Pred));
2210 auto CR = ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
2211 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2212 // We can have conflicts here if we are analyzing deadcode (its
2213 // impossible for us reach this BB based the icmp).
2214 if (KnownUnion.hasConflict()) {
2215 // No reason to continue analyzing in a known dead region, so
2216 // just resetAll and break. This will cause us to also exit
2217 // the outer loop.
2218 Known.resetAll();
2219 break;
2220 }
2221 Known2 = KnownUnion;
2222 }
2223 }
2224 }
2225 }
2226
2227 Known = Known.intersectWith(Known2);
2228 // If all bits have been ruled out, there's no need to check
2229 // more operands.
2230 if (Known.isUnknown())
2231 break;
2232 }
2233 }
2234 break;
2235 }
2236 case Instruction::Call:
2237 case Instruction::Invoke: {
2238 // If range metadata is attached to this call, set known bits from that,
2239 // and then intersect with known bits based on other properties of the
2240 // function.
2241 if (MDNode *MD =
2242 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2244
2245 const auto *CB = cast<CallBase>(I);
2246
2247 if (std::optional<ConstantRange> Range = CB->getRange())
2248 Known = Known.unionWith(Range->toKnownBits());
2249
2250 if (const Value *RV = CB->getReturnedArgOperand()) {
2251 if (RV->getType() == I->getType()) {
2252 computeKnownBits(RV, Known2, Q, Depth + 1);
2253 Known = Known.unionWith(Known2);
2254 // If the function doesn't return properly for all input values
2255 // (e.g. unreachable exits) then there might be conflicts between the
2256 // argument value and the range metadata. Simply discard the known bits
2257 // in case of conflicts.
2258 if (Known.hasConflict())
2259 Known.resetAll();
2260 }
2261 }
2262 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2263 switch (II->getIntrinsicID()) {
2264 default:
2265 break;
2266 case Intrinsic::abs: {
2267 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2268 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2269 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2270 break;
2271 }
2272 case Intrinsic::bitreverse:
2273 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2274 Known = Known.unionWith(Known2.reverseBits());
2275 break;
2276 case Intrinsic::bswap:
2277 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2278 Known = Known.unionWith(Known2.byteSwap());
2279 break;
2280 case Intrinsic::ctlz: {
2281 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2282 bool ZeroIsPoison = match(II->getArgOperand(1), m_One());
2283 Known = Known.unionWith(Known2.ctlz(ZeroIsPoison));
2284 break;
2285 }
2286 case Intrinsic::cttz: {
2287 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2288 // If we have a known 1, its position is our upper bound.
2289 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2290 // If this call is poison for 0 input, the result will be less than 2^n.
2291 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2292 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2293 unsigned LowBits = llvm::bit_width(PossibleTZ);
2294 Known.Zero.setBitsFrom(LowBits);
2295 break;
2296 }
2297 case Intrinsic::ctpop: {
2298 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2299 // We can bound the space the count needs. Also, bits known to be zero
2300 // can't contribute to the population.
2301 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2302 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2303 Known.Zero.setBitsFrom(LowBits);
2304 // TODO: we could bound KnownOne using the lower bound on the number
2305 // of bits which might be set provided by popcnt KnownOne2.
2306 break;
2307 }
2308 case Intrinsic::fshr:
2309 case Intrinsic::fshl: {
2310 const APInt *SA;
2311 if (!match(I->getOperand(2), m_APInt(SA)))
2312 break;
2313
2314 KnownBits Known3(BitWidth);
2315 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2316 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2317 Known = II->getIntrinsicID() == Intrinsic::fshl
2318 ? KnownBits::fshl(Known2, Known3, *SA)
2319 : KnownBits::fshr(Known2, Known3, *SA);
2320 break;
2321 }
2322 case Intrinsic::clmul:
2323 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2324 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2325 Known = KnownBits::clmul(Known, Known2);
2326 break;
2327 case Intrinsic::pext:
2328 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2329 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2330 Known = KnownBits::pext(Known, Known2);
2331 break;
2332 case Intrinsic::pdep:
2333 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2334 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2335 Known = KnownBits::pdep(Known, Known2);
2336 break;
2337 case Intrinsic::smulh:
2338 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2339 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2340 Known = KnownBits::mulhs(Known, Known2);
2341 break;
2342 case Intrinsic::umulh:
2343 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2344 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2345 Known = KnownBits::mulhu(Known, Known2);
2346 break;
2347 case Intrinsic::uadd_sat:
2348 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2349 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2350 Known = KnownBits::uadd_sat(Known, Known2);
2351 break;
2352 case Intrinsic::usub_sat:
2353 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2354 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2355 Known = KnownBits::usub_sat(Known, Known2);
2356 break;
2357 case Intrinsic::sadd_sat:
2358 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2359 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2360 Known = KnownBits::sadd_sat(Known, Known2);
2361 break;
2362 case Intrinsic::ssub_sat:
2363 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2364 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2365 Known = KnownBits::ssub_sat(Known, Known2);
2366 break;
2367 // Vec reverse preserves bits from input vec.
2368 case Intrinsic::vector_reverse:
2369 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2370 Depth + 1);
2371 break;
2372 // for min/max/and/or reduce, any bit common to each element in the
2373 // input vec is set in the output.
2374 case Intrinsic::vector_reduce_and:
2375 case Intrinsic::vector_reduce_or:
2376 case Intrinsic::vector_reduce_umax:
2377 case Intrinsic::vector_reduce_umin:
2378 case Intrinsic::vector_reduce_smax:
2379 case Intrinsic::vector_reduce_smin:
2380 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2381 break;
2382 case Intrinsic::vector_reduce_xor: {
2383 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2384 // The zeros common to all vecs are zero in the output.
2385 // If the number of elements is odd, then the common ones remain. If the
2386 // number of elements is even, then the common ones becomes zeros.
2387 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2388 // Even, so the ones become zeros.
2389 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2390 if (EvenCnt)
2391 Known.Zero |= Known.One;
2392 // Maybe even element count so need to clear ones.
2393 if (VecTy->isScalableTy() || EvenCnt)
2394 Known.One.clearAllBits();
2395 break;
2396 }
2397 case Intrinsic::vector_reduce_add: {
2398 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2399 if (!VecTy)
2400 break;
2401 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2402 Known = Known.reduceAdd(VecTy->getNumElements());
2403 break;
2404 }
2405 case Intrinsic::umin:
2406 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2407 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2408 Known = KnownBits::umin(Known, Known2);
2409 break;
2410 case Intrinsic::umax:
2411 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2412 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2413 Known = KnownBits::umax(Known, Known2);
2414 break;
2415 case Intrinsic::smin:
2416 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2417 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2418 Known = KnownBits::smin(Known, Known2);
2420 break;
2421 case Intrinsic::smax:
2422 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2423 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2424 Known = KnownBits::smax(Known, Known2);
2426 break;
2427 case Intrinsic::ptrmask: {
2428 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2429
2430 const Value *Mask = I->getOperand(1);
2431 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2432 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2433 // TODO: 1-extend would be more precise.
2434 Known &= Known2.anyextOrTrunc(BitWidth);
2435 break;
2436 }
2437 case Intrinsic::x86_sse42_crc32_64_64:
2438 Known.Zero.setBitsFrom(32);
2439 break;
2440 case Intrinsic::x86_ssse3_phadd_d_128:
2441 case Intrinsic::x86_ssse3_phadd_w_128:
2442 case Intrinsic::x86_avx2_phadd_d:
2443 case Intrinsic::x86_avx2_phadd_w: {
2445 I, DemandedElts, Q, Depth,
2446 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2447 return KnownBits::add(KnownLHS, KnownRHS);
2448 });
2449 break;
2450 }
2451 case Intrinsic::x86_ssse3_phadd_sw_128:
2452 case Intrinsic::x86_avx2_phadd_sw: {
2454 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2455 break;
2456 }
2457 case Intrinsic::x86_ssse3_phsub_d_128:
2458 case Intrinsic::x86_ssse3_phsub_w_128:
2459 case Intrinsic::x86_avx2_phsub_d:
2460 case Intrinsic::x86_avx2_phsub_w: {
2462 I, DemandedElts, Q, Depth,
2463 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2464 return KnownBits::sub(KnownLHS, KnownRHS);
2465 });
2466 break;
2467 }
2468 case Intrinsic::x86_ssse3_phsub_sw_128:
2469 case Intrinsic::x86_avx2_phsub_sw: {
2471 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2472 break;
2473 }
2474 case Intrinsic::riscv_vsetvli:
2475 case Intrinsic::riscv_vsetvlimax: {
2476 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2477 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2479 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2480 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2481 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2482 uint64_t MaxVLEN =
2483 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2484 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2485
2486 // Result of vsetvli must be not larger than AVL.
2487 if (HasAVL)
2488 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2489 MaxVL = std::min(MaxVL, CI->getZExtValue());
2490
2491 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2492 if (BitWidth > KnownZeroFirstBit)
2493 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2494 break;
2495 }
2496 case Intrinsic::amdgcn_mbcnt_hi:
2497 case Intrinsic::amdgcn_mbcnt_lo: {
2498 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2499 // most 31 + src1.
2500 KnownBits MbcntKnown(BitWidth);
2501 MbcntKnown.Zero.setBitsFrom(
2502 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2503 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2504 Known = Known.unionWith(KnownBits::add(MbcntKnown, Known2));
2505 break;
2506 }
2507 case Intrinsic::vscale: {
2508 if (!II->getParent() || !II->getFunction())
2509 break;
2510
2511 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2512 break;
2513 }
2514 case Intrinsic::stepvector: {
2515 auto *VecTy = cast<VectorType>(II->getType());
2516 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2517 if (!isUIntN(BitWidth, MinNumElts))
2518 break;
2519
2520 bool Overflow = false;
2521 APInt MaxNumElts(BitWidth, MinNumElts);
2522 if (VecTy->isScalableTy()) {
2523 if (!II->getParent() || !II->getFunction())
2524 break;
2525 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2527 .umul_ov(MaxNumElts, Overflow);
2528 }
2529
2530 // Give up if the lane count could wrap. Stepvector truncates lane
2531 // indices that do not fit in the element type.
2532 if (Overflow)
2533 break;
2534
2535 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2536 break;
2537 }
2538 }
2539 }
2540 break;
2541 }
2542 case Instruction::ShuffleVector: {
2543 if (auto *Splat = getSplatValue(I)) {
2545 break;
2546 }
2547
2548 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2549 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2550 if (!Shuf) {
2551 Known.resetAll();
2552 return;
2553 }
2554 // For undef elements, we don't know anything about the common state of
2555 // the shuffle result.
2556 APInt DemandedLHS, DemandedRHS;
2557 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2558 Known.resetAll();
2559 return;
2560 }
2561 Known.setAllConflict();
2562 if (!!DemandedLHS) {
2563 const Value *LHS = Shuf->getOperand(0);
2564 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2565 // If we don't know any bits, early out.
2566 if (Known.isUnknown())
2567 break;
2568 }
2569 if (!!DemandedRHS) {
2570 const Value *RHS = Shuf->getOperand(1);
2571 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2572 Known = Known.intersectWith(Known2);
2573 }
2574 break;
2575 }
2576 case Instruction::InsertElement: {
2577 if (isa<ScalableVectorType>(I->getType())) {
2578 Known.resetAll();
2579 return;
2580 }
2581 const Value *Vec = I->getOperand(0);
2582 const Value *Elt = I->getOperand(1);
2583 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2584 unsigned NumElts = DemandedElts.getBitWidth();
2585 APInt DemandedVecElts = DemandedElts;
2586 bool NeedsElt = true;
2587 // If we know the index we are inserting too, clear it from Vec check.
2588 if (CIdx && CIdx->getValue().ult(NumElts)) {
2589 DemandedVecElts.clearBit(CIdx->getZExtValue());
2590 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2591 }
2592
2593 Known.setAllConflict();
2594 if (NeedsElt) {
2595 computeKnownBits(Elt, Known, Q, Depth + 1);
2596 // If we don't know any bits, early out.
2597 if (Known.isUnknown())
2598 break;
2599 }
2600
2601 if (!DemandedVecElts.isZero()) {
2602 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2603 Known = Known.intersectWith(Known2);
2604 }
2605 break;
2606 }
2607 case Instruction::ExtractElement: {
2608 // Look through extract element. If the index is non-constant or
2609 // out-of-range demand all elements, otherwise just the extracted element.
2610 const Value *Vec = I->getOperand(0);
2611 const Value *Idx = I->getOperand(1);
2612 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2613 if (isa<ScalableVectorType>(Vec->getType())) {
2614 // FIXME: there's probably *something* we can do with scalable vectors
2615 Known.resetAll();
2616 break;
2617 }
2618 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2619 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2620 if (CIdx && CIdx->getValue().ult(NumElts))
2621 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2622 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2623 break;
2624 }
2625 case Instruction::ExtractValue:
2626 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2628 if (EVI->getNumIndices() != 1) break;
2629 if (EVI->getIndices()[0] == 0) {
2630 switch (II->getIntrinsicID()) {
2631 default: break;
2632 case Intrinsic::uadd_with_overflow:
2633 case Intrinsic::sadd_with_overflow:
2635 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2636 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2637 break;
2638 case Intrinsic::usub_with_overflow:
2639 case Intrinsic::ssub_with_overflow:
2641 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2642 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2643 break;
2644 case Intrinsic::umul_with_overflow:
2645 case Intrinsic::smul_with_overflow:
2646 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2647 false, DemandedElts, Known, Known2, Q, Depth);
2648 break;
2649 }
2650 }
2651 }
2652 break;
2653 case Instruction::Freeze:
2654 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2655 Depth + 1))
2656 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2657 break;
2658 }
2659}
2660
2661/// Determine which bits of V are known to be either zero or one and return
2662/// them.
2663KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2664 const SimplifyQuery &Q, unsigned Depth) {
2665 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2666 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2667 return Known;
2668}
2669
2670/// Determine which bits of V are known to be either zero or one and return
2671/// them.
2673 unsigned Depth) {
2674 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2676 return Known;
2677}
2678
2679/// Determine which bits of V are known to be either zero or one and return
2680/// them in the Known bit set.
2681///
2682/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2683/// we cannot optimize based on the assumption that it is zero without changing
2684/// it to be an explicit zero. If we don't change it to zero, other code could
2685/// optimized based on the contradictory assumption that it is non-zero.
2686/// Because instcombine aggressively folds operations with undef args anyway,
2687/// this won't lose us code quality.
2688///
2689/// This function is defined on values with integer type, values with pointer
2690/// type, and vectors of integers. In the case
2691/// where V is a vector, known zero, and known one values are the
2692/// same width as the vector element, and the bit is set only if it is true
2693/// for all of the demanded elements in the vector specified by DemandedElts.
2694void computeKnownBits(const Value *V, const APInt &DemandedElts,
2695 KnownBits &Known, const SimplifyQuery &Q,
2696 unsigned Depth) {
2697 if (!DemandedElts) {
2698 // No demanded elts, better to assume we don't know anything.
2699 Known.resetAll();
2700 return;
2701 }
2702
2703 assert(V && "No Value?");
2704 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2705
2706#ifndef NDEBUG
2707 Type *Ty = V->getType();
2708 unsigned BitWidth = Known.getBitWidth();
2709
2710 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2711 "Not integer or pointer type!");
2712
2713 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2714 assert(
2715 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2716 "DemandedElt width should equal the fixed vector number of elements");
2717 } else {
2718 assert(DemandedElts == APInt(1, 1) &&
2719 "DemandedElt width should be 1 for scalars or scalable vectors");
2720 }
2721
2722 Type *ScalarTy = Ty->getScalarType();
2723 if (ScalarTy->isPointerTy()) {
2724 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2725 "V and Known should have same BitWidth");
2726 } else {
2727 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2728 "V and Known should have same BitWidth");
2729 }
2730#endif
2731
2732 const APInt *C;
2733 if (match(V, m_APInt(C))) {
2734 // We know all of the bits for a scalar constant or a splat vector constant!
2736 return;
2737 }
2738 // Null and aggregate-zero are all-zeros.
2740 Known.setAllZero();
2741 return;
2742 }
2743 // Handle a constant vector by taking the intersection of the known bits of
2744 // each element.
2746 assert(!isa<ScalableVectorType>(V->getType()));
2747 // We know that CDV must be a vector of integers. Take the intersection of
2748 // each element.
2749 Known.setAllConflict();
2750 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2751 if (!DemandedElts[i])
2752 continue;
2753 APInt Elt = CDV->getElementAsAPInt(i);
2754 Known.Zero &= ~Elt;
2755 Known.One &= Elt;
2756 }
2757 if (Known.hasConflict())
2758 Known.resetAll();
2759 return;
2760 }
2761
2762 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2763 assert(!isa<ScalableVectorType>(V->getType()));
2764 // We know that CV must be a vector of integers. Take the intersection of
2765 // each element.
2766 Known.setAllConflict();
2767 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2768 if (!DemandedElts[i])
2769 continue;
2770 Constant *Element = CV->getAggregateElement(i);
2771 if (isa<PoisonValue>(Element))
2772 continue;
2773 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2774 if (!ElementCI) {
2775 Known.resetAll();
2776 return;
2777 }
2778 const APInt &Elt = ElementCI->getValue();
2779 Known.Zero &= ~Elt;
2780 Known.One &= Elt;
2781 }
2782 if (Known.hasConflict())
2783 Known.resetAll();
2784 return;
2785 }
2786
2787 // Start out not knowing anything.
2788 Known.resetAll();
2789
2790 // We can't imply anything about undefs.
2791 if (isa<UndefValue>(V))
2792 return;
2793
2794 // There's no point in looking through other users of ConstantData for
2795 // assumptions. Confirm that we've handled them all.
2796 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2797
2798 if (const auto *A = dyn_cast<Argument>(V))
2799 if (std::optional<ConstantRange> Range = A->getRange())
2800 Known = Range->toKnownBits();
2801
2802 // All recursive calls that increase depth must come after this.
2804 return;
2805
2806 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2807 // the bits of its aliasee.
2808 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2809 if (!GA->isInterposable())
2810 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2811 return;
2812 }
2813
2814 if (const Operator *I = dyn_cast<Operator>(V))
2815 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2816 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2817 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2818 Known = CR->toKnownBits();
2819 }
2820
2821 // Aligned pointers have trailing zeros - refine Known.Zero set
2822 if (isa<PointerType>(V->getType())) {
2823 Align Alignment = V->getPointerAlignment(Q.DL);
2824 Known.Zero.setLowBits(Log2(Alignment));
2825 }
2826
2827 // computeKnownBitsFromContext strictly refines Known.
2828 // Therefore, we run them after computeKnownBitsFromOperator.
2829
2830 // Check whether we can determine known bits from context such as assumes.
2832}
2833
2834/// Try to detect a recurrence that the value of the induction variable is
2835/// always a power of two (or zero).
2836static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2837 SimplifyQuery &Q, unsigned Depth) {
2838 BinaryOperator *BO = nullptr;
2839 Value *Start = nullptr, *Step = nullptr;
2840 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2841 return false;
2842
2843 // Initial value must be a power of two.
2844 for (const Use &U : PN->operands()) {
2845 if (U.get() == Start) {
2846 // Initial value comes from a different BB, need to adjust context
2847 // instruction for analysis.
2848 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2849 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2850 return false;
2851 }
2852 }
2853
2854 // Except for Mul, the induction variable must be on the left side of the
2855 // increment expression, otherwise its value can be arbitrary.
2856 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2857 return false;
2858
2859 Q.CtxI = BO->getParent()->getTerminator();
2860 switch (BO->getOpcode()) {
2861 case Instruction::Mul:
2862 // Power of two is closed under multiplication.
2863 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2864 Q.IIQ.hasNoSignedWrap(BO)) &&
2865 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2866 case Instruction::SDiv:
2867 // Start value must not be signmask for signed division, so simply being a
2868 // power of two is not sufficient, and it has to be a constant.
2869 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2870 return false;
2871 [[fallthrough]];
2872 case Instruction::UDiv:
2873 // Divisor must be a power of two.
2874 // If OrZero is false, cannot guarantee induction variable is non-zero after
2875 // division, same for Shr, unless it is exact division.
2876 return (OrZero || Q.IIQ.isExact(BO)) &&
2877 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2878 case Instruction::Shl:
2879 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2880 case Instruction::AShr:
2881 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2882 return false;
2883 [[fallthrough]];
2884 case Instruction::LShr:
2885 return OrZero || Q.IIQ.isExact(BO);
2886 default:
2887 return false;
2888 }
2889}
2890
2891/// Return true if we can infer that \p V is known to be a power of 2 from
2892/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2893static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2894 const Value *Cond,
2895 bool CondIsTrue) {
2897 const APInt *RHSC;
2898 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2899 return false;
2900 if (!CondIsTrue)
2902 // ctpop(V) u< 2
2903 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2904 return true;
2905 // ctpop(V) == 1
2906 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2907}
2908
2909/// Return true if the given value is known to have exactly one
2910/// bit set when defined. For vectors return true if every element is known to
2911/// be a power of two when defined. Supports values with integer or pointer
2912/// types and vectors of integers.
2913bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2914 const SimplifyQuery &Q, unsigned Depth) {
2915 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2916
2917 if (isa<Constant>(V))
2918 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2919
2920 // i1 is by definition a power of 2 or zero.
2921 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2922 return true;
2923
2924 // Try to infer from assumptions.
2925 if (Q.AC && Q.CtxI) {
2926 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2927 if (!AssumeVH)
2928 continue;
2929 CallInst *I = cast<CallInst>(AssumeVH);
2930 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2931 /*CondIsTrue=*/true) &&
2933 return true;
2934 }
2935 }
2936
2937 // Handle dominating conditions.
2938 if (Q.DC && Q.CtxI && Q.DT) {
2939 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2940 Value *Cond = BI->getCondition();
2941
2942 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2944 /*CondIsTrue=*/true) &&
2945 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2946 return true;
2947
2948 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2950 /*CondIsTrue=*/false) &&
2951 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2952 return true;
2953 }
2954 }
2955
2956 auto *I = dyn_cast<Instruction>(V);
2957 if (!I)
2958 return false;
2959
2960 if (Q.CtxI && match(V, m_VScale())) {
2961 const Function *F = Q.CtxI->getFunction();
2962 // The vscale_range indicates vscale is a power-of-two.
2963 return F->hasFnAttribute(Attribute::VScaleRange);
2964 }
2965
2966 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2967 // it is shifted off the end then the result is undefined.
2968 if (match(I, m_Shl(m_One(), m_Value())))
2969 return true;
2970
2971 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2972 // the bottom. If it is shifted off the bottom then the result is undefined.
2973 if (match(I, m_LShr(m_SignMask(), m_Value())))
2974 return true;
2975
2976 // The remaining tests are all recursive, so bail out if we hit the limit.
2978 return false;
2979
2980 switch (I->getOpcode()) {
2981 case Instruction::ZExt:
2982 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2983 case Instruction::Trunc:
2984 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2985 case Instruction::Shl:
2986 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2987 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2988 return false;
2989 case Instruction::LShr:
2990 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2991 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2992 return false;
2993 case Instruction::UDiv:
2995 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2996 return false;
2997 case Instruction::Mul:
2998 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2999 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
3000 (OrZero || isKnownNonZero(I, Q, Depth));
3001 case Instruction::And:
3002 // A power of two and'd with anything is a power of two or zero.
3003 if (OrZero &&
3004 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
3005 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
3006 return true;
3007 // X & (-X) is always a power of two or zero.
3008 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
3009 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
3010 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
3011 return false;
3012 case Instruction::Add: {
3013 // Adding a power-of-two or zero to the same power-of-two or zero yields
3014 // either the original power-of-two, a larger power-of-two or zero.
3016 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
3017 Q.IIQ.hasNoSignedWrap(VOBO)) {
3018 if (match(I->getOperand(0),
3019 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
3020 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
3021 return true;
3022 if (match(I->getOperand(1),
3023 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
3024 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
3025 return true;
3026
3027 unsigned BitWidth = V->getType()->getScalarSizeInBits();
3028 KnownBits LHSBits(BitWidth);
3029 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
3030
3031 KnownBits RHSBits(BitWidth);
3032 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
3033 // If i8 V is a power of two or zero:
3034 // ZeroBits: 1 1 1 0 1 1 1 1
3035 // ~ZeroBits: 0 0 0 1 0 0 0 0
3036 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
3037 // If OrZero isn't set, we cannot give back a zero result.
3038 // Make sure either the LHS or RHS has a bit set.
3039 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
3040 return true;
3041 }
3042
3043 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
3044 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
3045 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
3046 return true;
3047 return false;
3048 }
3049 case Instruction::Select:
3050 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
3051 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
3052 case Instruction::PHI: {
3053 // A PHI node is power of two if all incoming values are power of two, or if
3054 // it is an induction variable where in each step its value is a power of
3055 // two.
3056 auto *PN = cast<PHINode>(I);
3058
3059 // Check if it is an induction variable and always power of two.
3060 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
3061 return true;
3062
3063 // Recursively check all incoming values. Limit recursion to 2 levels, so
3064 // that search complexity is limited to number of operands^2.
3065 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3066 return llvm::all_of(PN->operands(), [&](const Use &U) {
3067 // Value is power of 2 if it is coming from PHI node itself by induction.
3068 if (U.get() == PN)
3069 return true;
3070
3071 // Change the context instruction to the incoming block where it is
3072 // evaluated.
3073 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3074 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
3075 });
3076 }
3077 case Instruction::Invoke:
3078 case Instruction::Call: {
3079 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3080 switch (II->getIntrinsicID()) {
3081 case Intrinsic::umax:
3082 case Intrinsic::smax:
3083 case Intrinsic::umin:
3084 case Intrinsic::smin:
3085 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
3086 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3087 // bswap/bitreverse just move around bits, but don't change any 1s/0s
3088 // thus dont change pow2/non-pow2 status.
3089 case Intrinsic::bitreverse:
3090 case Intrinsic::bswap:
3091 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3092 case Intrinsic::fshr:
3093 case Intrinsic::fshl:
3094 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
3095 if (II->getArgOperand(0) == II->getArgOperand(1))
3096 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
3097 break;
3098 case Intrinsic::riscv_vsetvlimax:
3099 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
3100 // for any valid vtype, so it is a power of two regardless of OrZero.
3101 return true;
3102 case Intrinsic::read_register:
3103 case Intrinsic::read_volatile_register: {
3104 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
3105 // of two, so it is a power of two regardless of OrZero.
3106 const Module *M = II->getModule();
3107 if (!M || !M->getTargetTriple().isRISCV())
3108 break;
3109 return isReadVLENB(*II);
3110 }
3111 default:
3112 break;
3113 }
3114 }
3115 return false;
3116 }
3117 default:
3118 return false;
3119 }
3120}
3121
3122/// Test whether a GEP's result is known to be non-null.
3123///
3124/// Uses properties inherent in a GEP to try to determine whether it is known
3125/// to be non-null.
3126///
3127/// Currently this routine does not support vector GEPs.
3128static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
3129 unsigned Depth) {
3130 const Function *F = nullptr;
3131 if (const Instruction *I = dyn_cast<Instruction>(GEP))
3132 F = I->getFunction();
3133
3134 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
3135 // may be null iff the base pointer is null and the offset is zero.
3136 if (!GEP->hasNoUnsignedWrap() &&
3137 !(GEP->isInBounds() &&
3138 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3139 return false;
3140
3141 // FIXME: Support vector-GEPs.
3142 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3143
3144 // If the base pointer is non-null, we cannot walk to a null address with an
3145 // inbounds GEP in address space zero.
3146 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3147 return true;
3148
3149 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3150 // If so, then the GEP cannot produce a null pointer, as doing so would
3151 // inherently violate the inbounds contract within address space zero.
3153 GTI != GTE; ++GTI) {
3154 // Struct types are easy -- they must always be indexed by a constant.
3155 if (StructType *STy = GTI.getStructTypeOrNull()) {
3156 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3157 unsigned ElementIdx = OpC->getZExtValue();
3158 const StructLayout *SL = Q.DL.getStructLayout(STy);
3159 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3160 if (ElementOffset > 0)
3161 return true;
3162 continue;
3163 }
3164
3165 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3166 if (GTI.getSequentialElementStride(Q.DL).isZero())
3167 continue;
3168
3169 // Fast path the constant operand case both for efficiency and so we don't
3170 // increment Depth when just zipping down an all-constant GEP.
3171 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3172 if (!OpC->isZero())
3173 return true;
3174 continue;
3175 }
3176
3177 // We post-increment Depth here because while isKnownNonZero increments it
3178 // as well, when we pop back up that increment won't persist. We don't want
3179 // to recurse 10k times just because we have 10k GEP operands. We don't
3180 // bail completely out because we want to handle constant GEPs regardless
3181 // of depth.
3183 continue;
3184
3185 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3186 return true;
3187 }
3188
3189 return false;
3190}
3191
3193 const Instruction *CtxI,
3194 const DominatorTree *DT) {
3195 assert(!isa<Constant>(V) && "Called for constant?");
3196
3197 if (!CtxI || !DT)
3198 return false;
3199
3200 unsigned NumUsesExplored = 0;
3201 for (auto &U : V->uses()) {
3202 // Avoid massive lists
3203 if (NumUsesExplored >= DomConditionsMaxUses)
3204 break;
3205 NumUsesExplored++;
3206
3207 const Instruction *UI = cast<Instruction>(U.getUser());
3208 // If the value is used as an argument to a call or invoke, then argument
3209 // attributes may provide an answer about null-ness.
3210 if (V->getType()->isPointerTy()) {
3211 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3212 if (CB->isArgOperand(&U) &&
3213 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3214 /*AllowUndefOrPoison=*/false) &&
3215 DT->dominates(CB, CtxI))
3216 return true;
3217 }
3218 }
3219
3220 // If the value is used as a load/store, then the pointer must be non null.
3221 if (V == getLoadStorePointerOperand(UI)) {
3223 V->getType()->getPointerAddressSpace()) &&
3224 DT->dominates(UI, CtxI))
3225 return true;
3226 }
3227
3228 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3229 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3230 isValidAssumeForContext(UI, CtxI, DT))
3231 return true;
3232
3233 // Consider only compare instructions uniquely controlling a branch
3234 Value *RHS;
3236 bool NonNullIfTrue;
3237 if (match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) {
3238 if (cmpExcludesZero(Pred, RHS))
3239 NonNullIfTrue = true;
3241 NonNullIfTrue = false;
3242 else
3243 continue;
3244 } else if (UI->getType()->isIntegerTy(1) &&
3245 match(UI, m_Trunc(m_Specific(V)))) {
3246 NonNullIfTrue = true;
3247 } else
3248 continue;
3249
3252 for (const auto *CmpU : UI->users()) {
3253 assert(WorkList.empty() && "Should be!");
3254 if (Visited.insert(CmpU).second)
3255 WorkList.push_back(CmpU);
3256
3257 while (!WorkList.empty()) {
3258 auto *Curr = WorkList.pop_back_val();
3259
3260 // If a user is an AND, add all its users to the work list. We only
3261 // propagate "pred != null" condition through AND because it is only
3262 // correct to assume that all conditions of AND are met in true branch.
3263 // TODO: Support similar logic of OR and EQ predicate?
3264 if (NonNullIfTrue)
3265 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3266 for (const auto *CurrU : Curr->users())
3267 if (Visited.insert(CurrU).second)
3268 WorkList.push_back(CurrU);
3269 continue;
3270 }
3271
3272 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3273 BasicBlock *NonNullSuccessor =
3274 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3275 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3276 if (DT->dominates(Edge, CtxI->getParent()))
3277 return true;
3278 } else if (NonNullIfTrue && isGuard(Curr) &&
3279 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3280 return true;
3281 }
3282 }
3283 }
3284 }
3285
3286 return false;
3287}
3288
3289/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3290/// ensure that the value it's attached to is never Value? 'RangeType' is
3291/// is the type of the value described by the range.
3292static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3293 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3294 assert(NumRanges >= 1);
3295 for (unsigned i = 0; i < NumRanges; ++i) {
3297 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3299 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3300 ConstantRange Range(Lower->getValue(), Upper->getValue());
3301 if (Range.contains(Value))
3302 return false;
3303 }
3304 return true;
3305}
3306
3307/// Try to detect a recurrence that monotonically increases/decreases from a
3308/// non-zero starting value. These are common as induction variables.
3309static bool isNonZeroRecurrence(const PHINode *PN) {
3310 BinaryOperator *BO = nullptr;
3311 Value *Start = nullptr, *Step = nullptr;
3312 const APInt *StartC, *StepC;
3313 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3314 !match(Start, m_APInt(StartC)) || StartC->isZero())
3315 return false;
3316
3317 switch (BO->getOpcode()) {
3318 case Instruction::Add:
3319 // Starting from non-zero and stepping away from zero can never wrap back
3320 // to zero.
3321 return BO->hasNoUnsignedWrap() ||
3322 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3323 StartC->isNegative() == StepC->isNegative());
3324 case Instruction::Mul:
3325 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3326 match(Step, m_APInt(StepC)) && !StepC->isZero();
3327 case Instruction::Shl:
3328 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3329 case Instruction::AShr:
3330 case Instruction::LShr:
3331 return BO->isExact();
3332 case Instruction::Or:
3333 return true;
3334 default:
3335 return false;
3336 }
3337}
3338
3339static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3341 m_Specific(Op1), m_Zero()))) ||
3343 m_Specific(Op0), m_Zero())));
3344}
3345
3346/// Return true if "addr(P) + Off" cannot be zero. The object P points to
3347/// cannot cross the unsigned address space boundary, including the address one
3348/// past its end, so an offset that stays within the object cannot wrap around
3349/// to zero. This holds even if the object starts at the zero address, which is
3350/// all that null_pointer_is_valid permits, so a non-zero offset is enough.
3352 Value *Y) {
3353 const APInt *Off;
3354 if (!match(Y, m_APInt(Off)) || Off->isZero())
3355 return false;
3356
3357 // ptrtoaddr always produces the address. ptrtoint only does so when its
3358 // result is at least as wide as the address: a narrower result is truncated
3359 // and may wrap to zero, while bits above the address can only make the
3360 // result more non-zero.
3361 Value *P;
3362 if (!match(X, m_PtrToAddr(m_Value(P))) &&
3363 !(match(X, m_PtrToInt(m_Value(P))) &&
3364 X->getType()->getScalarSizeInBits() >=
3365 Q.DL.getAddressSizeInBits(P->getType())))
3366 return false;
3367
3368 // A vector of pointers has no single object whose size can be taken, and
3369 // getPointerDereferenceableBytes() requires a plain pointer.
3370 if (!P->getType()->isPointerTy())
3371 return false;
3372
3373 bool CanBeNull;
3374 uint64_t DerefBytes = P->getPointerDereferenceableBytes(
3375 Q.DL, CanBeNull, /*CanBeFreed=*/nullptr);
3376 if (CanBeNull || DerefBytes == 0 || !Off->ule(DerefBytes))
3377 return false;
3378
3379 return true;
3380}
3381
3382static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3383 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3384 bool NUW, unsigned Depth) {
3386 return true;
3387
3388 // (X + (X != 0)) is non zero
3389 if (matchOpWithOpEqZero(X, Y))
3390 return true;
3391
3392 if (NUW)
3393 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3394 isKnownNonZero(X, DemandedElts, Q, Depth);
3395
3396 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3397 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3398
3399 // If X and Y are both non-negative (as signed values) then their sum is not
3400 // zero unless both X and Y are zero.
3401 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3402 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3403 isKnownNonZero(X, DemandedElts, Q, Depth))
3404 return true;
3405
3406 // If X and Y are both negative (as signed values) then their sum is not
3407 // zero unless both X and Y equal INT_MIN.
3408 if (XKnown.isNegative() && YKnown.isNegative()) {
3410 // The sign bit of X is set. If some other bit is set then X is not equal
3411 // to INT_MIN.
3412 if (XKnown.One.intersects(Mask))
3413 return true;
3414 // The sign bit of Y is set. If some other bit is set then Y is not equal
3415 // to INT_MIN.
3416 if (YKnown.One.intersects(Mask))
3417 return true;
3418 }
3419
3420 // The sum of a non-negative number and a power of two is not zero.
3421 if (XKnown.isNonNegative() &&
3422 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3423 return true;
3424 if (YKnown.isNonNegative() &&
3425 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3426 return true;
3427
3428 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3429}
3430
3431static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3432 unsigned BitWidth, Value *X, Value *Y,
3433 unsigned Depth) {
3434 // (X - (X != 0)) is non zero
3435 // ((X != 0) - X) is non zero
3436 if (matchOpWithOpEqZero(X, Y))
3437 return true;
3438
3439 // TODO: Move this case into isKnownNonEqual().
3440 if (auto *C = dyn_cast<Constant>(X))
3441 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3442 return true;
3443
3444 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3445}
3446
3447static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3448 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3449 bool NUW, unsigned Depth) {
3450 // If X and Y are non-zero then so is X * Y as long as the multiplication
3451 // does not overflow.
3452 if (NSW || NUW)
3453 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3454 isKnownNonZero(Y, DemandedElts, Q, Depth);
3455
3456 // If either X or Y is odd, then if the other is non-zero the result can't
3457 // be zero.
3458 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3459 if (XKnown.One[0])
3460 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3461
3462 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3463 if (YKnown.One[0])
3464 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3465
3466 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3467 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3468 // the lowest known One of X and Y. If they are non-zero, the result
3469 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3470 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3471 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3472 BitWidth;
3473}
3474
3475static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3476 const SimplifyQuery &Q, const KnownBits &KnownVal,
3477 unsigned Depth) {
3478 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3479 switch (I->getOpcode()) {
3480 case Instruction::Shl:
3481 return Lhs.shl(Rhs);
3482 case Instruction::LShr:
3483 return Lhs.lshr(Rhs);
3484 case Instruction::AShr:
3485 return Lhs.ashr(Rhs);
3486 default:
3487 llvm_unreachable("Unknown Shift Opcode");
3488 }
3489 };
3490
3491 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3492 switch (I->getOpcode()) {
3493 case Instruction::Shl:
3494 return Lhs.lshr(Rhs);
3495 case Instruction::LShr:
3496 case Instruction::AShr:
3497 return Lhs.shl(Rhs);
3498 default:
3499 llvm_unreachable("Unknown Shift Opcode");
3500 }
3501 };
3502
3503 if (KnownVal.isUnknown())
3504 return false;
3505
3506 KnownBits KnownCnt =
3507 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3508 APInt MaxShift = KnownCnt.getMaxValue();
3509 unsigned NumBits = KnownVal.getBitWidth();
3510 if (MaxShift.uge(NumBits))
3511 return false;
3512
3513 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3514 return true;
3515
3516 // If all of the bits shifted out are known to be zero, and Val is known
3517 // non-zero then at least one non-zero bit must remain.
3518 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3519 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3520 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3521 return true;
3522
3523 return false;
3524}
3525
3527 const APInt &DemandedElts,
3528 const SimplifyQuery &Q, unsigned Depth) {
3529 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3530 switch (I->getOpcode()) {
3531 case Instruction::Alloca:
3532 // Alloca never returns null, malloc might.
3533 return I->getType()->getPointerAddressSpace() == 0;
3534 case Instruction::GetElementPtr:
3535 if (I->getType()->isPointerTy())
3537 break;
3538 case Instruction::BitCast: {
3539 // We need to be a bit careful here. We can only peek through the bitcast
3540 // if the scalar size of elements in the operand are smaller than and a
3541 // multiple of the size they are casting too. Take three cases:
3542 //
3543 // 1) Unsafe:
3544 // bitcast <2 x i16> %NonZero to <4 x i8>
3545 //
3546 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3547 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3548 // guranteed (imagine just sign bit set in the 2 i16 elements).
3549 //
3550 // 2) Unsafe:
3551 // bitcast <4 x i3> %NonZero to <3 x i4>
3552 //
3553 // Even though the scalar size of the src (`i3`) is smaller than the
3554 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3555 // its possible for the `3 x i4` elements to be zero because there are
3556 // some elements in the destination that don't contain any full src
3557 // element.
3558 //
3559 // 3) Safe:
3560 // bitcast <4 x i8> %NonZero to <2 x i16>
3561 //
3562 // This is always safe as non-zero in the 4 i8 elements implies
3563 // non-zero in the combination of any two adjacent ones. Since i8 is a
3564 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3565 // This all implies the 2 i16 elements are non-zero.
3566 Type *FromTy = I->getOperand(0)->getType();
3567 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3568 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3569 return isKnownNonZero(I->getOperand(0), Q, Depth);
3570 } break;
3571 case Instruction::IntToPtr:
3572 // Note that we have to take special care to avoid looking through
3573 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3574 // as casts that can alter the value, e.g., AddrSpaceCasts.
3575 if (!isa<ScalableVectorType>(I->getType()) &&
3576 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3577 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3578 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3579 break;
3580 case Instruction::PtrToAddr:
3581 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3582 // so we can directly forward.
3583 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3584 case Instruction::PtrToInt:
3585 // For inttoptr, make sure the result size is >= the address size. If the
3586 // address is non-zero, any larger value is also non-zero.
3587 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3588 I->getType()->getScalarSizeInBits())
3589 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3590 break;
3591 case Instruction::Trunc:
3592 // nuw/nsw trunc preserves zero/non-zero status of input.
3593 if (auto *TI = dyn_cast<TruncInst>(I))
3594 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3595 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3596 break;
3597
3598 // Iff x - y != 0, then x ^ y != 0
3599 // Therefore we can do the same exact checks
3600 case Instruction::Xor:
3601 case Instruction::Sub:
3602 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3603 I->getOperand(1), Depth);
3604 case Instruction::Or:
3605 // (X | (X != 0)) is non zero
3606 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3607 return true;
3608 // X | Y != 0 if X != Y.
3609 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3610 Depth))
3611 return true;
3612 // X | Y != 0 if X != 0 or Y != 0.
3613 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3614 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3615 case Instruction::SExt:
3616 case Instruction::ZExt:
3617 // ext X != 0 if X != 0.
3618 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3619
3620 case Instruction::Shl: {
3621 // shl nsw/nuw can't remove any non-zero bits.
3623 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3624 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3625
3626 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3627 // if the lowest bit is shifted off the end.
3629 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3630 if (Known.One[0])
3631 return true;
3632
3633 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3634 }
3635 case Instruction::LShr:
3636 case Instruction::AShr: {
3637 // shr exact can only shift out zero bits.
3639 if (BO->isExact())
3640 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3641
3642 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3643 // defined if the sign bit is shifted off the end.
3645 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3646 if (Known.isNegative())
3647 return true;
3648
3649 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3650 // position >= C, because the sum >= max(A, B).
3651 Value *A, *B;
3652 const APInt *C;
3653 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3654 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3655 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3656 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3657 if (!KnownA.One.lshr(*C).isZero())
3658 return true;
3659 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3660 if (!KnownB.One.lshr(*C).isZero())
3661 return true;
3662 }
3663
3664 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3665 }
3666 case Instruction::UDiv:
3667 case Instruction::SDiv: {
3668 // X / Y
3669 // div exact can only produce a zero if the dividend is zero.
3670 if (cast<PossiblyExactOperator>(I)->isExact())
3671 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3672
3673 KnownBits XKnown =
3674 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3675 // If X is fully unknown we won't be able to figure anything out so don't
3676 // both computing knownbits for Y.
3677 if (XKnown.isUnknown())
3678 return false;
3679
3680 KnownBits YKnown =
3681 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3682 if (I->getOpcode() == Instruction::SDiv) {
3683 // For signed division need to compare abs value of the operands.
3684 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3685 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3686 }
3687 // If X u>= Y then div is non zero (0/0 is UB).
3688 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3689 // If X is total unknown or X u< Y we won't be able to prove non-zero
3690 // with compute known bits so just return early.
3691 return XUgeY && *XUgeY;
3692 }
3693 case Instruction::Add: {
3694 // X + Y.
3695
3696 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3697 // non-zero.
3699 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3700 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3701 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3702 }
3703 case Instruction::Mul: {
3705 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3706 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3707 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3708 }
3709 case Instruction::Select: {
3710 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3711
3712 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3713 // then see if the select condition implies the arm is non-zero. For example
3714 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3715 // dominated by `X != 0`.
3716 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3717 Value *Op;
3718 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3719 // Op is trivially non-zero.
3720 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3721 return true;
3722
3723 // The condition of the select dominates the true/false arm. Check if the
3724 // condition implies that a given arm is non-zero.
3725 Value *X;
3727 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3728 return false;
3729
3730 if (!IsTrueArm)
3732
3733 return cmpExcludesZero(Pred, X);
3734 };
3735
3736 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3737 SelectArmIsNonZero(/* IsTrueArm */ false))
3738 return true;
3739 break;
3740 }
3741 case Instruction::PHI: {
3742 auto *PN = cast<PHINode>(I);
3744 return true;
3745
3746 // Check if all incoming values are non-zero using recursion.
3748 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3749 return llvm::all_of(PN->operands(), [&](const Use &U) {
3750 if (U.get() == PN)
3751 return true;
3752 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3753 // Check if the branch on the phi excludes zero.
3754 CmpPredicate Pred;
3755 Value *X;
3756 BasicBlock *TrueSucc, *FalseSucc;
3757 if (match(RecQ.CtxI,
3758 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3759 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3760 // Check for cases of duplicate successors.
3761 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3762 // If we're using the false successor, invert the predicate.
3763 if (FalseSucc == PN->getParent())
3764 Pred = CmpInst::getInversePredicate(Pred);
3765 if (cmpExcludesZero(Pred, X))
3766 return true;
3767 }
3768 }
3769 if (match(RecQ.CtxI,
3770 m_Br(m_Trunc(m_Specific(U.get())), m_BasicBlock(TrueSucc),
3771 m_BasicBlock(FalseSucc))) &&
3772 TrueSucc == PN->getParent() && FalseSucc != TrueSucc)
3773 return true;
3774 // Finally recurse on the edge and check it directly.
3775 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3776 });
3777 }
3778 case Instruction::InsertElement: {
3779 if (isa<ScalableVectorType>(I->getType()))
3780 break;
3781
3782 const Value *Vec = I->getOperand(0);
3783 const Value *Elt = I->getOperand(1);
3784 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3785
3786 unsigned NumElts = DemandedElts.getBitWidth();
3787 APInt DemandedVecElts = DemandedElts;
3788 bool SkipElt = false;
3789 // If we know the index we are inserting too, clear it from Vec check.
3790 if (CIdx && CIdx->getValue().ult(NumElts)) {
3791 DemandedVecElts.clearBit(CIdx->getZExtValue());
3792 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3793 }
3794
3795 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3796 // are non-zero.
3797 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3798 (DemandedVecElts.isZero() ||
3799 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3800 }
3801 case Instruction::ExtractElement:
3802 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3803 const Value *Vec = EEI->getVectorOperand();
3804 const Value *Idx = EEI->getIndexOperand();
3805 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3806 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3807 unsigned NumElts = VecTy->getNumElements();
3808 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3809 if (CIdx && CIdx->getValue().ult(NumElts))
3810 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3811 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3812 }
3813 }
3814 break;
3815 case Instruction::ShuffleVector: {
3816 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3817 if (!Shuf)
3818 break;
3819 APInt DemandedLHS, DemandedRHS;
3820 // For undef elements, we don't know anything about the common state of
3821 // the shuffle result.
3822 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3823 break;
3824 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3825 return (DemandedRHS.isZero() ||
3826 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3827 (DemandedLHS.isZero() ||
3828 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3829 }
3830 case Instruction::Freeze:
3831 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3832 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3833 Depth);
3834 case Instruction::Load: {
3835 auto *LI = cast<LoadInst>(I);
3836 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3837 // is never null.
3838 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3839 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3840 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3841 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3842 return true;
3843 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3845 }
3846
3847 // No need to fall through to computeKnownBits as range metadata is already
3848 // handled in isKnownNonZero.
3849 return false;
3850 }
3851 case Instruction::ExtractValue: {
3852 const WithOverflowInst *WO;
3854 switch (WO->getBinaryOp()) {
3855 default:
3856 break;
3857 case Instruction::Add:
3858 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3859 WO->getArgOperand(1),
3860 /*NSW=*/false,
3861 /*NUW=*/false, Depth);
3862 case Instruction::Sub:
3863 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3864 WO->getArgOperand(1), Depth);
3865 case Instruction::Mul:
3866 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3867 WO->getArgOperand(1),
3868 /*NSW=*/false, /*NUW=*/false, Depth);
3869 break;
3870 }
3871 }
3872 break;
3873 }
3874 case Instruction::Call:
3875 case Instruction::Invoke: {
3876 const auto *Call = cast<CallBase>(I);
3877 if (I->getType()->isPointerTy()) {
3878 if (Call->isReturnNonNull())
3879 return true;
3880 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3881 Call, /*MustPreserveOffset=*/true))
3882 return isKnownNonZero(RP, Q, Depth);
3883 } else {
3884 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3886 if (std::optional<ConstantRange> Range = Call->getRange()) {
3887 const APInt ZeroValue(Range->getBitWidth(), 0);
3888 if (!Range->contains(ZeroValue))
3889 return true;
3890 }
3891 if (const Value *RV = Call->getReturnedArgOperand())
3892 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3893 return true;
3894 }
3895
3896 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3897 switch (II->getIntrinsicID()) {
3898 case Intrinsic::sshl_sat:
3899 case Intrinsic::ushl_sat:
3900 case Intrinsic::abs:
3901 case Intrinsic::bitreverse:
3902 case Intrinsic::bswap:
3903 case Intrinsic::ctpop:
3904 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3905 // NB: We don't do usub_sat here as in any case we can prove its
3906 // non-zero, we will fold it to `sub nuw` in InstCombine.
3907 case Intrinsic::ssub_sat:
3908 // For most types, if x != y then ssub.sat x, y != 0. But
3909 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3910 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3911 if (BitWidth == 1)
3912 return false;
3913 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3914 II->getArgOperand(1), Depth);
3915 case Intrinsic::sadd_sat:
3916 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3917 II->getArgOperand(1),
3918 /*NSW=*/true, /* NUW=*/false, Depth);
3919 // Vec reverse preserves zero/non-zero status from input vec.
3920 case Intrinsic::vector_reverse:
3921 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3922 Q, Depth);
3923 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3924 case Intrinsic::vector_reduce_or:
3925 case Intrinsic::vector_reduce_umax:
3926 case Intrinsic::vector_reduce_umin:
3927 case Intrinsic::vector_reduce_smax:
3928 case Intrinsic::vector_reduce_smin:
3929 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3930 case Intrinsic::umax:
3931 case Intrinsic::uadd_sat:
3932 // umax(X, (X != 0)) is non zero
3933 // X +usat (X != 0) is non zero
3934 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3935 return true;
3936
3937 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3938 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3939 case Intrinsic::smax: {
3940 // If either arg is strictly positive the result is non-zero. Otherwise
3941 // the result is non-zero if both ops are non-zero.
3942 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3943 const KnownBits &OpKnown) {
3944 if (!OpNonZero.has_value())
3945 OpNonZero = OpKnown.isNonZero() ||
3946 isKnownNonZero(Op, DemandedElts, Q, Depth);
3947 return *OpNonZero;
3948 };
3949 // Avoid re-computing isKnownNonZero.
3950 std::optional<bool> Op0NonZero, Op1NonZero;
3951 KnownBits Op1Known =
3952 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3953 if (Op1Known.isNonNegative() &&
3954 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3955 return true;
3956 KnownBits Op0Known =
3957 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3958 if (Op0Known.isNonNegative() &&
3959 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3960 return true;
3961 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3962 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3963 }
3964 case Intrinsic::smin: {
3965 // If either arg is negative the result is non-zero. Otherwise
3966 // the result is non-zero if both ops are non-zero.
3967 KnownBits Op1Known =
3968 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3969 if (Op1Known.isNegative())
3970 return true;
3971 KnownBits Op0Known =
3972 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3973 if (Op0Known.isNegative())
3974 return true;
3975
3976 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3977 return true;
3978 }
3979 [[fallthrough]];
3980 case Intrinsic::umin:
3981 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3982 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3983 case Intrinsic::cttz:
3984 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3985 .Zero[0];
3986 case Intrinsic::ctlz:
3987 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3988 .isNonNegative();
3989 case Intrinsic::fshr:
3990 case Intrinsic::fshl:
3991 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3992 if (II->getArgOperand(0) == II->getArgOperand(1))
3993 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3994 break;
3995 case Intrinsic::vscale:
3996 return true;
3997 case Intrinsic::experimental_get_vector_length:
3998 return isKnownNonZero(I->getOperand(0), Q, Depth);
3999 default:
4000 break;
4001 }
4002 break;
4003 }
4004
4005 return false;
4006 }
4007 }
4008
4010 computeKnownBits(I, DemandedElts, Known, Q, Depth);
4011 return Known.One != 0;
4012}
4013
4014/// Return true if the given value is known to be non-zero when defined. For
4015/// vectors, return true if every demanded element is known to be non-zero when
4016/// defined. For pointers, if the context instruction and dominator tree are
4017/// specified, perform context-sensitive analysis and return true if the
4018/// pointer couldn't possibly be null at the specified instruction.
4019/// Supports values with integer or pointer type and vectors of integers.
4020bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
4021 const SimplifyQuery &Q, unsigned Depth) {
4022 Type *Ty = V->getType();
4023
4024#ifndef NDEBUG
4025 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4026
4027 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4028 assert(
4029 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4030 "DemandedElt width should equal the fixed vector number of elements");
4031 } else {
4032 assert(DemandedElts == APInt(1, 1) &&
4033 "DemandedElt width should be 1 for scalars");
4034 }
4035#endif
4036
4037 if (auto *C = dyn_cast<Constant>(V)) {
4038 if (C->isNullValue())
4039 return false;
4040 if (isa<ConstantInt>(C))
4041 // Must be non-zero due to null test above.
4042 return true;
4043
4044 // For constant vectors, check that all elements are poison or known
4045 // non-zero to determine that the whole vector is known non-zero.
4046 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
4047 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
4048 if (!DemandedElts[i])
4049 continue;
4050 Constant *Elt = C->getAggregateElement(i);
4051 if (!Elt || Elt->isNullValue())
4052 return false;
4053 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
4054 return false;
4055 }
4056 return true;
4057 }
4058
4059 // Constant ptrauth can be null, iff the base pointer can be.
4060 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
4061 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
4062
4063 // A global variable is non null unless extern weak or an absolute symbol
4064 // reference. An alias is also excluded, as it may resolve to a weak
4065 // undefined symbol and thus to the null address. Where null is a valid
4066 // address an allocation may start there, so nothing can be assumed; that
4067 // covers both null_pointer_is_valid and address spaces other than zero.
4068 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
4070 GV->getType()->getAddressSpace()) &&
4071 !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
4072 !isa<GlobalAlias>(GV))
4073 return true;
4074 }
4075
4076 // For constant expressions, fall through to the Operator code below.
4077 if (!isa<ConstantExpr>(V))
4078 return false;
4079 }
4080
4081 if (const auto *A = dyn_cast<Argument>(V))
4082 if (std::optional<ConstantRange> Range = A->getRange()) {
4083 const APInt ZeroValue(Range->getBitWidth(), 0);
4084 if (!Range->contains(ZeroValue))
4085 return true;
4086 }
4087
4089 return true;
4090
4091 // Some of the tests below are recursive, so bail out if we hit the limit.
4093 return false;
4094
4095 // Check for pointer simplifications.
4096
4097 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
4098 // A byval, inalloca may not be null in a non-default addres space. A
4099 // nonnull argument is assumed never 0.
4100 if (const Argument *A = dyn_cast<Argument>(V)) {
4101 if (((A->hasPassPointeeByValueCopyAttr() &&
4102 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
4103 A->hasNonNullAttr()))
4104 return true;
4105 }
4106 }
4107
4108 if (const auto *I = dyn_cast<Operator>(V))
4109 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
4110 return true;
4111
4112 if (!isa<Constant>(V) &&
4114 return true;
4115
4116 if (const Value *Stripped = stripNullTest(V))
4117 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
4118
4119 return false;
4120}
4121
4123 unsigned Depth) {
4124 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4125 APInt DemandedElts =
4126 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
4127 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
4128}
4129
4130/// If the pair of operators are the same invertible function, return the
4131/// the operands of the function corresponding to each input. Otherwise,
4132/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
4133/// every input value to exactly one output value. This is equivalent to
4134/// saying that Op1 and Op2 are equal exactly when the specified pair of
4135/// operands are equal, (except that Op1 and Op2 may be poison more often.)
4136static std::optional<std::pair<Value*, Value*>>
4138 const Operator *Op2) {
4139 if (Op1->getOpcode() != Op2->getOpcode())
4140 return std::nullopt;
4141
4142 auto getOperands = [&](unsigned OpNum) -> auto {
4143 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
4144 };
4145
4146 switch (Op1->getOpcode()) {
4147 default:
4148 break;
4149 case Instruction::Or:
4150 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
4151 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
4152 break;
4153 [[fallthrough]];
4154 case Instruction::Xor:
4155 case Instruction::Add: {
4156 Value *Other;
4157 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
4158 return std::make_pair(Op1->getOperand(1), Other);
4159 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
4160 return std::make_pair(Op1->getOperand(0), Other);
4161 break;
4162 }
4163 case Instruction::Sub:
4164 if (Op1->getOperand(0) == Op2->getOperand(0))
4165 return getOperands(1);
4166 if (Op1->getOperand(1) == Op2->getOperand(1))
4167 return getOperands(0);
4168 break;
4169 case Instruction::Mul: {
4170 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4171 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4172 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4173 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4174 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4175 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4176 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4177 break;
4178
4179 // Assume operand order has been canonicalized
4180 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4181 isa<ConstantInt>(Op1->getOperand(1)) &&
4182 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4183 return getOperands(0);
4184 break;
4185 }
4186 case Instruction::Shl: {
4187 // Same as multiplies, with the difference that we don't need to check
4188 // for a non-zero multiply. Shifts always multiply by non-zero.
4189 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4190 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4191 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4192 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4193 break;
4194
4195 if (Op1->getOperand(1) == Op2->getOperand(1))
4196 return getOperands(0);
4197 break;
4198 }
4199 case Instruction::AShr:
4200 case Instruction::LShr: {
4201 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4202 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4203 if (!PEO1->isExact() || !PEO2->isExact())
4204 break;
4205
4206 if (Op1->getOperand(1) == Op2->getOperand(1))
4207 return getOperands(0);
4208 break;
4209 }
4210 case Instruction::SExt:
4211 case Instruction::ZExt:
4212 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4213 return getOperands(0);
4214 break;
4215 case Instruction::PHI: {
4216 const PHINode *PN1 = cast<PHINode>(Op1);
4217 const PHINode *PN2 = cast<PHINode>(Op2);
4218
4219 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4220 // are a single invertible function of the start values? Note that repeated
4221 // application of an invertible function is also invertible
4222 BinaryOperator *BO1 = nullptr;
4223 Value *Start1 = nullptr, *Step1 = nullptr;
4224 BinaryOperator *BO2 = nullptr;
4225 Value *Start2 = nullptr, *Step2 = nullptr;
4226 if (PN1->getParent() != PN2->getParent() ||
4227 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4228 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4229 break;
4230
4232 cast<Operator>(BO2));
4233 if (!Values)
4234 break;
4235
4236 // We have to be careful of mutually defined recurrences here. Ex:
4237 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4238 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4239 // The invertibility of these is complicated, and not worth reasoning
4240 // about (yet?).
4241 if (Values->first != PN1 || Values->second != PN2)
4242 break;
4243
4244 return std::make_pair(Start1, Start2);
4245 }
4246 }
4247 return std::nullopt;
4248}
4249
4250/// Return true if V1 == (binop V2, X), where X is known non-zero.
4251/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4252/// implies V2 != V1.
4253static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4254 const APInt &DemandedElts,
4255 const SimplifyQuery &Q, unsigned Depth) {
4257 if (!BO)
4258 return false;
4259 switch (BO->getOpcode()) {
4260 default:
4261 break;
4262 case Instruction::Or:
4263 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4264 break;
4265 [[fallthrough]];
4266 case Instruction::Xor:
4267 case Instruction::Add:
4268 Value *Op = nullptr;
4269 if (V2 == BO->getOperand(0))
4270 Op = BO->getOperand(1);
4271 else if (V2 == BO->getOperand(1))
4272 Op = BO->getOperand(0);
4273 else
4274 return false;
4275 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4276 }
4277 return false;
4278}
4279
4280/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4281/// the multiplication is nuw or nsw.
4282static bool isNonEqualMul(const Value *V1, const Value *V2,
4283 const APInt &DemandedElts, const SimplifyQuery &Q,
4284 unsigned Depth) {
4285 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4286 const APInt *C;
4287 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4288 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4289 !C->isZero() && !C->isOne() &&
4290 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4291 }
4292 return false;
4293}
4294
4295/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4296/// the shift is nuw or nsw.
4297static bool isNonEqualShl(const Value *V1, const Value *V2,
4298 const APInt &DemandedElts, const SimplifyQuery &Q,
4299 unsigned Depth) {
4300 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4301 const APInt *C;
4302 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4303 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4304 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4305 }
4306 return false;
4307}
4308
4309static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4310 const APInt &DemandedElts, const SimplifyQuery &Q,
4311 unsigned Depth) {
4312 // Check two PHIs are in same block.
4313 if (PN1->getParent() != PN2->getParent())
4314 return false;
4315
4317 bool UsedFullRecursion = false;
4318 for (const BasicBlock *IncomBB : PN1->blocks()) {
4319 if (!VisitedBBs.insert(IncomBB).second)
4320 continue; // Don't reprocess blocks that we have dealt with already.
4321 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4322 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4323 const APInt *C1, *C2;
4324 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4325 continue;
4326
4327 // Only one pair of phi operands is allowed for full recursion.
4328 if (UsedFullRecursion)
4329 return false;
4330
4332 RecQ.CtxI = IncomBB->getTerminator();
4333 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4334 return false;
4335 UsedFullRecursion = true;
4336 }
4337 return true;
4338}
4339
4340static bool isNonEqualSelect(const Value *V1, const Value *V2,
4341 const APInt &DemandedElts, const SimplifyQuery &Q,
4342 unsigned Depth) {
4343 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4344 if (!SI1)
4345 return false;
4346
4347 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4348 const Value *Cond1 = SI1->getCondition();
4349 const Value *Cond2 = SI2->getCondition();
4350 if (Cond1 == Cond2)
4351 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4352 DemandedElts, Q, Depth + 1) &&
4353 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4354 DemandedElts, Q, Depth + 1);
4355 }
4356 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4357 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4358}
4359
4360// Check to see if A is both a GEP and is the incoming value for a PHI in the
4361// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4362// one of them being the recursive GEP A and the other a ptr at same base and at
4363// the same/higher offset than B we are only incrementing the pointer further in
4364// loop if offset of recursive GEP is greater than 0.
4366 const SimplifyQuery &Q) {
4367 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4368 return false;
4369
4370 auto *GEPA = dyn_cast<GEPOperator>(A);
4371 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4372 return false;
4373
4374 // Handle 2 incoming PHI values with one being a recursive GEP.
4375 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4376 if (!PN || PN->getNumIncomingValues() != 2)
4377 return false;
4378
4379 // Search for the recursive GEP as an incoming operand, and record that as
4380 // Step.
4381 Value *Start = nullptr;
4382 Value *Step = const_cast<Value *>(A);
4383 if (PN->getIncomingValue(0) == Step)
4384 Start = PN->getIncomingValue(1);
4385 else if (PN->getIncomingValue(1) == Step)
4386 Start = PN->getIncomingValue(0);
4387 else
4388 return false;
4389
4390 // Other incoming node base should match the B base.
4391 // StartOffset >= OffsetB && StepOffset > 0?
4392 // StartOffset <= OffsetB && StepOffset < 0?
4393 // Is non-equal if above are true.
4394 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4395 // optimisation to inbounds GEPs only.
4396 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4397 APInt StartOffset(IndexWidth, 0);
4398 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4399 APInt StepOffset(IndexWidth, 0);
4400 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4401
4402 // Check if Base Pointer of Step matches the PHI.
4403 if (Step != PN)
4404 return false;
4405 APInt OffsetB(IndexWidth, 0);
4406 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4407 return Start == B &&
4408 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4409 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4410}
4411
4412static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4413 const SimplifyQuery &Q, unsigned Depth) {
4414 if (!Q.CtxI)
4415 return false;
4416
4417 // Try to infer NonEqual based on information from dominating conditions.
4418 if (Q.DC && Q.DT) {
4419 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4420 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4421 Value *Cond = BI->getCondition();
4422 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4423 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4425 /*LHSIsTrue=*/true, Depth)
4426 .value_or(false))
4427 return true;
4428
4429 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4430 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4432 /*LHSIsTrue=*/false, Depth)
4433 .value_or(false))
4434 return true;
4435 }
4436
4437 return false;
4438 };
4439
4440 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4441 IsKnownNonEqualFromDominatingCondition(V2))
4442 return true;
4443 }
4444
4445 if (!Q.AC)
4446 return false;
4447
4448 // Try to infer NonEqual based on information from assumptions.
4449 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4450 if (!AssumeVH)
4451 continue;
4452 CallInst *I = cast<CallInst>(AssumeVH);
4453
4454 assert(I->getFunction() == Q.CtxI->getFunction() &&
4455 "Got assumption for the wrong function!");
4456 assert(I->getIntrinsicID() == Intrinsic::assume &&
4457 "must be an assume intrinsic");
4458
4459 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4460 /*LHSIsTrue=*/true, Depth)
4461 .value_or(false) &&
4463 return true;
4464 }
4465
4466 return false;
4467}
4468
4469static bool isNonEqualURem(const Value *X, const Value *Rem,
4470 const SimplifyQuery &Q) {
4471 const Value *Y;
4472 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4473 return false;
4474
4475 // For a defined urem, X != X urem Y exactly when X u>= Y.
4476 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4478 return true;
4479
4480 std::optional<bool> Implied =
4482 return Implied && *Implied;
4483}
4484
4485/// Return true if it is known that V1 != V2.
4486static bool isKnownNonEqual(const Value *V1, const Value *V2,
4487 const APInt &DemandedElts, const SimplifyQuery &Q,
4488 unsigned Depth) {
4489 if (V1 == V2)
4490 return false;
4491 if (V1->getType() != V2->getType())
4492 // We can't look through casts yet.
4493 return false;
4494
4496 return false;
4497
4498 // See if we can recurse through (exactly one of) our operands. This
4499 // requires our operation be 1-to-1 and map every input value to exactly
4500 // one output value. Such an operation is invertible.
4501 auto *O1 = dyn_cast<Operator>(V1);
4502 auto *O2 = dyn_cast<Operator>(V2);
4503 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4504 if (auto Values = getInvertibleOperands(O1, O2))
4505 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4506 Depth + 1);
4507
4508 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4509 const PHINode *PN2 = cast<PHINode>(V2);
4510 // FIXME: This is missing a generalization to handle the case where one is
4511 // a PHI and another one isn't.
4512 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4513 return true;
4514 };
4515 }
4516
4517 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4518 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4519 return true;
4520
4521 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4522 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4523 return true;
4524
4525 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4526 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4527 return true;
4528
4529 if (V1->getType()->isIntOrIntVectorTy()) {
4530 // Are any known bits in V1 contradictory to known bits in V2? If V1
4531 // has a known zero where V2 has a known one, they must not be equal.
4532 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4533 if (!Known1.isUnknown()) {
4534 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4535 if (Known1.Zero.intersects(Known2.One) ||
4536 Known2.Zero.intersects(Known1.One))
4537 return true;
4538 }
4539 }
4540
4541 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4542 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4543 return true;
4544
4547 return true;
4548
4549 Value *A, *B;
4550 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4551 // Check PtrToInt type matches the pointer size.
4552 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4554 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4555
4556 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4557 return true;
4558
4559 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4560 return true;
4561
4562 return false;
4563}
4564
4565/// For vector constants, loop over the elements and find the constant with the
4566/// minimum number of sign bits. Return 0 if the value is not a vector constant
4567/// or if any element was not analyzed; otherwise, return the count for the
4568/// element with the minimum number of sign bits.
4570 const APInt &DemandedElts,
4571 unsigned TyBits) {
4572 const auto *CV = dyn_cast<Constant>(V);
4573 if (!CV || !isa<FixedVectorType>(CV->getType()))
4574 return 0;
4575
4576 unsigned MinSignBits = TyBits;
4577 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4578 for (unsigned i = 0; i != NumElts; ++i) {
4579 if (!DemandedElts[i])
4580 continue;
4581 // If we find a non-ConstantInt, bail out.
4582 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4583 if (!Elt)
4584 return 0;
4585
4586 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4587 }
4588
4589 return MinSignBits;
4590}
4591
4592static unsigned ComputeNumSignBitsImpl(const Value *V,
4593 const APInt &DemandedElts,
4594 const SimplifyQuery &Q, unsigned Depth);
4595
4596static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4597 const SimplifyQuery &Q, unsigned Depth) {
4598 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4599 assert(Result > 0 && "At least one sign bit needs to be present!");
4600 return Result;
4601}
4602
4603/// Return the number of times the sign bit of the register is replicated into
4604/// the other bits. We know that at least 1 bit is always equal to the sign bit
4605/// (itself), but other cases can give us information. For example, immediately
4606/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4607/// other, so we return 3. For vectors, return the number of sign bits for the
4608/// vector element with the minimum number of known sign bits of the demanded
4609/// elements in the vector specified by DemandedElts.
4610static unsigned ComputeNumSignBitsImpl(const Value *V,
4611 const APInt &DemandedElts,
4612 const SimplifyQuery &Q, unsigned Depth) {
4613 Type *Ty = V->getType();
4614#ifndef NDEBUG
4615 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4616
4617 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4618 assert(
4619 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4620 "DemandedElt width should equal the fixed vector number of elements");
4621 } else {
4622 assert(DemandedElts == APInt(1, 1) &&
4623 "DemandedElt width should be 1 for scalars");
4624 }
4625#endif
4626
4627 // We return the minimum number of sign bits that are guaranteed to be present
4628 // in V, so for undef we have to conservatively return 1. We don't have the
4629 // same behavior for poison though -- that's a FIXME today.
4630
4631 Type *ScalarTy = Ty->getScalarType();
4632 unsigned TyBits = ScalarTy->isPointerTy() ?
4633 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4634 Q.DL.getTypeSizeInBits(ScalarTy);
4635
4636 unsigned Tmp, Tmp2;
4637 unsigned FirstAnswer = 1;
4638
4639 // Note that ConstantInt is handled by the general computeKnownBits case
4640 // below.
4641
4643 return 1;
4644
4645 if (auto *U = dyn_cast<Operator>(V)) {
4646 switch (Operator::getOpcode(V)) {
4647 default: break;
4648 case Instruction::BitCast: {
4649 Value *Src = U->getOperand(0);
4650 Type *SrcTy = Src->getType();
4651
4652 // Skip if the source type is not an integer or integer vector type
4653 // This ensures we only process integer-like types
4654 if (!SrcTy->isIntOrIntVectorTy())
4655 break;
4656
4657 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4658
4659 // Bitcast 'large element' scalar/vector to 'small element' vector.
4660 if ((SrcBits % TyBits) != 0)
4661 break;
4662
4663 // Only proceed if the destination type is a fixed-size vector
4664 if (isa<FixedVectorType>(Ty)) {
4665 // Fast case - sign splat can be simply split across the small elements.
4666 // This works for both vector and scalar sources
4667 unsigned Scale = SrcBits / TyBits;
4668 APInt SrcDemandedElts = APIntOps::ScaleBitMask(
4669 DemandedElts, DemandedElts.getBitWidth() / Scale);
4670 Tmp = ComputeNumSignBits(Src, SrcDemandedElts, Q, Depth + 1);
4671 if (Tmp == SrcBits)
4672 return TyBits;
4673 }
4674 break;
4675 }
4676 case Instruction::SExt:
4677 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4678 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4679 Tmp;
4680
4681 case Instruction::SDiv: {
4682 const APInt *Denominator;
4683 // sdiv X, C -> adds log(C) sign bits.
4684 if (match(U->getOperand(1), m_APInt(Denominator))) {
4685
4686 // Ignore non-positive denominator.
4687 if (!Denominator->isStrictlyPositive())
4688 break;
4689
4690 // Calculate the incoming numerator bits.
4691 unsigned NumBits =
4692 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4693
4694 // Add floor(log(C)) bits to the numerator bits.
4695 return std::min(TyBits, NumBits + Denominator->logBase2());
4696 }
4697 break;
4698 }
4699
4700 case Instruction::SRem: {
4701 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4702
4703 const APInt *Denominator;
4704 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4705 // positive constant. This let us put a lower bound on the number of sign
4706 // bits.
4707 if (match(U->getOperand(1), m_APInt(Denominator))) {
4708
4709 // Ignore non-positive denominator.
4710 if (Denominator->isStrictlyPositive()) {
4711 // Calculate the leading sign bit constraints by examining the
4712 // denominator. Given that the denominator is positive, there are two
4713 // cases:
4714 //
4715 // 1. The numerator is positive. The result range is [0,C) and
4716 // [0,C) u< (1 << ceilLogBase2(C)).
4717 //
4718 // 2. The numerator is negative. Then the result range is (-C,0] and
4719 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4720 //
4721 // Thus a lower bound on the number of sign bits is `TyBits -
4722 // ceilLogBase2(C)`.
4723
4724 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4725 Tmp = std::max(Tmp, ResBits);
4726 }
4727 }
4728 return Tmp;
4729 }
4730
4731 case Instruction::AShr: {
4732 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4733 // ashr X, C -> adds C sign bits. Vectors too.
4734 const APInt *ShAmt;
4735 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4736 if (ShAmt->uge(TyBits))
4737 break; // Bad shift.
4738 unsigned ShAmtLimited = ShAmt->getZExtValue();
4739 Tmp += ShAmtLimited;
4740 if (Tmp > TyBits) Tmp = TyBits;
4741 }
4742 return Tmp;
4743 }
4744 case Instruction::Shl: {
4745 const APInt *ShAmt;
4746 Value *X = nullptr;
4747 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4748 // shl destroys sign bits.
4749 if (ShAmt->uge(TyBits))
4750 break; // Bad shift.
4751 // We can look through a zext (more or less treating it as a sext) if
4752 // all extended bits are shifted out.
4753 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4754 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4755 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4756 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4757 } else
4758 Tmp =
4759 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4760 if (ShAmt->uge(Tmp))
4761 break; // Shifted all sign bits out.
4762 Tmp2 = ShAmt->getZExtValue();
4763 return Tmp - Tmp2;
4764 }
4765 break;
4766 }
4767 case Instruction::And:
4768 case Instruction::Or:
4769 case Instruction::Xor: // NOT is handled here.
4770 // Logical binary ops preserve the number of sign bits at the worst.
4771 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4772 if (Tmp != 1) {
4773 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4774 FirstAnswer = std::min(Tmp, Tmp2);
4775 // We computed what we know about the sign bits as our first
4776 // answer. Now proceed to the generic code that uses
4777 // computeKnownBits, and pick whichever answer is better.
4778 }
4779 break;
4780
4781 case Instruction::Select: {
4782 // If we have a clamp pattern, we know that the number of sign bits will
4783 // be the minimum of the clamp min/max range.
4784 const Value *X;
4785 const APInt *CLow, *CHigh;
4786 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4787 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4788
4789 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4790 if (Tmp == 1)
4791 break;
4792 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4793 return std::min(Tmp, Tmp2);
4794 }
4795
4796 case Instruction::Add:
4797 // Add can have at most one carry bit. Thus we know that the output
4798 // is, at worst, one more bit than the inputs.
4799 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4800 if (Tmp == 1) break;
4801
4802 // Special case decrementing a value (ADD X, -1):
4803 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4804 if (CRHS->isAllOnesValue()) {
4805 KnownBits Known(TyBits);
4806 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4807
4808 // If the input is known to be 0 or 1, the output is 0/-1, which is
4809 // all sign bits set.
4810 if ((Known.Zero | 1).isAllOnes())
4811 return TyBits;
4812
4813 // If we are subtracting one from a positive number, there is no carry
4814 // out of the result.
4815 if (Known.isNonNegative())
4816 return Tmp;
4817 }
4818
4819 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4820 if (Tmp2 == 1)
4821 break;
4822 return std::min(Tmp, Tmp2) - 1;
4823
4824 case Instruction::Sub:
4825 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4826 if (Tmp2 == 1)
4827 break;
4828
4829 // Handle NEG.
4830 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4831 if (CLHS->isNullValue()) {
4832 KnownBits Known(TyBits);
4833 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4834 // If the input is known to be 0 or 1, the output is 0/-1, which is
4835 // all sign bits set.
4836 if ((Known.Zero | 1).isAllOnes())
4837 return TyBits;
4838
4839 // If the input is known to be positive (the sign bit is known clear),
4840 // the output of the NEG has the same number of sign bits as the
4841 // input.
4842 if (Known.isNonNegative())
4843 return Tmp2;
4844
4845 // Otherwise, we treat this like a SUB.
4846 }
4847
4848 // Sub can have at most one carry bit. Thus we know that the output
4849 // is, at worst, one more bit than the inputs.
4850 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4851 if (Tmp == 1)
4852 break;
4853 return std::min(Tmp, Tmp2) - 1;
4854
4855 case Instruction::Mul: {
4856 // The output of the Mul can be at most twice the valid bits in the
4857 // inputs.
4858 unsigned SignBitsOp0 =
4859 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4860 if (SignBitsOp0 == 1)
4861 break;
4862 unsigned SignBitsOp1 =
4863 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4864 if (SignBitsOp1 == 1)
4865 break;
4866 unsigned OutValidBits =
4867 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4868 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4869 }
4870
4871 case Instruction::PHI: {
4872 const PHINode *PN = cast<PHINode>(U);
4873 unsigned NumIncomingValues = PN->getNumIncomingValues();
4874 // Don't analyze large in-degree PHIs.
4875 if (NumIncomingValues > 4) break;
4876 // Unreachable blocks may have zero-operand PHI nodes.
4877 if (NumIncomingValues == 0) break;
4878
4879 // Take the minimum of all incoming values. This can't infinitely loop
4880 // because of our depth threshold.
4882 Tmp = TyBits;
4883 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4884 if (Tmp == 1) return Tmp;
4885 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4886 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4887 DemandedElts, RecQ, Depth + 1));
4888 }
4889 return Tmp;
4890 }
4891
4892 case Instruction::Trunc: {
4893 // If the input contained enough sign bits that some remain after the
4894 // truncation, then we can make use of that. Otherwise we don't know
4895 // anything.
4896 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4897 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4898 if (Tmp > (OperandTyBits - TyBits))
4899 return Tmp - (OperandTyBits - TyBits);
4900
4901 return 1;
4902 }
4903
4904 case Instruction::ExtractElement: {
4905 const Value *Vec = U->getOperand(0);
4906 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
4907 if (!VecTy)
4908 return ComputeNumSignBits(Vec, Q, Depth + 1);
4909
4910 unsigned NumElts = VecTy->getNumElements();
4911 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
4912 if (auto *CIdx = dyn_cast<ConstantInt>(U->getOperand(1)))
4913 if (CIdx->getValue().ult(NumElts))
4914 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
4915 return ComputeNumSignBits(Vec, DemandedVecElts, Q, Depth + 1);
4916 }
4917
4918 case Instruction::ShuffleVector: {
4919 // Collect the minimum number of sign bits that are shared by every vector
4920 // element referenced by the shuffle.
4921 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4922 if (!Shuf) {
4923 // FIXME: Add support for shufflevector constant expressions.
4924 return 1;
4925 }
4926 APInt DemandedLHS, DemandedRHS;
4927 // For undef elements, we don't know anything about the common state of
4928 // the shuffle result.
4929 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4930 return 1;
4931 Tmp = std::numeric_limits<unsigned>::max();
4932 if (!!DemandedLHS) {
4933 const Value *LHS = Shuf->getOperand(0);
4934 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4935 }
4936 // If we don't know anything, early out and try computeKnownBits
4937 // fall-back.
4938 if (Tmp == 1)
4939 break;
4940 if (!!DemandedRHS) {
4941 const Value *RHS = Shuf->getOperand(1);
4942 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4943 Tmp = std::min(Tmp, Tmp2);
4944 }
4945 // If we don't know anything, early out and try computeKnownBits
4946 // fall-back.
4947 if (Tmp == 1)
4948 break;
4949 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4950 return Tmp;
4951 }
4952 case Instruction::Call: {
4953 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4954 switch (II->getIntrinsicID()) {
4955 default:
4956 break;
4957 case Intrinsic::abs:
4958 Tmp =
4959 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4960 if (Tmp == 1)
4961 break;
4962
4963 // Absolute value reduces number of sign bits by at most 1.
4964 return Tmp - 1;
4965 case Intrinsic::smin:
4966 case Intrinsic::smax: {
4967 const APInt *CLow, *CHigh;
4968 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4969 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4970 }
4971 }
4972 }
4973 }
4974 }
4975 }
4976
4977 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4978 // use this information.
4979
4980 // If we can examine all elements of a vector constant successfully, we're
4981 // done (we can't do any better than that). If not, keep trying.
4982 if (unsigned VecSignBits =
4983 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4984 return VecSignBits;
4985
4986 KnownBits Known(TyBits);
4987 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4988
4989 // If we know that the sign bit is either zero or one, determine the number of
4990 // identical bits in the top of the input value.
4991 return std::max(FirstAnswer, Known.countMinSignBits());
4992}
4993
4995 const TargetLibraryInfo *TLI) {
4996 const Function *F = CB.getCalledFunction();
4997 if (!F)
4999
5000 if (F->isIntrinsic())
5001 return F->getIntrinsicID();
5002
5003 // We are going to infer semantics of a library function based on mapping it
5004 // to an LLVM intrinsic. Check that the library function is available from
5005 // this callbase and in this environment.
5006 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
5008
5009 LibFunc Func = TLI->getLibFunc(CB);
5010 if (Func == NotLibFunc)
5012
5013 switch (Func) {
5014 default:
5015 break;
5016 case LibFunc_sin:
5017 case LibFunc_sinf:
5018 case LibFunc_sinl:
5019 return Intrinsic::sin;
5020 case LibFunc_cos:
5021 case LibFunc_cosf:
5022 case LibFunc_cosl:
5023 return Intrinsic::cos;
5024 case LibFunc_tan:
5025 case LibFunc_tanf:
5026 case LibFunc_tanl:
5027 return Intrinsic::tan;
5028 case LibFunc_asin:
5029 case LibFunc_asinf:
5030 case LibFunc_asinl:
5031 return Intrinsic::asin;
5032 case LibFunc_acos:
5033 case LibFunc_acosf:
5034 case LibFunc_acosl:
5035 return Intrinsic::acos;
5036 case LibFunc_atan:
5037 case LibFunc_atanf:
5038 case LibFunc_atanl:
5039 return Intrinsic::atan;
5040 case LibFunc_atan2:
5041 case LibFunc_atan2f:
5042 case LibFunc_atan2l:
5043 return Intrinsic::atan2;
5044 case LibFunc_sinh:
5045 case LibFunc_sinhf:
5046 case LibFunc_sinhl:
5047 return Intrinsic::sinh;
5048 case LibFunc_cosh:
5049 case LibFunc_coshf:
5050 case LibFunc_coshl:
5051 return Intrinsic::cosh;
5052 case LibFunc_tanh:
5053 case LibFunc_tanhf:
5054 case LibFunc_tanhl:
5055 return Intrinsic::tanh;
5056 case LibFunc_exp:
5057 case LibFunc_expf:
5058 case LibFunc_expl:
5059 return Intrinsic::exp;
5060 case LibFunc_exp2:
5061 case LibFunc_exp2f:
5062 case LibFunc_exp2l:
5063 return Intrinsic::exp2;
5064 case LibFunc_exp10:
5065 case LibFunc_exp10f:
5066 case LibFunc_exp10l:
5067 return Intrinsic::exp10;
5068 case LibFunc_log:
5069 case LibFunc_logf:
5070 case LibFunc_logl:
5071 return Intrinsic::log;
5072 case LibFunc_log10:
5073 case LibFunc_log10f:
5074 case LibFunc_log10l:
5075 return Intrinsic::log10;
5076 case LibFunc_log2:
5077 case LibFunc_log2f:
5078 case LibFunc_log2l:
5079 return Intrinsic::log2;
5080 case LibFunc_fabs:
5081 case LibFunc_fabsf:
5082 case LibFunc_fabsl:
5083 return Intrinsic::fabs;
5084 case LibFunc_fmin:
5085 case LibFunc_fminf:
5086 case LibFunc_fminl:
5087 return Intrinsic::minnum;
5088 case LibFunc_fmax:
5089 case LibFunc_fmaxf:
5090 case LibFunc_fmaxl:
5091 return Intrinsic::maxnum;
5092 case LibFunc_copysign:
5093 case LibFunc_copysignf:
5094 case LibFunc_copysignl:
5095 return Intrinsic::copysign;
5096 case LibFunc_floor:
5097 case LibFunc_floorf:
5098 case LibFunc_floorl:
5099 return Intrinsic::floor;
5100 case LibFunc_ceil:
5101 case LibFunc_ceilf:
5102 case LibFunc_ceill:
5103 return Intrinsic::ceil;
5104 case LibFunc_trunc:
5105 case LibFunc_truncf:
5106 case LibFunc_truncl:
5107 return Intrinsic::trunc;
5108 case LibFunc_rint:
5109 case LibFunc_rintf:
5110 case LibFunc_rintl:
5111 return Intrinsic::rint;
5112 case LibFunc_nearbyint:
5113 case LibFunc_nearbyintf:
5114 case LibFunc_nearbyintl:
5115 return Intrinsic::nearbyint;
5116 case LibFunc_round:
5117 case LibFunc_roundf:
5118 case LibFunc_roundl:
5119 return Intrinsic::round;
5120 case LibFunc_roundeven:
5121 case LibFunc_roundevenf:
5122 case LibFunc_roundevenl:
5123 return Intrinsic::roundeven;
5124 case LibFunc_pow:
5125 case LibFunc_powf:
5126 case LibFunc_powl:
5127 return Intrinsic::pow;
5128 case LibFunc_sqrt:
5129 case LibFunc_sqrtf:
5130 case LibFunc_sqrtl:
5131 return Intrinsic::sqrt;
5132 }
5133
5135}
5136
5137/// Given an exploded icmp instruction, return true if the comparison only
5138/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
5139/// the result of the comparison is true when the input value is signed.
5141 bool &TrueIfSigned) {
5142 switch (Pred) {
5143 case ICmpInst::ICMP_SLT: // True if LHS s< 0
5144 TrueIfSigned = true;
5145 return RHS.isZero();
5146 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
5147 TrueIfSigned = true;
5148 return RHS.isAllOnes();
5149 case ICmpInst::ICMP_SGT: // True if LHS s> -1
5150 TrueIfSigned = false;
5151 return RHS.isAllOnes();
5152 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
5153 TrueIfSigned = false;
5154 return RHS.isZero();
5155 case ICmpInst::ICMP_UGT:
5156 // True if LHS u> RHS and RHS == sign-bit-mask - 1
5157 TrueIfSigned = true;
5158 return RHS.isMaxSignedValue();
5159 case ICmpInst::ICMP_UGE:
5160 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5161 TrueIfSigned = true;
5162 return RHS.isMinSignedValue();
5163 case ICmpInst::ICMP_ULT:
5164 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5165 TrueIfSigned = false;
5166 return RHS.isMinSignedValue();
5167 case ICmpInst::ICMP_ULE:
5168 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
5169 TrueIfSigned = false;
5170 return RHS.isMaxSignedValue();
5171 default:
5172 return false;
5173 }
5174}
5175
5177 bool CondIsTrue,
5178 const Instruction *CtxI,
5179 KnownFPClass &KnownFromContext,
5180 unsigned Depth = 0) {
5181 Value *A, *B;
5183 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
5184 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
5185 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
5186 Depth + 1);
5187 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
5188 Depth + 1);
5189 return;
5190 }
5192 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
5193 Depth + 1);
5194 return;
5195 }
5197 Value *LHS;
5198 uint64_t ClassVal = 0;
5199 const APFloat *CRHS;
5200 const APInt *RHS;
5201 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5202 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5204 LHS != V);
5205 if (CmpVal == V)
5206 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5208 m_Specific(V), m_ConstantInt(ClassVal)))) {
5209 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5210 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5212 m_APInt(RHS)))) {
5213 bool TrueIfSigned;
5214 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5215 return;
5216 if (TrueIfSigned == CondIsTrue)
5217 KnownFromContext.signBitMustBeOne();
5218 else
5219 KnownFromContext.signBitMustBeZero();
5220 }
5221}
5222
5223/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5224/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5225/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5226/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5227/// exponent range is [-149, -2], but the 0 edge case is above this range).
5228static std::tuple<int, int, int>
5230 if (!Q.CtxI || !Q.DC || !Q.DT)
5232
5233 // Intersect the bounds implied by every dominating condition, keeping the
5234 // tightest maximum. A value may participate in multiple compares
5235 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5236 int MaxExp = APFloat::IEK_Inf;
5237 int MaxExpNonZero = APFloat::IEK_Inf;
5238
5239 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5241 const APFloat *LimitC;
5242 if (!match(BI->getCondition(),
5243 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5244 continue;
5245
5248 continue;
5249
5250 // If fabs(x) <= K, implies the exponent min exp range.
5251 // if fabs(x) >= K, swap the successor
5252 bool IsLessEqual =
5256
5257 bool KnownStrictlyLess =
5260
5261 BasicBlockEdge Edge1(BI->getParent(),
5262 BI->getSuccessor(IsLessEqual ? 0 : 1));
5263 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5264 // frexp returns an exponent one greater than ilogb.
5265 int Exp = ilogb(*LimitC) + 1;
5266
5267 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5268 // exponent drops by one when K is exact power of two.
5269 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5270 --Exp;
5271
5272 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5273 // may exclude.
5274
5275 // TODO: Figure out lower bound to detect no-underflow.
5276 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5277 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5278 }
5279 }
5280
5281 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5282}
5283
5285 const SimplifyQuery &Q) {
5286 KnownFPClass KnownFromContext;
5287
5288 if (Q.CC && Q.CC->AffectedValues.contains(V))
5290 KnownFromContext);
5291
5292 if (!Q.CtxI)
5293 return KnownFromContext;
5294
5295 if (Q.DC && Q.DT) {
5296 // Handle dominating conditions.
5297 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5298 Value *Cond = BI->getCondition();
5299
5300 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5301 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5302 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5303 KnownFromContext);
5304
5305 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5306 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5307 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5308 KnownFromContext);
5309 }
5310 }
5311
5312 if (!Q.AC)
5313 return KnownFromContext;
5314
5315 // Try to restrict the floating-point classes based on information from
5316 // assumptions.
5317 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5318 if (!AssumeVH)
5319 continue;
5320 CallInst *I = cast<CallInst>(AssumeVH);
5321
5322 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5323 "Got assumption for the wrong function!");
5324 assert(I->getIntrinsicID() == Intrinsic::assume &&
5325 "must be an assume intrinsic");
5326
5327 if (!isValidAssumeForContext(I, Q))
5328 continue;
5329
5330 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5331 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5332 }
5333
5334 return KnownFromContext;
5335}
5336
5338 Value *Arm, bool Invert,
5339 const SimplifyQuery &SQ,
5340 unsigned Depth) {
5341
5342 KnownFPClass KnownSrc;
5344 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5345 Depth + 1);
5346 KnownSrc = KnownSrc.unionWith(Known);
5347 if (KnownSrc.isUnknown())
5348 return;
5349
5350 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5351 Known = KnownSrc;
5352}
5353
5354void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5355 FPClassTest InterestedClasses, KnownFPClass &Known,
5356 const SimplifyQuery &Q, unsigned Depth);
5357
5359 FPClassTest InterestedClasses,
5360 const SimplifyQuery &Q, unsigned Depth) {
5361 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5362 APInt DemandedElts =
5363 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5364 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5365}
5366
5368 const APInt &DemandedElts,
5369 FPClassTest InterestedClasses,
5371 const SimplifyQuery &Q,
5372 unsigned Depth) {
5373 if ((InterestedClasses & (KnownFPClass::OrderedLessThanZeroMask | fcNan)) ==
5374 fcNone)
5375 return;
5376
5377 KnownFPClass KnownSrc;
5378 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5379 KnownSrc, Q, Depth + 1);
5380
5381 const fltSemantics &DstTy = Op->getType()->getScalarType()->getFltSemantics();
5382 const fltSemantics &SrcTy =
5383 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
5384
5385 const auto *I = dyn_cast<Instruction>(Op);
5386 const Function *F = I ? I->getFunction() : nullptr;
5387 DenormalMode DstMode =
5388 F ? F->getDenormalMode(DstTy) : DenormalMode::getDynamic();
5389 DenormalMode SrcMode =
5390 F ? F->getDenormalMode(SrcTy) : DenormalMode::getDynamic();
5391
5392 Known = KnownFPClass::fptrunc(KnownSrc, DstTy, SrcTy, RM, DstMode, SrcMode);
5393}
5394
5395static void
5397 FPClassTest InterestedClasses,
5398 KnownFPClass &Known, const SimplifyQuery &Q,
5399 unsigned Depth, bool IsAdd, bool IsStrict) {
5400 const Value *LHS = Op->getOperand(0);
5401 const Value *RHS = Op->getOperand(1);
5402
5403 const RoundingMode RM =
5404 IsStrict ? cast<ConstrainedFPIntrinsic>(Op)->getRoundingMode().value_or(
5407
5408 KnownFPClass KnownLHS, KnownRHS;
5409 bool WantNegative =
5410 IsAdd &&
5411 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5412 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5413 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5414 bool WantSubnormal = (InterestedClasses & fcSubnormal) != fcNone;
5415
5416 if (!WantNaN && !WantNegative && !WantNegZero && !WantSubnormal)
5417 return;
5418
5419 FPClassTest InterestedSrcs = InterestedClasses;
5420 if (WantNegative)
5421 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5422 if (InterestedClasses & fcNan)
5423 InterestedSrcs |= fcInf;
5424 computeKnownFPClass(RHS, DemandedElts, InterestedSrcs, KnownRHS, Q,
5425 Depth + 1);
5426
5427 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5428 bool Self = LHS == RHS &&
5429 isGuaranteedNotToBeUndef(LHS, Q.AC, Q.CtxI, Q.DT, Depth + 1);
5430 if (Self)
5431 KnownLHS = KnownRHS;
5432
5433 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5434 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) || WantNegZero ||
5435 WantSubnormal || !IsAdd) {
5436
5437 // FIXME: Context function should always be passed in separately
5438 const Function *F = cast<Instruction>(Op)->getFunction();
5439 const fltSemantics &FltSem =
5440 Op->getType()->getScalarType()->getFltSemantics();
5442 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5443
5444 if (Self && IsAdd) {
5445 Known = KnownFPClass::fadd_self(KnownLHS, RM, Mode);
5446 } else {
5447 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5448 // there's no point.
5449
5450 if (!Self) {
5451 computeKnownFPClass(LHS, DemandedElts, InterestedSrcs, KnownLHS, Q,
5452 Depth + 1);
5453 }
5454
5455 if (const APFloat *CRHS; IsAdd && match(RHS, m_APFloat(CRHS))) {
5456 Known = KnownFPClass::fadd(KnownLHS, *CRHS, RM, Mode);
5457 return;
5458 }
5459
5460 Known = IsAdd ? KnownFPClass::fadd(KnownLHS, KnownRHS, RM, Mode)
5461 : KnownFPClass::fsub(KnownLHS, KnownRHS, RM, Mode);
5462 }
5463 }
5464}
5465
5467 const APInt &DemandedElts,
5468 FPClassTest InterestedClasses,
5470 const SimplifyQuery &Q, unsigned Depth) {
5471 const Value *LHS = Op->getOperand(0);
5472 const Value *RHS = Op->getOperand(1);
5473
5474 FPClassTest InterestedLHS = fcNone;
5475 FPClassTest InterestedRHS = fcNone;
5476
5477 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
5478 if (InterestedClasses & fcNan) {
5479 InterestedLHS |= fcNan | fcInf;
5480 InterestedRHS |= fcNan | fcZero | fcSubnormal;
5481 }
5482
5483 // The sign for frem is the same as the first operand.
5484 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
5485 InterestedLHS |= fcPosNormal | fcPosSubnormal;
5486 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
5487 InterestedLHS |= fcNegNormal | fcNegSubnormal;
5488
5489 // A negative zero result requires a negative finite first operand.
5490 if (InterestedClasses & fcNegZero)
5491 InterestedLHS |= fcNegFinite;
5492
5493 // A positive zero result can additionally come from a negative finite
5494 // result being flushed to positive zero.
5495 if (InterestedClasses & fcPosZero)
5496 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
5497
5498 const Function *F = cast<Instruction>(Op)->getFunction();
5500 F ? F->getDenormalMode(Op->getType()->getScalarType()->getFltSemantics())
5502
5503 if (LHS == RHS && isGuaranteedNotToBeUndef(LHS, Q.AC, Q.CtxI, Q.DT)) {
5504 // X % X is always exactly [+-]0.0 or a NaN.
5505 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
5506 KnownFPClass KnownSrc;
5507 if (InterestedSrcs != fcNone)
5508 computeKnownFPClass(LHS, DemandedElts, InterestedSrcs, KnownSrc, Q,
5509 Depth + 1);
5510 Known = KnownFPClass::frem_self(KnownSrc, Mode);
5511 return;
5512 }
5513
5514 KnownFPClass KnownLHS;
5515 if (InterestedLHS != fcNone)
5516 computeKnownFPClass(LHS, DemandedElts, InterestedLHS, KnownLHS, Q,
5517 Depth + 1);
5518
5519 KnownFPClass KnownRHS;
5520 // RHS is only useful for refining NaN classes.
5521 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
5522 computeKnownFPClass(RHS, DemandedElts, InterestedRHS, KnownRHS, Q,
5523 Depth + 1);
5524
5525 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
5526}
5527
5529 switch (IID) {
5530 case Intrinsic::minimum:
5532 case Intrinsic::maximum:
5534 case Intrinsic::minimumnum:
5536 case Intrinsic::maximumnum:
5538 case Intrinsic::minnum:
5540 case Intrinsic::maxnum:
5542 default:
5543 llvm_unreachable("not a floating-point min-max intrinsic");
5544 }
5545}
5546
5547/// \return true if this is a floating point value that is known to have a
5548/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5549static bool isAbsoluteValueULEOne(const Value *V) {
5550 // TODO: Handle frexp
5551 // TODO: Other rounding intrinsics?
5552 // TODO: Try computeKnownExponentRangeFromContext
5553
5554 // fabs(x - floor(x)) <= 1
5555 const Value *SubFloorX;
5556 if (match(V, m_FSub(m_Value(SubFloorX),
5558 return true;
5559
5562}
5563
5564void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5565 FPClassTest InterestedClasses, KnownFPClass &Known,
5566 const SimplifyQuery &Q, unsigned Depth) {
5567 assert(Known.isUnknown() && "should not be called with known information");
5568
5569 if (!DemandedElts) {
5570 // No demanded elts, better to assume we don't know anything.
5571 Known.resetAll();
5572 return;
5573 }
5574
5575 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5576
5577 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5578 Known = KnownFPClass(CFP->getValueAPF());
5579 return;
5580 }
5581
5583 Known.setKnownFPClasses(fcPosZero);
5584 return;
5585 }
5586
5587 if (isa<PoisonValue>(V)) {
5589 return;
5590 }
5591
5592 // Try to handle fixed width vector constants
5593 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5594 const Constant *CV = dyn_cast<Constant>(V);
5595 if (VFVTy && CV) {
5597
5598 // For vectors, verify that each element is not NaN.
5599 unsigned NumElts = VFVTy->getNumElements();
5600 for (unsigned i = 0; i != NumElts; ++i) {
5601 if (!DemandedElts[i])
5602 continue;
5603
5604 Constant *Elt = CV->getAggregateElement(i);
5605 if (!Elt) {
5606 Known = KnownFPClass();
5607 return;
5608 }
5609 if (isa<PoisonValue>(Elt))
5610 continue;
5611 auto *CElt = dyn_cast<ConstantFP>(Elt);
5612 if (!CElt) {
5613 Known = KnownFPClass();
5614 return;
5615 }
5616
5617 Known |= KnownFPClass(CElt->getValueAPF());
5618 }
5619 return;
5620 }
5621
5622 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5624 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5625 Known |= KnownFPClass(CDS->getElementAsAPFloat(I));
5626 return;
5627 }
5628
5629 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5630 // TODO: Handle complex aggregates
5632 for (const Use &Op : CA->operands()) {
5633 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5634 if (!CFP) {
5635 Known = KnownFPClass();
5636 return;
5637 }
5638
5639 Known |= KnownFPClass(CFP->getValueAPF());
5640 }
5641
5642 return;
5643 }
5644
5645 FPClassTest KnownNotFromFlags = fcNone;
5646 if (const auto *CB = dyn_cast<CallBase>(V))
5647 KnownNotFromFlags |= CB->getRetNoFPClass();
5648 else if (const auto *Arg = dyn_cast<Argument>(V))
5649 KnownNotFromFlags |= Arg->getNoFPClass();
5650
5651 const Operator *Op = dyn_cast<Operator>(V);
5653 if (FPOp->hasNoNaNs())
5654 KnownNotFromFlags |= fcNan;
5655 if (FPOp->hasNoInfs())
5656 KnownNotFromFlags |= fcInf;
5657 }
5658
5659 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5660 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5661
5662 // We no longer need to find out about these bits from inputs if we can
5663 // assume this from flags/attributes.
5664 InterestedClasses &= ~KnownNotFromFlags;
5665
5666 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5667 Known.knownNot(KnownNotFromFlags);
5668 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5669 if (*AssumedClasses.getSignBit())
5670 Known.signBitMustBeOne();
5671 else
5672 Known.signBitMustBeZero();
5673 }
5674 });
5675
5676 if (!Op)
5677 return;
5678
5679 // All recursive calls that increase depth must come after this.
5681 return;
5682
5683 const unsigned Opc = Op->getOpcode();
5684 switch (Opc) {
5685 case Instruction::FNeg: {
5686 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5687 Known, Q, Depth + 1);
5688 Known.fneg();
5689 break;
5690 }
5691 case Instruction::Select: {
5692 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5693 KnownFPClass Res;
5694 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5695 Depth + 1);
5696 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5697 Depth);
5698 return Res;
5699 };
5700 // Only known if known in both the LHS and RHS.
5701 Known =
5702 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5703 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5704 break;
5705 }
5706 case Instruction::Load: {
5707 const MDNode *NoFPClass =
5708 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5709 if (!NoFPClass)
5710 break;
5711
5712 ConstantInt *MaskVal =
5714 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5715 break;
5716 }
5717 case Instruction::Call: {
5718 const CallInst *II = cast<CallInst>(Op);
5719 const Intrinsic::ID IID = II->getIntrinsicID();
5720 switch (IID) {
5721 case Intrinsic::fabs: {
5722 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5723 // If we only care about the sign bit we don't need to inspect the
5724 // operand.
5725 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5726 InterestedClasses, Known, Q, Depth + 1);
5727 }
5728
5729 Known.fabs();
5730 break;
5731 }
5732 case Intrinsic::copysign: {
5733 KnownFPClass KnownSign;
5734
5735 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5736 Known, Q, Depth + 1);
5737 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5738 KnownSign, Q, Depth + 1);
5739 Known.copysign(KnownSign);
5740 break;
5741 }
5742 case Intrinsic::fma:
5743 case Intrinsic::fmuladd: {
5744 if ((InterestedClasses & (fcNegative | fcNan)) == fcNone)
5745 break;
5746
5747 const bool IsFMA = IID == Intrinsic::fma;
5748
5749 // FIXME: This should check isGuaranteedNotToBeUndef
5750 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5751 FPClassTest InterestedSquared = InterestedClasses;
5752 FPClassTest InterestedAddend = InterestedClasses;
5753 // Only fma(+inf, +inf, -inf) and fma(-inf, -inf, -inf) produce NaN when
5754 // squaring.
5755 if (InterestedClasses & fcQNan) {
5756 InterestedSquared |= fcSNan | fcInf;
5757 InterestedAddend |= fcSNan | fcNegInf;
5758 }
5759
5760 KnownFPClass KnownSrc, KnownAddend;
5761 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5762 InterestedAddend, KnownAddend, Q, Depth + 1);
5763 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5764 InterestedSquared, KnownSrc, Q, Depth + 1);
5765
5766 const Function *F = II->getFunction();
5767 const fltSemantics &FltSem =
5768 II->getType()->getScalarType()->getFltSemantics();
5770 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5771
5772 if ((KnownNotFromFlags & fcNan) == fcNan) {
5773 KnownSrc.knownNot(fcNan);
5774 KnownAddend.knownNot(fcNan);
5775 }
5776
5777 if ((KnownNotFromFlags & fcInf) == fcInf) {
5778 KnownSrc.knownNot(fcInf);
5779 KnownAddend.knownNot(fcInf);
5780 }
5781
5782 Known = IsFMA
5783 ? KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode)
5784 : KnownFPClass::fmuladd_square(KnownSrc, KnownAddend, Mode);
5785 break;
5786 }
5787
5788 KnownFPClass KnownSrc[3];
5789 for (int I = 0; I != 3; ++I) {
5790 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5791 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5792 if (KnownSrc[I].isUnknown())
5793 return;
5794
5795 if ((KnownNotFromFlags & fcNan) == fcNan)
5796 KnownSrc[I].knownNot(fcNan);
5797 if ((KnownNotFromFlags & fcInf) == fcInf)
5798 KnownSrc[I].knownNot(fcInf);
5799 }
5800
5801 const Function *F = II->getFunction();
5802 const fltSemantics &FltSem =
5803 II->getType()->getScalarType()->getFltSemantics();
5805 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5806 Known =
5807 IsFMA ? KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode)
5808 : KnownFPClass::fmuladd(KnownSrc[0], KnownSrc[1], KnownSrc[2],
5809 Mode);
5810 break;
5811 }
5812 case Intrinsic::experimental_constrained_fadd:
5813 case Intrinsic::experimental_constrained_fsub: {
5815 Op, DemandedElts, InterestedClasses, Known, Q, Depth,
5816 /*IsAdd=*/IID == Intrinsic::experimental_constrained_fadd,
5817 /*IsStrict=*/true);
5818 break;
5819 }
5820 case Intrinsic::experimental_constrained_frem: {
5821 computeKnownFPClassForFRem(Op, DemandedElts, InterestedClasses, Known, Q,
5822 Depth);
5823 break;
5824 }
5825 case Intrinsic::sqrt:
5826 case Intrinsic::experimental_constrained_sqrt: {
5827 KnownFPClass KnownSrc;
5828 FPClassTest InterestedSrcs = InterestedClasses;
5829 if (InterestedClasses & fcQNan)
5831 // Subnormals may flush to zero.
5832 if (InterestedClasses & fcZero)
5833 InterestedSrcs |= fcSubnormal;
5834
5835 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5836 KnownSrc, Q, Depth + 1);
5837
5839
5840 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5841 if (!HasNSZ) {
5842 const Function *F = II->getFunction();
5843 const fltSemantics &FltSem =
5844 II->getType()->getScalarType()->getFltSemantics();
5845 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5846 }
5847
5848 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5849 if (HasNSZ)
5850 Known.knownNot(fcNegZero);
5851
5852 break;
5853 }
5854 case Intrinsic::sin: {
5855 KnownFPClass KnownSrc;
5856 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5857 KnownSrc, Q, Depth + 1);
5858 Known = KnownFPClass::sin(KnownSrc);
5859 break;
5860 }
5861 case Intrinsic::cos: {
5862 KnownFPClass KnownSrc;
5863 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5864 KnownSrc, Q, Depth + 1);
5865 Known = KnownFPClass::cos(KnownSrc);
5866 break;
5867 }
5868 case Intrinsic::tan: {
5869 KnownFPClass KnownSrc;
5870 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5871 KnownSrc, Q, Depth + 1);
5872 Known = KnownFPClass::tan(KnownSrc);
5873 break;
5874 }
5875 case Intrinsic::sinh: {
5876 KnownFPClass KnownSrc;
5877 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5878 KnownSrc, Q, Depth + 1);
5879 Known = KnownFPClass::sinh(KnownSrc);
5880 break;
5881 }
5882 case Intrinsic::cosh: {
5883 KnownFPClass KnownSrc;
5884 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5885 KnownSrc, Q, Depth + 1);
5886 Known = KnownFPClass::cosh(KnownSrc);
5887 break;
5888 }
5889 case Intrinsic::tanh: {
5890 KnownFPClass KnownSrc;
5891 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5892 KnownSrc, Q, Depth + 1);
5893 Known = KnownFPClass::tanh(KnownSrc);
5894 break;
5895 }
5896 case Intrinsic::asin: {
5897 KnownFPClass KnownSrc;
5898 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5899 KnownSrc, Q, Depth + 1);
5900 Known = KnownFPClass::asin(KnownSrc);
5901 break;
5902 }
5903 case Intrinsic::acos: {
5904 KnownFPClass KnownSrc;
5905 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5906 KnownSrc, Q, Depth + 1);
5907 Known = KnownFPClass::acos(KnownSrc);
5908 break;
5909 }
5910 case Intrinsic::atan: {
5911 KnownFPClass KnownSrc;
5912 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5913 KnownSrc, Q, Depth + 1);
5914 Known = KnownFPClass::atan(KnownSrc);
5915 break;
5916 }
5917 case Intrinsic::atan2: {
5918 FPClassTest InterestedY = InterestedClasses;
5919 FPClassTest InterestedX = InterestedClasses;
5920
5921 // We can rule out negative values if y cannot have a negative value.
5922 if ((InterestedClasses & fcNegFinite) != fcNone)
5923 InterestedY |= fcNegative;
5924
5925 // We can rule out positive values if y cannot have a positive value.
5926 if ((InterestedClasses & fcPosFinite) != fcNone)
5927 InterestedY |= fcPositive | fcNegSubnormal;
5928
5929 // We can rule out zero and subnormal if x cannot have a positive value.
5930 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5931 InterestedX |= fcPositive | fcNegSubnormal;
5932
5933 KnownFPClass KnownY, KnownX;
5934 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5935 KnownY, Q, Depth + 1);
5936 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5937 KnownX, Q, Depth + 1);
5938
5939 const Function *F = II->getFunction();
5941 F ? F->getDenormalMode(
5942 II->getType()->getScalarType()->getFltSemantics())
5944 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5945 break;
5946 }
5947 case Intrinsic::maxnum:
5948 case Intrinsic::minnum:
5949 case Intrinsic::minimum:
5950 case Intrinsic::maximum:
5951 case Intrinsic::minimumnum:
5952 case Intrinsic::maximumnum: {
5953 KnownFPClass KnownLHS, KnownRHS;
5954 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5955 KnownLHS, Q, Depth + 1);
5956 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5957 KnownRHS, Q, Depth + 1);
5958
5959 const Function *F = II->getFunction();
5960
5962 F ? F->getDenormalMode(
5963 II->getType()->getScalarType()->getFltSemantics())
5965
5966 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5967 Mode);
5968 break;
5969 }
5970 case Intrinsic::canonicalize: {
5971 KnownFPClass KnownSrc;
5972 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5973 KnownSrc, Q, Depth + 1);
5974
5975 const Function *F = II->getFunction();
5976 const fltSemantics &Flt =
5977 II->getType()->getScalarType()->getFltSemantics();
5979 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5980 Known = KnownFPClass::canonicalize(KnownSrc, Flt, Mode);
5981 break;
5982 }
5983 case Intrinsic::vector_reduce_fmax:
5984 case Intrinsic::vector_reduce_fmin:
5985 case Intrinsic::vector_reduce_fmaximum:
5986 case Intrinsic::vector_reduce_fminimum:
5987 case Intrinsic::vector_reduce_fmaximumnum:
5988 case Intrinsic::vector_reduce_fminimumnum: {
5989 // reduce min/max will choose an element from one of the vector elements,
5990 // so we can infer and class information that is common to all elements.
5991 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5992 InterestedClasses, Q, Depth + 1);
5993 // Can only propagate sign if output is never NaN.
5994 if (!Known.isKnownNeverNaN())
5995 Known.setSignBit(std::nullopt);
5996 break;
5997 }
5998 // reverse preserves all characteristics of the input vec's element.
5999 case Intrinsic::vector_reverse:
6001 II->getArgOperand(0), DemandedElts.reverseBits(),
6002 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
6003 break;
6004 case Intrinsic::trunc:
6005 case Intrinsic::floor:
6006 case Intrinsic::ceil:
6007 case Intrinsic::rint:
6008 case Intrinsic::nearbyint:
6009 case Intrinsic::round:
6010 case Intrinsic::roundeven: {
6011 KnownFPClass KnownSrc;
6012 FPClassTest InterestedSrcs = InterestedClasses;
6013
6014 // Negative round ups towards zero produce negative zero.
6015 if (InterestedSrcs & fcNegFinite)
6016 InterestedSrcs |= fcNegFinite;
6017
6018 // Negative subnormals may flush to positive zero.
6019 if (InterestedSrcs & fcPosFinite)
6020 InterestedSrcs |= fcPosFinite | fcNegSubnormal;
6021
6022 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
6023 KnownSrc, Q, Depth + 1);
6024
6025 const Function *F = II->getFunction();
6027 F ? F->getDenormalMode(
6028 II->getType()->getScalarType()->getFltSemantics())
6030 const bool IsMultiUnitFPType =
6031 V->getType()->getScalarType()->isMultiUnitFPType();
6032
6033 switch (IID) {
6034 case Intrinsic::trunc:
6035 Known = KnownFPClass::trunc(KnownSrc, Mode);
6036 break;
6037 case Intrinsic::floor:
6038 Known = KnownFPClass::floor(KnownSrc, IsMultiUnitFPType, Mode);
6039 break;
6040 case Intrinsic::ceil:
6041 Known = KnownFPClass::ceil(KnownSrc, IsMultiUnitFPType, Mode);
6042 break;
6043 default:
6044 Known =
6045 KnownFPClass::roundToIntegral(KnownSrc, IsMultiUnitFPType, Mode);
6046 break;
6047 }
6048 break;
6049 }
6050 case Intrinsic::exp:
6051 case Intrinsic::exp2:
6052 case Intrinsic::exp10:
6053 case Intrinsic::amdgcn_exp2: {
6054 KnownFPClass KnownSrc;
6055 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
6056 KnownSrc, Q, Depth + 1);
6057
6058 Known = KnownFPClass::exp(KnownSrc);
6059
6060 Type *EltTy = II->getType()->getScalarType();
6061 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
6062 Known.knownNot(fcSubnormal);
6063
6064 break;
6065 }
6066 case Intrinsic::fptrunc_round: {
6067 Metadata *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
6068 RoundingMode RM =
6069 *convertStrToRoundingMode(cast<MDString>(MD)->getString());
6070 computeKnownFPClassForFPTrunc(Op, RM, DemandedElts, InterestedClasses,
6071 Known, Q, Depth);
6072 break;
6073 }
6074 case Intrinsic::log:
6075 case Intrinsic::log10:
6076 case Intrinsic::log2:
6077 case Intrinsic::experimental_constrained_log:
6078 case Intrinsic::experimental_constrained_log10:
6079 case Intrinsic::experimental_constrained_log2:
6080 case Intrinsic::amdgcn_log: {
6081 FPClassTest InterestedSrcs = fcNone;
6082
6083 // log(negative) produces NaN.
6084 if ((InterestedClasses & fcNan) != fcNone)
6085 InterestedSrcs |= fcNan | fcNegative;
6086
6087 // log(logical-zero) produces negative infinity.
6088 if ((InterestedClasses & fcNegInf) != fcNone)
6089 InterestedSrcs |= fcZero | fcSubnormal;
6090
6091 // log(x) < -0.0 if x < +1.0
6092 if ((InterestedClasses & fcNegNormal) != fcNone)
6093 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
6094
6095 // log(x) >= +0.0 if x >= +1.0
6096 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
6097 InterestedSrcs |= fcPosNormal;
6098
6099 // log(x) is positive infinity iff x is positive infinity.
6100 if ((InterestedClasses & fcPosInf) != fcNone)
6101 InterestedSrcs |= fcPosInf;
6102
6103 KnownFPClass KnownSrc;
6104 if (InterestedSrcs != fcNone)
6105 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
6106 KnownSrc, Q, Depth + 1);
6107 const Function *F = II->getFunction();
6109 F ? F->getDenormalMode(
6110 II->getType()->getScalarType()->getFltSemantics())
6112 const bool IsMultiUnitFPType =
6113 V->getType()->getScalarType()->isMultiUnitFPType();
6114 Known = KnownFPClass::log(KnownSrc, Mode, IsMultiUnitFPType);
6115 break;
6116 }
6117 case Intrinsic::pow: {
6118 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6119 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6120 if (!WantNaN && !WantNegative)
6121 break;
6122
6123 FPClassTest InterestedLHS = fcNone;
6124 FPClassTest InterestedRHS = fcNone;
6125 if (WantNaN) {
6126 // pow may return NaN if one of the arguments is NaN. NaN may also be
6127 // produced from a negative, non-zero finite base and a non-integer
6128 // exponent.
6129 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
6130 InterestedRHS |= fcNan;
6131 }
6132 if (WantNegative) {
6133 // A negative value is returned when a negative base is raised to an odd
6134 // integer power. Only normal values can be odd integers.
6135 InterestedLHS |= fcNegative;
6136 InterestedRHS |= fcNormal;
6137 }
6138
6139 KnownFPClass KnownLHS;
6140 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
6141 KnownLHS, Q, Depth + 1);
6142
6143 // If the LHS is unknown, then querying the RHS is only useful for rare
6144 // edge cases.
6145 if (KnownLHS.isUnknown())
6146 break;
6147
6148 KnownFPClass KnownRHS;
6149 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
6150 KnownRHS, Q, Depth + 1);
6151 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
6152 break;
6153 }
6154 case Intrinsic::powi: {
6155 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
6156 break;
6157
6158 // The exponent is always a scalar, even when raising a vector to a power.
6159 const Value *Exp = II->getArgOperand(1);
6160 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
6161 KnownBits ExponentKnownBits(BitWidth);
6162 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
6163
6164 FPClassTest InterestedSrcs = fcNone;
6165 if (InterestedClasses & fcNan)
6166 InterestedSrcs |= fcNan;
6167 if (!ExponentKnownBits.isZero()) {
6168 if (InterestedClasses & fcInf)
6169 InterestedSrcs |= fcFinite | fcInf;
6170 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
6171 InterestedSrcs |= fcNegative;
6172 }
6173
6174 KnownFPClass KnownSrc;
6175 if (InterestedSrcs != fcNone)
6176 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
6177 KnownSrc, Q, Depth + 1);
6178
6179 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
6180 break;
6181 }
6182 case Intrinsic::ldexp: {
6183 KnownFPClass KnownSrc;
6184 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
6185 KnownSrc, Q, Depth + 1);
6186 // Can refine inf/zero handling based on the exponent operand.
6187 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
6188
6189 const Value *ExpArg = II->getArgOperand(1);
6190 ConstantRange ExpKnownRange =
6191 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
6192 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
6193 : ConstantRange::getFull(
6194 ExpArg->getType()->getScalarSizeInBits());
6195
6196 const fltSemantics &Flt =
6197 II->getType()->getScalarType()->getFltSemantics();
6198
6199 const Function *F = II->getFunction();
6201 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
6202
6203 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
6204 ExpKnownRange.getSignedMax(), Flt, Mode);
6205 break;
6206 }
6207 case Intrinsic::arithmetic_fence: {
6208 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
6209 Known, Q, Depth + 1);
6210 break;
6211 }
6212 case Intrinsic::experimental_constrained_sitofp:
6213 case Intrinsic::experimental_constrained_uitofp:
6214 // Cannot produce nan
6215 Known.knownNot(fcNan);
6216
6217 // sitofp and uitofp turn into +0.0 for zero.
6218 Known.knownNot(fcNegZero);
6219
6220 // Integers cannot be subnormal
6221 Known.knownNot(fcSubnormal);
6222
6223 if (IID == Intrinsic::experimental_constrained_uitofp)
6224 Known.signBitMustBeZero();
6225
6226 // TODO: Copy inf handling from instructions
6227 break;
6228
6229 case Intrinsic::amdgcn_fract: {
6230 Known.knownNot(fcInf);
6231
6232 if (InterestedClasses & fcNan) {
6233 KnownFPClass KnownSrc;
6234 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6235 InterestedClasses, KnownSrc, Q, Depth + 1);
6236
6237 if (KnownSrc.isKnownNeverInfOrNaN())
6238 Known.knownNot(fcNan);
6239 else if (KnownSrc.isKnownNever(fcSNan))
6240 Known.knownNot(fcSNan);
6241 }
6242
6243 break;
6244 }
6245 case Intrinsic::amdgcn_rcp: {
6246 KnownFPClass KnownSrc;
6247 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
6248 KnownSrc, Q, Depth + 1);
6249
6250 Known.propagateNonNaN(KnownSrc);
6251
6252 Type *EltTy = II->getType()->getScalarType();
6253
6254 // f32 denormal always flushed.
6255 if (EltTy->isFloatTy()) {
6256 Known.knownNot(fcSubnormal);
6257 KnownSrc.knownNot(fcSubnormal);
6258 }
6259
6260 if (KnownSrc.isKnownNever(fcNegative))
6261 Known.knownNot(fcNegative);
6262 if (KnownSrc.isKnownNever(fcPositive))
6263 Known.knownNot(fcPositive);
6264
6265 if (const Function *F = II->getFunction()) {
6266 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
6267 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
6268 Known.knownNot(fcPosInf);
6269 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
6270 Known.knownNot(fcNegInf);
6271 }
6272
6273 break;
6274 }
6275 case Intrinsic::amdgcn_rsq: {
6276 KnownFPClass KnownSrc;
6277 // The only negative value that can be returned is -inf for -0 inputs.
6279
6280 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
6281 KnownSrc, Q, Depth + 1);
6282
6283 // Negative -> nan
6284 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
6285 Known.knownNot(fcNan);
6286 else if (KnownSrc.isKnownNever(fcSNan))
6287 Known.knownNot(fcSNan);
6288
6289 // +inf -> +0
6290 if (KnownSrc.isKnownNeverPosInfinity())
6291 Known.knownNot(fcPosZero);
6292
6293 Type *EltTy = II->getType()->getScalarType();
6294
6295 // f32 denormal always flushed.
6296 if (EltTy->isFloatTy())
6297 Known.knownNot(fcPosSubnormal);
6298
6299 if (const Function *F = II->getFunction()) {
6300 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
6301
6302 // -0 -> -inf
6303 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
6304 Known.knownNot(fcNegInf);
6305
6306 // +0 -> +inf
6307 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
6308 Known.knownNot(fcPosInf);
6309 }
6310
6311 break;
6312 }
6313 case Intrinsic::amdgcn_trig_preop: {
6314 // Always returns a value [0, 1)
6315 Known.knownNot(fcNan | fcInf | fcNegative);
6316 break;
6317 }
6318 case Intrinsic::convert_from_arbitrary_fp: {
6319 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
6320 StringRef FormatStr = cast<MDString>(MD)->getString();
6321
6322 const fltSemantics *SrcSemantics =
6324 if (!SrcSemantics)
6325 break;
6326
6327 const fltSemantics DstSemantics =
6328 II->getType()->getScalarType()->getFltSemantics();
6329
6330 if (!APFloat::semanticsHasNaN(*SrcSemantics))
6331 Known.knownNot(fcNan);
6332
6333 // fcInf can only be cleared if the source format has no Inf encoding
6334 // and the dst max exp can accommodate src max exp.
6335 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
6336 APFloat::semanticsMaxExponent(*SrcSemantics) <=
6337 APFloat::semanticsMaxExponent(DstSemantics))
6338 Known.knownNot(fcInf);
6339
6340 // Check and clear all neg flags for formats that do not have signed
6341 // representation.
6342 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
6343 Known.knownNot(fcNegative);
6344
6345 // Check if format has no zero at all (Float8E8M0FNU), or no negative
6346 // zero.
6347 if (!APFloat::semanticsHasZero(*SrcSemantics))
6348 Known.knownNot(fcZero);
6349 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
6350 Known.knownNot(fcNegZero);
6351
6352 // If src lands normally in dest, the result can never be subnormal.
6353 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6354 Known.knownNot(fcSubnormal);
6355 break;
6356 }
6357 default:
6358 break;
6359 }
6360
6361 break;
6362 }
6363 case Instruction::FAdd:
6364 case Instruction::FSub: {
6365 computeKnownFPClassForFAddSub(Op, DemandedElts, InterestedClasses, Known, Q,
6366 Depth, /*IsAdd=*/Opc == Instruction::FAdd,
6367 /*IsStrict=*/false);
6368 break;
6369 }
6370 case Instruction::FMul: {
6371 const Function *F = cast<Instruction>(Op)->getFunction();
6373 F ? F->getDenormalMode(
6374 Op->getType()->getScalarType()->getFltSemantics())
6376
6377 Value *LHS = Op->getOperand(0);
6378 Value *RHS = Op->getOperand(1);
6379 // X * X is always non-negative or a NaN.
6380 // FIXME: Should check isGuaranteedNotToBeUndef
6381 if (LHS == RHS) {
6382 KnownFPClass KnownSrc;
6383 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6384 Depth + 1);
6385 Known = KnownFPClass::square(KnownSrc, Mode);
6386 break;
6387 }
6388
6389 KnownFPClass KnownLHS, KnownRHS;
6390
6391 const APFloat *CRHS;
6392 if (match(RHS, m_APFloat(CRHS))) {
6393 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6394 Depth + 1);
6395 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6396 } else {
6397 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6398 Depth + 1);
6399 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6400 // additional not-nan if the addend is known-not negative infinity if the
6401 // multiply is known-not infinity.
6402
6403 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6404 Depth + 1);
6405 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6406 }
6407
6408 /// Propgate no-infs if the other source is known smaller than one, such
6409 /// that this cannot introduce overflow.
6410 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6411 Known.knownNot(fcInf);
6412 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6413 Known.knownNot(fcInf);
6414
6415 break;
6416 }
6417 case Instruction::FDiv: {
6418 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6419
6420 const Function *F = cast<Instruction>(Op)->getFunction();
6421 const fltSemantics &FltSem =
6422 Op->getType()->getScalarType()->getFltSemantics();
6424 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6425
6426 if (Op->getOperand(0) == Op->getOperand(1) &&
6427 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6428 // X / X is always exactly 1.0 or a NaN.
6429 Known.setKnownFPClasses(fcNan | fcPosNormal);
6430
6431 if (!WantNan)
6432 break;
6433
6434 KnownFPClass KnownSrc;
6435 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6436 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6437 Depth + 1);
6438
6439 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6440 break;
6441 }
6442
6443 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6444 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6445 if (!WantNan && !WantNegative && !WantPositive)
6446 break;
6447
6448 KnownFPClass KnownLHS, KnownRHS;
6449 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6450 Q, Depth + 1);
6451
6452 bool KnowSomethingUseful =
6453 KnownRHS.isKnownNever(fcSNan) ||
6456
6457 if (KnowSomethingUseful)
6458 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6459 Q, Depth + 1);
6460
6461 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6462 break;
6463 }
6464 case Instruction::FRem: {
6465 computeKnownFPClassForFRem(Op, DemandedElts, InterestedClasses, Known, Q,
6466 Depth);
6467 break;
6468 }
6469 case Instruction::FPExt: {
6470 KnownFPClass KnownSrc;
6471 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6472 KnownSrc, Q, Depth + 1);
6473
6474 const fltSemantics &DstTy =
6475 Op->getType()->getScalarType()->getFltSemantics();
6476 const fltSemantics &SrcTy =
6477 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6478
6479 const auto *I = dyn_cast<Instruction>(Op);
6480 const Function *F = I ? I->getFunction() : nullptr;
6481 DenormalMode DstMode =
6482 F ? F->getDenormalMode(DstTy) : DenormalMode::getDynamic();
6483 DenormalMode SrcMode =
6484 F ? F->getDenormalMode(SrcTy) : DenormalMode::getDynamic();
6485
6486 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy, DstMode, SrcMode);
6487 break;
6488 }
6489 case Instruction::FPTrunc: {
6491 DemandedElts, InterestedClasses, Known, Q,
6492 Depth);
6493 break;
6494 }
6495 case Instruction::SIToFP:
6496 case Instruction::UIToFP: {
6497 // Cannot produce nan
6498 Known.knownNot(fcNan);
6499
6500 // Integers cannot be subnormal
6501 Known.knownNot(fcSubnormal);
6502
6503 // sitofp and uitofp turn into +0.0 for zero.
6504 Known.knownNot(fcNegZero);
6505
6506 // UIToFP is always non-negative regardless of known bits.
6507 if (Op->getOpcode() == Instruction::UIToFP)
6508 Known.signBitMustBeZero();
6509
6510 // Only compute known bits if we can learn something useful from them.
6511 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6512 break;
6513
6514 KnownBits IntKnown =
6515 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6516
6517 // If the integer is non-zero, the result cannot be +0.0
6518 if (IntKnown.isNonZero())
6519 Known.knownNot(fcPosZero);
6520
6521 if (Op->getOpcode() == Instruction::SIToFP) {
6522 // If the signed integer is known non-negative, the result is
6523 // non-negative. If the signed integer is known negative, the result is
6524 // negative.
6525 if (IntKnown.isNonNegative()) {
6526 Known.signBitMustBeZero();
6527 } else if (IntKnown.isNegative()) {
6528 Known.signBitMustBeOne();
6529 }
6530 }
6531
6532 // Guard kept for ilogb()
6533 if (InterestedClasses & fcInf) {
6534 // Get width of largest magnitude integer known.
6535 // This still works for a signed minimum value because the largest FP
6536 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6537 int IntSize = IntKnown.getBitWidth();
6538 if (Op->getOpcode() == Instruction::UIToFP)
6539 IntSize -= IntKnown.countMinLeadingZeros();
6540 else if (Op->getOpcode() == Instruction::SIToFP)
6541 IntSize -= IntKnown.countMinSignBits();
6542
6543 // If the exponent of the largest finite FP value can hold the largest
6544 // integer, the result of the cast must be finite.
6545 Type *FPTy = Op->getType()->getScalarType();
6546 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6547 Known.knownNot(fcInf);
6548 }
6549
6550 break;
6551 }
6552 case Instruction::ExtractElement: {
6553 // Look through extract element. If the index is non-constant or
6554 // out-of-range demand all elements, otherwise just the extracted element.
6555 const Value *Vec = Op->getOperand(0);
6556
6557 APInt DemandedVecElts;
6558 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6559 unsigned NumElts = VecTy->getNumElements();
6560 DemandedVecElts = APInt::getAllOnes(NumElts);
6561 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6562 if (CIdx && CIdx->getValue().ult(NumElts))
6563 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6564 } else {
6565 DemandedVecElts = APInt(1, 1);
6566 }
6567
6568 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6569 Q, Depth + 1);
6570 }
6571 case Instruction::InsertElement: {
6572 if (isa<ScalableVectorType>(Op->getType()))
6573 return;
6574
6575 const Value *Vec = Op->getOperand(0);
6576 const Value *Elt = Op->getOperand(1);
6577 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6578 unsigned NumElts = DemandedElts.getBitWidth();
6579 APInt DemandedVecElts = DemandedElts;
6580 bool NeedsElt = true;
6581 // If we know the index we are inserting to, clear it from Vec check.
6582 if (CIdx && CIdx->getValue().ult(NumElts)) {
6583 DemandedVecElts.clearBit(CIdx->getZExtValue());
6584 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6585 }
6586
6587 // Do we demand the inserted element?
6588 if (NeedsElt) {
6589 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6590 // If we don't know any bits, early out.
6591 if (Known.isUnknown())
6592 break;
6593 } else {
6595 }
6596
6597 // Do we need anymore elements from Vec?
6598 if (!DemandedVecElts.isZero()) {
6599 KnownFPClass Known2;
6600 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6601 Depth + 1);
6602 Known |= Known2;
6603 }
6604
6605 break;
6606 }
6607 case Instruction::ShuffleVector: {
6608 // Handle vector splat idiom
6609 if (Value *Splat = getSplatValue(V)) {
6610 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6611 break;
6612 }
6613
6614 // For undef elements, we don't know anything about the common state of
6615 // the shuffle result.
6616 APInt DemandedLHS, DemandedRHS;
6617 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6618 if (!Shuf ||
6619 !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6620 return;
6621
6622 if (!!DemandedLHS) {
6623 const Value *LHS = Shuf->getOperand(0);
6624 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6625 Depth + 1);
6626
6627 // If we don't know any bits, early out.
6628 if (Known.isUnknown())
6629 break;
6630 } else {
6632 }
6633
6634 if (!!DemandedRHS) {
6635 KnownFPClass Known2;
6636 const Value *RHS = Shuf->getOperand(1);
6637 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6638 Depth + 1);
6639 Known |= Known2;
6640 }
6641
6642 break;
6643 }
6644 case Instruction::ExtractValue: {
6645 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6646 ArrayRef<unsigned> Indices = Extract->getIndices();
6647 const Value *Src = Extract->getAggregateOperand();
6648 if (isa<StructType>(Src->getType()) && Indices.size() == 1) {
6649 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6650 switch (II->getIntrinsicID()) {
6651 case Intrinsic::frexp: {
6652 if (Indices[0] != 0)
6653 break;
6654
6655 FPClassTest InterestedSrcs = InterestedClasses;
6656
6657 // Positive subnormals and negative subnormals could become positive
6658 // zero.
6659 if (InterestedClasses & fcPosZero)
6660 InterestedSrcs |= fcSubnormal;
6661
6662 // Negative subnormals could become negative zero.
6663 if (InterestedClasses & fcNegZero)
6664 InterestedSrcs |= fcNegSubnormal;
6665
6666 if (InterestedClasses & fcPosNormal)
6667 InterestedSrcs |= fcPosSubnormal;
6668
6669 if (InterestedClasses & fcNegNormal)
6670 InterestedSrcs |= fcNegSubnormal;
6671
6672 KnownFPClass KnownSrc;
6673 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6674 InterestedSrcs, KnownSrc, Q, Depth + 1);
6675
6676 const Function *F = cast<Instruction>(Op)->getFunction();
6677 const fltSemantics &FltSem =
6678 Op->getType()->getScalarType()->getFltSemantics();
6679
6681 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6682 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6683 return;
6684 }
6685 case Intrinsic::sincospi: {
6686 FPClassTest InterestedSrcs = InterestedClasses;
6687
6688 // Infinite inputs become NaN.
6689 if (InterestedClasses & fcNan)
6690 InterestedSrcs |= fcInf;
6691
6692 KnownFPClass KnownSrc;
6693 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6694 InterestedSrcs, KnownSrc, Q, Depth + 1);
6695
6696 const bool IsMultiUnitFPType =
6697 V->getType()->getScalarType()->isMultiUnitFPType();
6698
6699 if (Indices[0] == 0)
6700 Known = KnownFPClass::sinpi(KnownSrc, IsMultiUnitFPType);
6701 else if (Indices[0] == 1)
6702 Known = KnownFPClass::cospi(KnownSrc, IsMultiUnitFPType);
6703 return;
6704 }
6705 default:
6706 break;
6707 }
6708 }
6709 }
6710
6711 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6712 Depth + 1);
6713 break;
6714 }
6715 case Instruction::PHI: {
6716 const PHINode *P = cast<PHINode>(Op);
6717 // Unreachable blocks may have zero-operand PHI nodes.
6718 if (P->getNumIncomingValues() == 0)
6719 break;
6720
6721 // Otherwise take the unions of the known bit sets of the operands,
6722 // taking conservative care to avoid excessive recursion.
6723 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6724
6725 if (Depth < PhiRecursionLimit) {
6726 // Skip if every incoming value references to ourself.
6727 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6728 break;
6729
6730 bool First = true;
6731
6732 for (const Use &U : P->operands()) {
6733 Value *IncValue;
6734 Instruction *CtxI;
6735 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6736 // Skip direct self references.
6737 if (IncValue == P)
6738 continue;
6739
6740 KnownFPClass KnownSrc;
6741 // Recurse, but cap the recursion to two levels, because we don't want
6742 // to waste time spinning around in loops. We need at least depth 2 to
6743 // detect known sign bits.
6744 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6746 PhiRecursionLimit);
6747
6748 if (First) {
6749 Known = KnownSrc;
6750 First = false;
6751 } else {
6752 Known |= KnownSrc;
6753 }
6754
6755 if (Known.getKnownFPClasses() == fcAllFlags)
6756 break;
6757 }
6758 }
6759
6760 // Look for the case of a for loop which has a positive
6761 // initial value and is incremented by a squared value.
6762 // This will propagate sign information out of such loops.
6763 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6764 break;
6765 for (unsigned I = 0; I < 2; I++) {
6766 Value *RecurValue = P->getIncomingValue(1 - I);
6768 if (!II)
6769 continue;
6770 Value *R, *L, *Init;
6771 PHINode *PN;
6773 PN == P) {
6774 switch (II->getIntrinsicID()) {
6775 case Intrinsic::fma:
6776 case Intrinsic::fmuladd: {
6777 KnownFPClass KnownStart;
6778 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6779 Q, Depth + 1);
6780 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6781 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6783 break;
6784 }
6785 }
6786 }
6787 }
6788 break;
6789 }
6790 case Instruction::BitCast: {
6791 const Value *Src;
6792 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6793 !Src->getType()->isIntOrIntVectorTy())
6794 break;
6795
6796 const Type *Ty = Op->getType();
6797
6798 Value *CastLHS, *CastRHS;
6799
6800 // Match bitcast(umax(bitcast(a), bitcast(b)))
6801 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6802 m_BitCast(m_Value(CastRHS)))) &&
6803 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6804 KnownFPClass KnownLHS, KnownRHS;
6805 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6806 Depth + 1);
6807 if (!KnownRHS.isUnknown()) {
6808 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6809 Q, Depth + 1);
6810 Known = KnownLHS | KnownRHS;
6811 }
6812
6813 return;
6814 }
6815
6816 const Type *EltTy = Ty->getScalarType();
6817 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6818 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6819
6821 break;
6822 }
6823 default:
6824 break;
6825 }
6826}
6827
6829 const APInt &DemandedElts,
6830 FPClassTest InterestedClasses,
6831 const SimplifyQuery &SQ,
6832 unsigned Depth) {
6833 KnownFPClass KnownClasses;
6834 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6835 Depth);
6836 return KnownClasses;
6837}
6838
6840 FPClassTest InterestedClasses,
6841 const SimplifyQuery &SQ,
6842 unsigned Depth) {
6844 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6845 return Known;
6846}
6847
6849 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6850 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6851 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6852 return computeKnownFPClass(V, InterestedClasses,
6853 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6854 Depth);
6855}
6856
6858llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6859 FastMathFlags FMF, FPClassTest InterestedClasses,
6860 const SimplifyQuery &SQ, unsigned Depth) {
6861 if (FMF.noNaNs())
6862 InterestedClasses &= ~fcNan;
6863 if (FMF.noInfs())
6864 InterestedClasses &= ~fcInf;
6865
6866 KnownFPClass Result =
6867 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6868
6869 if (FMF.noNaNs())
6870 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6871 if (FMF.noInfs())
6872 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6873 return Result;
6874}
6875
6877 FPClassTest InterestedClasses,
6878 const SimplifyQuery &SQ,
6879 unsigned Depth) {
6880 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6881 APInt DemandedElts =
6882 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6883 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6884 Depth);
6885}
6886
6888 unsigned Depth) {
6890 return Known.isKnownNever(fcNegZero);
6891}
6892
6894 unsigned Depth) {
6897 return Known.cannotBeOrderedLessThanZero();
6898}
6899
6901 unsigned Depth) {
6903 return Known.isKnownNeverInfinity();
6904}
6905
6906/// Return true if the floating-point value can never contain a NaN or infinity.
6908 unsigned Depth) {
6910 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6911}
6912
6913/// Return true if the floating-point scalar value is not a NaN or if the
6914/// floating-point vector value has no NaN elements. Return false if a value
6915/// could ever be NaN.
6917 unsigned Depth) {
6919 return Known.isKnownNeverNaN();
6920}
6921
6922/// Return false if we can prove that the specified FP value's sign bit is 0.
6923/// Return true if we can prove that the specified FP value's sign bit is 1.
6924/// Otherwise return std::nullopt.
6925std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6926 const SimplifyQuery &SQ,
6927 unsigned Depth) {
6929 return Known.getSignBit();
6930}
6931
6933 auto *User = cast<Instruction>(U.getUser());
6934 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6935 if (FPOp->hasNoSignedZeros())
6936 return true;
6937 }
6938
6939 switch (User->getOpcode()) {
6940 case Instruction::FPToSI:
6941 case Instruction::FPToUI:
6942 return true;
6943 case Instruction::FRem:
6944 // frem(x, +-0.0) == NaN, and more generally frem(x, y) == frem(x, -y).
6945 return U.getOperandNo() == 1;
6946 case Instruction::FCmp:
6947 // fcmp treats both positive and negative zero as equal.
6948 return true;
6949 case Instruction::Call:
6950 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6951 switch (II->getIntrinsicID()) {
6952 case Intrinsic::fabs:
6953 case Intrinsic::exp:
6954 case Intrinsic::exp2:
6955 case Intrinsic::exp10:
6956 case Intrinsic::log:
6957 case Intrinsic::log2:
6958 case Intrinsic::log10:
6959 case Intrinsic::cos:
6960 case Intrinsic::acos:
6961 case Intrinsic::cosh:
6962 case Intrinsic::fptosi_sat:
6963 case Intrinsic::fptoui_sat:
6964 case Intrinsic::lround:
6965 case Intrinsic::llround:
6966 case Intrinsic::lrint:
6967 case Intrinsic::llrint:
6968 return true;
6969 case Intrinsic::copysign:
6970 return U.getOperandNo() == 0;
6971 case Intrinsic::pow:
6972 // pow(x, +-0.0) == +1.0 or NaN
6973 return U.getOperandNo() == 1;
6974 case Intrinsic::is_fpclass: {
6975 auto Test =
6976 static_cast<FPClassTest>(
6977 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6980 }
6981 default:
6982 return false;
6983 }
6984 }
6985 return false;
6986 default:
6987 return false;
6988 }
6989}
6990
6992 auto *User = cast<Instruction>(U.getUser());
6993 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6994 if (FPOp->hasNoNaNs())
6995 return true;
6996 }
6997
6998 switch (User->getOpcode()) {
6999 case Instruction::FPToSI:
7000 case Instruction::FPToUI:
7001 return true;
7002 // Proper FP math operations ignore the sign bit of NaN.
7003 case Instruction::FAdd:
7004 case Instruction::FSub:
7005 case Instruction::FMul:
7006 case Instruction::FDiv:
7007 case Instruction::FRem:
7008 case Instruction::FPTrunc:
7009 case Instruction::FPExt:
7010 case Instruction::FCmp:
7011 return true;
7012 // Bitwise FP operations should preserve the sign bit of NaN.
7013 case Instruction::FNeg:
7014 case Instruction::Select:
7015 case Instruction::PHI:
7016 return false;
7017 case Instruction::Ret:
7018 return User->getFunction()->getAttributes().getRetNoFPClass() &
7020 case Instruction::Call:
7021 case Instruction::Invoke: {
7022 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
7023 switch (II->getIntrinsicID()) {
7024 case Intrinsic::fabs:
7025 return true;
7026 case Intrinsic::copysign:
7027 return U.getOperandNo() == 0;
7028 // Other proper FP math intrinsics ignore the sign bit of NaN.
7029 case Intrinsic::maxnum:
7030 case Intrinsic::minnum:
7031 case Intrinsic::maximum:
7032 case Intrinsic::minimum:
7033 case Intrinsic::maximumnum:
7034 case Intrinsic::minimumnum:
7035 case Intrinsic::canonicalize:
7036 case Intrinsic::fptrunc_round:
7037 case Intrinsic::fma:
7038 case Intrinsic::fmuladd:
7039 case Intrinsic::ldexp:
7040 case Intrinsic::frexp:
7041 case Intrinsic::modf:
7042 case Intrinsic::sqrt:
7043 case Intrinsic::exp:
7044 case Intrinsic::exp2:
7045 case Intrinsic::exp10:
7046 case Intrinsic::log:
7047 case Intrinsic::log2:
7048 case Intrinsic::log10:
7049 case Intrinsic::pow:
7050 case Intrinsic::powi:
7051 case Intrinsic::sin:
7052 case Intrinsic::cos:
7053 case Intrinsic::sincos:
7054 case Intrinsic::sincospi:
7055 case Intrinsic::tan:
7056 case Intrinsic::asin:
7057 case Intrinsic::acos:
7058 case Intrinsic::atan:
7059 case Intrinsic::atan2:
7060 case Intrinsic::sinh:
7061 case Intrinsic::cosh:
7062 case Intrinsic::tanh:
7063 case Intrinsic::trunc:
7064 case Intrinsic::floor:
7065 case Intrinsic::ceil:
7066 case Intrinsic::round:
7067 case Intrinsic::roundeven:
7068 case Intrinsic::nearbyint:
7069 case Intrinsic::rint:
7070 case Intrinsic::fptoui_sat:
7071 case Intrinsic::fptosi_sat:
7072 case Intrinsic::lround:
7073 case Intrinsic::llround:
7074 case Intrinsic::lrint:
7075 case Intrinsic::llrint:
7076 case Intrinsic::is_fpclass:
7077 return true;
7078 default:
7079 return false;
7080 }
7081 }
7082
7083 FPClassTest NoFPClass =
7084 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
7085 return NoFPClass & FPClassTest::fcNan;
7086 }
7087 default:
7088 return false;
7089 }
7090}
7091
7093 FastMathFlags FMF) {
7094 if (isa<PoisonValue>(V))
7095 return true;
7096 if (isa<UndefValue>(V))
7097 return false;
7098
7099 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
7100 return true;
7101
7103 if (!I)
7104 return false;
7105
7106 switch (I->getOpcode()) {
7107 case Instruction::SIToFP:
7108 case Instruction::UIToFP:
7109 // TODO: Could check nofpclass(inf) on incoming argument
7110 if (FMF.noInfs())
7111 return true;
7112
7113 // Need to check int size cannot produce infinity, which computeKnownFPClass
7114 // knows how to do already.
7115 return isKnownNeverInfinity(I, SQ);
7116 case Instruction::Call: {
7117 const CallInst *CI = cast<CallInst>(I);
7118 switch (CI->getIntrinsicID()) {
7119 case Intrinsic::trunc:
7120 case Intrinsic::floor:
7121 case Intrinsic::ceil:
7122 case Intrinsic::rint:
7123 case Intrinsic::nearbyint:
7124 case Intrinsic::round:
7125 case Intrinsic::roundeven:
7126 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
7127 default:
7128 break;
7129 }
7130
7131 break;
7132 }
7133 default:
7134 break;
7135 }
7136
7137 return false;
7138}
7139
7141
7142 // All byte-wide stores are splatable, even of arbitrary variables.
7143 if (V->getType()->isIntegerTy(8))
7144 return V;
7145
7146 LLVMContext &Ctx = V->getContext();
7147
7148 // Undef don't care.
7149 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
7150 if (isa<UndefValue>(V))
7151 return UndefInt8;
7152
7153 // Return poison for zero-sized type.
7154 if (DL.getTypeStoreSize(V->getType()).isZero())
7155 return PoisonValue::get(Type::getInt8Ty(Ctx));
7156
7158 if (!C) {
7159 // Conceptually, we could handle things like:
7160 // %a = zext i8 %X to i16
7161 // %b = shl i16 %a, 8
7162 // %c = or i16 %a, %b
7163 // but until there is an example that actually needs this, it doesn't seem
7164 // worth worrying about.
7165 return nullptr;
7166 }
7167
7168 // Handle 'null' ConstantArrayZero etc.
7169 if (C->isNullValue())
7171
7172 // Constant floating-point values can be handled as integer values if the
7173 // corresponding integer value is "byteable". An important case is 0.0.
7174 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
7175 Type *ScalarTy = CFP->getType()->getScalarType();
7176 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
7177 return isBytewiseValue(
7178 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
7179
7180 // Don't handle long double formats, which have strange constraints.
7181 return nullptr;
7182 }
7183
7184 // We can handle constant integers that are multiple of 8 bits.
7185 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
7186 if (CI->getBitWidth() % 8 == 0) {
7187 if (!CI->getValue().isSplat(8))
7188 return nullptr;
7189 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
7190 }
7191 }
7192
7193 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
7194 if (CE->getOpcode() == Instruction::IntToPtr) {
7195 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
7196 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
7198 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
7199 return isBytewiseValue(Op, DL);
7200 }
7201 }
7202 }
7203
7204 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
7205 if (LHS == RHS)
7206 return LHS;
7207 if (!LHS || !RHS)
7208 return nullptr;
7209 if (LHS == UndefInt8)
7210 return RHS;
7211 if (RHS == UndefInt8)
7212 return LHS;
7213 return nullptr;
7214 };
7215
7217 Value *Val = UndefInt8;
7218 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
7219 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
7220 return nullptr;
7221 return Val;
7222 }
7223
7225 Value *Val = UndefInt8;
7226 for (Value *Op : C->operands())
7227 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
7228 return nullptr;
7229 return Val;
7230 }
7231
7232 // Don't try to handle the handful of other constants.
7233 return nullptr;
7234}
7235
7236// This is the recursive version of BuildSubAggregate. It takes a few different
7237// arguments. Idxs is the index within the nested struct From that we are
7238// looking at now (which is of type IndexedType). IdxSkip is the number of
7239// indices from Idxs that should be left out when inserting into the resulting
7240// struct. To is the result struct built so far, new insertvalue instructions
7241// build on that.
7242static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
7244 unsigned IdxSkip,
7245 BasicBlock::iterator InsertBefore) {
7246 StructType *STy = dyn_cast<StructType>(IndexedType);
7247 if (STy) {
7248 // Save the original To argument so we can modify it
7249 Value *OrigTo = To;
7250 // General case, the type indexed by Idxs is a struct
7251 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
7252 // Process each struct element recursively
7253 Idxs.push_back(i);
7254 Value *PrevTo = To;
7255 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
7256 InsertBefore);
7257 Idxs.pop_back();
7258 if (!To) {
7259 // Couldn't find any inserted value for this index? Cleanup
7260 while (PrevTo != OrigTo) {
7262 PrevTo = Del->getAggregateOperand();
7263 Del->eraseFromParent();
7264 }
7265 // Stop processing elements
7266 break;
7267 }
7268 }
7269 // If we successfully found a value for each of our subaggregates
7270 if (To)
7271 return To;
7272 }
7273 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
7274 // the struct's elements had a value that was inserted directly. In the latter
7275 // case, perhaps we can't determine each of the subelements individually, but
7276 // we might be able to find the complete struct somewhere.
7277
7278 // Find the value that is at that particular spot
7279 Value *V = FindInsertedValue(From, Idxs);
7280
7281 if (!V)
7282 return nullptr;
7283
7284 // Insert the value in the new (sub) aggregate
7285 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
7286 InsertBefore);
7287}
7288
7289// This helper takes a nested struct and extracts a part of it (which is again a
7290// struct) into a new value. For example, given the struct:
7291// { a, { b, { c, d }, e } }
7292// and the indices "1, 1" this returns
7293// { c, d }.
7294//
7295// It does this by inserting an insertvalue for each element in the resulting
7296// struct, as opposed to just inserting a single struct. This will only work if
7297// each of the elements of the substruct are known (ie, inserted into From by an
7298// insertvalue instruction somewhere).
7299//
7300// All inserted insertvalue instructions are inserted before InsertBefore
7302 BasicBlock::iterator InsertBefore) {
7303 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
7304 idx_range);
7305 Value *To = PoisonValue::get(IndexedType);
7306 SmallVector<unsigned, 10> Idxs(idx_range);
7307 unsigned IdxSkip = Idxs.size();
7308
7309 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
7310}
7311
7312/// Given an aggregate and a sequence of indices, see if the scalar value
7313/// indexed is already around as a register, for example if it was inserted
7314/// directly into the aggregate.
7315///
7316/// If InsertBefore is not null, this function will duplicate (modified)
7317/// insertvalues when a part of a nested struct is extracted.
7318Value *
7320 std::optional<BasicBlock::iterator> InsertBefore) {
7321 // Nothing to index? Just return V then (this is useful at the end of our
7322 // recursion).
7323 if (idx_range.empty())
7324 return V;
7325 // We have indices, so V should have an indexable type.
7326 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
7327 "Not looking at a struct or array?");
7328 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
7329 "Invalid indices for type?");
7330
7331 if (Constant *C = dyn_cast<Constant>(V)) {
7332 C = C->getAggregateElement(idx_range[0]);
7333 if (!C) return nullptr;
7334 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
7335 }
7336
7338 // Loop the indices for the insertvalue instruction in parallel with the
7339 // requested indices
7340 const unsigned *req_idx = idx_range.begin();
7341 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7342 i != e; ++i, ++req_idx) {
7343 if (req_idx == idx_range.end()) {
7344 // We can't handle this without inserting insertvalues
7345 if (!InsertBefore)
7346 return nullptr;
7347
7348 // The requested index identifies a part of a nested aggregate. Handle
7349 // this specially. For example,
7350 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7351 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7352 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7353 // This can be changed into
7354 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7355 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7356 // which allows the unused 0,0 element from the nested struct to be
7357 // removed.
7358 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7359 *InsertBefore);
7360 }
7361
7362 // This insert value inserts something else than what we are looking for.
7363 // See if the (aggregate) value inserted into has the value we are
7364 // looking for, then.
7365 if (*req_idx != *i)
7366 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7367 InsertBefore);
7368 }
7369 // If we end up here, the indices of the insertvalue match with those
7370 // requested (though possibly only partially). Now we recursively look at
7371 // the inserted value, passing any remaining indices.
7372 return FindInsertedValue(I->getInsertedValueOperand(),
7373 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7374 }
7375
7377 // If we're extracting a value from an aggregate that was extracted from
7378 // something else, we can extract from that something else directly instead.
7379 // However, we will need to chain I's indices with the requested indices.
7380
7381 // Calculate the number of indices required
7382 unsigned size = I->getNumIndices() + idx_range.size();
7383 // Allocate some space to put the new indices in
7385 Idxs.reserve(size);
7386 // Add indices from the extract value instruction
7387 Idxs.append(I->idx_begin(), I->idx_end());
7388
7389 // Add requested indices
7390 Idxs.append(idx_range.begin(), idx_range.end());
7391
7392 assert(Idxs.size() == size
7393 && "Number of indices added not correct?");
7394
7395 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7396 }
7397 // Otherwise, we don't know (such as, extracting from a function return value
7398 // or load instruction)
7399 return nullptr;
7400}
7401
7402// If V refers to an initialized global constant, set Slice either to
7403// its initializer if the size of its elements equals ElementSize, or,
7404// for ElementSize == 8, to its representation as an array of unsiged
7405// char. Return true on success.
7406// Offset is in the unit "nr of ElementSize sized elements".
7409 unsigned ElementSize, uint64_t Offset) {
7410 assert(V && "V should not be null.");
7411 assert((ElementSize % 8) == 0 &&
7412 "ElementSize expected to be a multiple of the size of a byte.");
7413 unsigned ElementSizeInBytes = ElementSize / 8;
7414
7415 // Drill down into the pointer expression V, ignoring any intervening
7416 // casts, and determine the identity of the object it references along
7417 // with the cumulative byte offset into it.
7418 const GlobalVariable *GV =
7420 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7421 // Fail if V is not based on constant global object.
7422 return false;
7423
7424 const DataLayout &DL = GV->getDataLayout();
7425 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7426
7428 /*AllowNonInbounds*/ true))
7429 // Fail if a constant offset could not be determined.
7430 return false;
7431
7432 uint64_t StartIdx = Off.getLimitedValue();
7433 if (StartIdx == UINT64_MAX)
7434 // Fail if the constant offset is excessive.
7435 return false;
7436
7437 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7438 // elements. Simply bail out if that isn't possible.
7439 if ((StartIdx % ElementSizeInBytes) != 0)
7440 return false;
7441
7442 Offset += StartIdx / ElementSizeInBytes;
7443 ConstantDataArray *Array = nullptr;
7444 ArrayType *ArrayTy = nullptr;
7445
7446 if (GV->getInitializer()->isNullValue()) {
7447 Type *GVTy = GV->getValueType();
7448 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7449 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7450
7451 Slice.Array = nullptr;
7452 Slice.Offset = 0;
7453 // Return an empty Slice for undersized constants to let callers
7454 // transform even undefined library calls into simpler, well-defined
7455 // expressions. This is preferable to making the calls although it
7456 // prevents sanitizers from detecting such calls.
7457 Slice.Length = Length < Offset ? 0 : Length - Offset;
7458 return true;
7459 }
7460
7461 auto *Init = const_cast<Constant *>(GV->getInitializer());
7462 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7463 Type *InitElTy = ArrayInit->getElementType();
7464 if (InitElTy->isIntegerTy(ElementSize)) {
7465 // If Init is an initializer for an array of the expected type
7466 // and size, use it as is.
7467 Array = ArrayInit;
7468 ArrayTy = ArrayInit->getType();
7469 }
7470 }
7471
7472 if (!Array) {
7473 if (ElementSize != 8)
7474 // TODO: Handle conversions to larger integral types.
7475 return false;
7476
7477 // Otherwise extract the portion of the initializer starting
7478 // at Offset as an array of bytes, and reset Offset.
7480 if (!Init)
7481 return false;
7482
7483 Offset = 0;
7485 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7486 }
7487
7488 uint64_t NumElts = ArrayTy->getArrayNumElements();
7489 if (Offset > NumElts)
7490 return false;
7491
7492 Slice.Array = Array;
7493 Slice.Offset = Offset;
7494 Slice.Length = NumElts - Offset;
7495 return true;
7496}
7497
7498/// Extract bytes from the initializer of the constant array V, which need
7499/// not be a nul-terminated string. On success, store the bytes in Str and
7500/// return true. When TrimAtNul is set, Str will contain only the bytes up
7501/// to but not including the first nul. Return false on failure.
7503 bool TrimAtNul) {
7505 if (!getConstantDataArrayInfo(V, Slice, 8))
7506 return false;
7507
7508 if (Slice.Array == nullptr) {
7509 if (TrimAtNul) {
7510 // Return a nul-terminated string even for an empty Slice. This is
7511 // safe because all existing SimplifyLibcalls callers require string
7512 // arguments and the behavior of the functions they fold is undefined
7513 // otherwise. Folding the calls this way is preferable to making
7514 // the undefined library calls, even though it prevents sanitizers
7515 // from reporting such calls.
7516 Str = StringRef();
7517 return true;
7518 }
7519 if (Slice.Length == 1) {
7520 Str = StringRef("", 1);
7521 return true;
7522 }
7523 // We cannot instantiate a StringRef as we do not have an appropriate string
7524 // of 0s at hand.
7525 return false;
7526 }
7527
7528 // Start out with the entire array in the StringRef.
7529 Str = Slice.Array->getAsString();
7530 // Skip over 'offset' bytes.
7531 Str = Str.substr(Slice.Offset);
7532
7533 if (TrimAtNul) {
7534 // Trim off the \0 and anything after it. If the array is not nul
7535 // terminated, we just return the whole end of string. The client may know
7536 // some other way that the string is length-bound.
7537 Str = Str.substr(0, Str.find('\0'));
7538 }
7539 return true;
7540}
7541
7542// These next two are very similar to the above, but also look through PHI
7543// nodes.
7544// TODO: See if we can integrate these two together.
7545
7546/// If we can compute the length of the string pointed to by
7547/// the specified pointer, return 'len+1'. If we can't, return 0.
7550 unsigned CharSize) {
7551 // Look through noop bitcast instructions.
7552 V = V->stripPointerCasts();
7553
7554 // If this is a PHI node, there are two cases: either we have already seen it
7555 // or we haven't.
7556 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7557 if (!PHIs.insert(PN).second)
7558 return ~0ULL; // already in the set.
7559
7560 // If it was new, see if all the input strings are the same length.
7561 uint64_t LenSoFar = ~0ULL;
7562 for (Value *IncValue : PN->incoming_values()) {
7563 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7564 if (Len == 0) return 0; // Unknown length -> unknown.
7565
7566 if (Len == ~0ULL) continue;
7567
7568 if (Len != LenSoFar && LenSoFar != ~0ULL)
7569 return 0; // Disagree -> unknown.
7570 LenSoFar = Len;
7571 }
7572
7573 // Success, all agree.
7574 return LenSoFar;
7575 }
7576
7577 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7578 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7579 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7580 if (Len1 == 0) return 0;
7581 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7582 if (Len2 == 0) return 0;
7583 if (Len1 == ~0ULL) return Len2;
7584 if (Len2 == ~0ULL) return Len1;
7585 if (Len1 != Len2) return 0;
7586 return Len1;
7587 }
7588
7589 // Otherwise, see if we can read the string.
7591 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7592 return 0;
7593
7594 if (Slice.Array == nullptr)
7595 // Zeroinitializer (including an empty one).
7596 return 1;
7597
7598 // Search for the first nul character. Return a conservative result even
7599 // when there is no nul. This is safe since otherwise the string function
7600 // being folded such as strlen is undefined, and can be preferable to
7601 // making the undefined library call.
7602 unsigned NullIndex = 0;
7603 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7604 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7605 break;
7606 }
7607
7608 return NullIndex + 1;
7609}
7610
7611/// If we can compute the length of the string pointed to by
7612/// the specified pointer, return 'len+1'. If we can't, return 0.
7613uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7614 if (!V->getType()->isPointerTy())
7615 return 0;
7616
7618 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7619 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7620 // an empty string as a length.
7621 return Len == ~0ULL ? 1 : Len;
7622}
7623
7624const Value *
7626 bool MustPreserveOffset,
7627 bool MustPreserveProvenance) {
7628 assert(Call &&
7629 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7630 if (const Value *RV = Call->getReturnedArgOperand())
7631 return RV;
7632 // This can be used only as a aliasing property.
7634 Call, MustPreserveOffset, MustPreserveProvenance))
7635 return Call->getArgOperand(0);
7636 return nullptr;
7637}
7638
7640 const CallBase *Call, bool MustPreserveOffset,
7641 bool MustPreserveProvenance) {
7642 switch (Call->getIntrinsicID()) {
7643 case Intrinsic::launder_invariant_group:
7644 case Intrinsic::aarch64_irg:
7645 case Intrinsic::aarch64_tagp:
7646 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7647 // input pointer (and thus preserves the byte offset, which is the property
7648 // the MustPreserveOffset flag selects). However, it will not necessarily
7649 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7650 // descriptor", which has "all loads return 0, all stores are dropped"
7651 // semantics. Given the context of this intrinsic list, no one should be
7652 // relying on such a strict bit-exact null mapping (and, at time of
7653 // writing, they are not), but we document this fact out of an abundance
7654 // of caution.
7655 case Intrinsic::amdgcn_make_buffer_rsrc:
7656 return !MustPreserveProvenance;
7657 case Intrinsic::ptrmask:
7658 return !MustPreserveOffset;
7659 case Intrinsic::threadlocal_address:
7660 // The underlying variable changes with thread ID. The Thread ID may change
7661 // at coroutine suspend points.
7662 return !Call->getParent()->getParent()->isPresplitCoroutine();
7663 default:
7664 return false;
7665 }
7666}
7667
7668/// \p PN defines a loop-variant pointer to an object. Check if the
7669/// previous iteration of the loop was referring to the same object as \p PN.
7671 const LoopInfo *LI) {
7672 // Find the loop-defined value.
7673 Loop *L = LI->getLoopFor(PN->getParent());
7674 if (PN->getNumIncomingValues() != 2)
7675 return true;
7676
7677 // Find the value from previous iteration.
7678 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7679 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7680 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7681 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7682 return true;
7683
7684 // If a new pointer is loaded in the loop, the pointer references a different
7685 // object in every iteration. E.g.:
7686 // for (i)
7687 // int *p = a[i];
7688 // ...
7689 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7690 if (!L->isLoopInvariant(Load->getPointerOperand()))
7691 return false;
7692 return true;
7693}
7694
7695const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7696 bool MustPreserveProvenance) {
7697 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7698 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7699 const Value *PtrOp = GEP->getPointerOperand();
7700 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7701 return V;
7702 V = PtrOp;
7703 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7704 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7705 Value *NewV = cast<Operator>(V)->getOperand(0);
7706 if (!NewV->getType()->isPointerTy())
7707 return V;
7708 V = NewV;
7709 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7710 if (GA->isInterposable())
7711 return V;
7712 V = GA->getAliasee();
7713 } else {
7714 if (auto *PHI = dyn_cast<PHINode>(V)) {
7715 // Look through single-arg phi nodes created by LCSSA.
7716 if (PHI->getNumIncomingValues() == 1) {
7717 V = PHI->getIncomingValue(0);
7718 continue;
7719 }
7720 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7721 // CaptureTracking can know about special capturing properties of some
7722 // intrinsics like launder.invariant.group, that can't be expressed with
7723 // the attributes, but have properties like returning aliasing pointer.
7724 // Because some analysis may assume that nocaptured pointer is not
7725 // returned from some special intrinsic (because function would have to
7726 // be marked with returns attribute), it is crucial to use this function
7727 // because it should be in sync with CaptureTracking. Not using it may
7728 // cause weird miscompilations where 2 aliasing pointers are assumed to
7729 // noalias.
7731 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7732 V = RP;
7733 continue;
7734 }
7735 }
7736
7737 return V;
7738 }
7739 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7740 }
7741 return V;
7742}
7743
7746 const LoopInfo *LI, unsigned MaxLookup) {
7749 Worklist.push_back(V);
7750 do {
7751 const Value *P = Worklist.pop_back_val();
7752 P = getUnderlyingObject(P, MaxLookup);
7753
7754 if (!Visited.insert(P).second)
7755 continue;
7756
7757 if (auto *SI = dyn_cast<SelectInst>(P)) {
7758 Worklist.push_back(SI->getTrueValue());
7759 Worklist.push_back(SI->getFalseValue());
7760 continue;
7761 }
7762
7763 if (auto *PN = dyn_cast<PHINode>(P)) {
7764 // If this PHI changes the underlying object in every iteration of the
7765 // loop, don't look through it. Consider:
7766 // int **A;
7767 // for (i) {
7768 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7769 // Curr = A[i];
7770 // *Prev, *Curr;
7771 //
7772 // Prev is tracking Curr one iteration behind so they refer to different
7773 // underlying objects.
7774 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7776 append_range(Worklist, PN->incoming_values());
7777 else
7778 Objects.push_back(P);
7779 continue;
7780 }
7781
7782 Objects.push_back(P);
7783 } while (!Worklist.empty());
7784}
7785
7787 bool MustPreserveProvenance) {
7788 const unsigned MaxVisited = 8;
7789
7792 Worklist.push_back(V);
7793 const Value *Object = nullptr;
7794 // Used as fallback if we can't find a common underlying object through
7795 // recursion.
7796 bool First = true;
7797 const Value *FirstObject =
7798 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7799 do {
7800 const Value *P = Worklist.pop_back_val();
7801 P = First ? FirstObject
7803 MustPreserveProvenance);
7804 First = false;
7805
7806 if (!Visited.insert(P).second)
7807 continue;
7808
7809 if (Visited.size() == MaxVisited)
7810 return FirstObject;
7811
7812 if (auto *SI = dyn_cast<SelectInst>(P)) {
7813 Worklist.push_back(SI->getTrueValue());
7814 Worklist.push_back(SI->getFalseValue());
7815 continue;
7816 }
7817
7818 if (auto *PN = dyn_cast<PHINode>(P)) {
7819 append_range(Worklist, PN->incoming_values());
7820 continue;
7821 }
7822
7823 if (!Object)
7824 Object = P;
7825 else if (Object != P)
7826 return FirstObject;
7827 } while (!Worklist.empty());
7828
7829 return Object ? Object : FirstObject;
7830}
7831
7832/// This is the function that does the work of looking through basic
7833/// ptrtoint+arithmetic+inttoptr sequences.
7835 do {
7836 if (const Operator *U = dyn_cast<Operator>(V)) {
7837 // If we find a ptrtoint, we can transfer control back to the
7838 // regular getUnderlyingObjectFromInt.
7839 if (U->getOpcode() == Instruction::PtrToInt)
7840 return U->getOperand(0);
7841 // If we find an add of a constant, a multiplied value, or a phi, it's
7842 // likely that the other operand will lead us to the base
7843 // object. We don't have to worry about the case where the
7844 // object address is somehow being computed by the multiply,
7845 // because our callers only care when the result is an
7846 // identifiable object.
7847 if (U->getOpcode() != Instruction::Add ||
7848 (!isa<ConstantInt>(U->getOperand(1)) &&
7849 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7850 !isa<PHINode>(U->getOperand(1))))
7851 return V;
7852 V = U->getOperand(0);
7853 } else {
7854 return V;
7855 }
7856 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7857 } while (true);
7858}
7859
7860/// This is a wrapper around getUnderlyingObjects and adds support for basic
7861/// ptrtoint+arithmetic+inttoptr sequences.
7862/// It returns false if unidentified object is found in getUnderlyingObjects.
7864 SmallVectorImpl<Value *> &Objects) {
7866 SmallVector<const Value *, 4> Working(1, V);
7867 bool AllObjectsIdentified = true;
7868 do {
7869 V = Working.pop_back_val();
7870
7872 getUnderlyingObjects(V, Objs);
7873
7874 for (const Value *V : Objs) {
7875 if (!Visited.insert(V).second)
7876 continue;
7877 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7878 const Value *O =
7879 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7880 if (O->getType()->isPointerTy()) {
7881 Working.push_back(O);
7882 continue;
7883 }
7884 }
7885 AllObjectsIdentified &= isIdentifiedObject(V);
7886 Objects.push_back(const_cast<Value *>(V));
7887 }
7888 } while (!Working.empty());
7889 return AllObjectsIdentified;
7890}
7891
7893 AllocaInst *Result = nullptr;
7895 SmallVector<Value *, 4> Worklist;
7896
7897 auto AddWork = [&](Value *V) {
7898 if (Visited.insert(V).second)
7899 Worklist.push_back(V);
7900 };
7901
7902 AddWork(V);
7903 do {
7904 V = Worklist.pop_back_val();
7905 assert(Visited.count(V));
7906
7907 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7908 if (Result && Result != AI)
7909 return nullptr;
7910 Result = AI;
7911 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7912 AddWork(CI->getOperand(0));
7913 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7914 for (Value *IncValue : PN->incoming_values())
7915 AddWork(IncValue);
7916 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7917 AddWork(SI->getTrueValue());
7918 AddWork(SI->getFalseValue());
7920 if (OffsetZero && !GEP->hasAllZeroIndices())
7921 return nullptr;
7922 AddWork(GEP->getPointerOperand());
7923 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7924 Value *Returned = CB->getReturnedArgOperand();
7925 if (Returned)
7926 AddWork(Returned);
7927 else
7928 return nullptr;
7929 } else {
7930 return nullptr;
7931 }
7932 } while (!Worklist.empty());
7933
7934 return Result;
7935}
7936
7938 if (auto *II = dyn_cast<IntrinsicInst>(I))
7939 return isTriviallyVectorizable(II->getIntrinsicID());
7940 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7941 return (!Shuffle || Shuffle->isSelect()) &&
7943}
7944
7946 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7947 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7948 bool IgnoreUBImplyingAttrs) {
7949 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7950 AC, DT, TLI, UseVariableInfo,
7951 IgnoreUBImplyingAttrs);
7952}
7953
7955 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7956 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7957 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7958#ifndef NDEBUG
7959 if (Inst->getOpcode() != Opcode) {
7960 // Check that the operands are actually compatible with the Opcode override.
7961 auto hasEqualReturnAndLeadingOperandTypes =
7962 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7963 if (Inst->getNumOperands() < NumLeadingOperands)
7964 return false;
7965 const Type *ExpectedType = Inst->getType();
7966 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7967 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7968 return false;
7969 return true;
7970 };
7972 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7973 assert(!Instruction::isUnaryOp(Opcode) ||
7974 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7975 }
7976#endif
7977
7978 switch (Opcode) {
7979 default:
7980 return true;
7981 case Instruction::UDiv:
7982 case Instruction::URem: {
7983 // x / y is undefined if y == 0.
7984 const APInt *V;
7985 if (match(Inst->getOperand(1), m_APInt(V)))
7986 return *V != 0;
7987 return false;
7988 }
7989 case Instruction::SDiv:
7990 case Instruction::SRem: {
7991 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7992 const APInt *Numerator, *Denominator;
7993 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7994 return false;
7995 // We cannot hoist this division if the denominator is 0.
7996 if (*Denominator == 0)
7997 return false;
7998 // It's safe to hoist if the denominator is not 0 or -1.
7999 if (!Denominator->isAllOnes())
8000 return true;
8001 // At this point we know that the denominator is -1. It is safe to hoist as
8002 // long we know that the numerator is not INT_MIN.
8003 if (match(Inst->getOperand(0), m_APInt(Numerator)))
8004 return !Numerator->isMinSignedValue();
8005 // The numerator *might* be MinSignedValue.
8006 return false;
8007 }
8008 case Instruction::Load: {
8009 if (!UseVariableInfo)
8010 return false;
8011
8012 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
8013 if (!LI)
8014 return false;
8015 if (mustSuppressSpeculation(*LI))
8016 return false;
8017 const DataLayout &DL = LI->getDataLayout();
8019 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
8020 SimplifyQuery(DL, TLI, DT, AC, CtxI));
8021 }
8022 case Instruction::Call: {
8023 auto *CI = dyn_cast<const CallInst>(Inst);
8024 if (!CI)
8025 return false;
8026 const Function *Callee = CI->getCalledFunction();
8027
8028 // The called function could have undefined behavior or side-effects, even
8029 // if marked readnone nounwind.
8030 if (!Callee || !Callee->isSpeculatable())
8031 return false;
8032 // Since the operands may be changed after hoisting, undefined behavior may
8033 // be triggered by some UB-implying attributes.
8034 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
8035 }
8036 case Instruction::VAArg:
8037 case Instruction::Alloca:
8038 case Instruction::Invoke:
8039 case Instruction::CallBr:
8040 case Instruction::PHI:
8041 case Instruction::Store:
8042 case Instruction::Ret:
8043 case Instruction::UncondBr:
8044 case Instruction::CondBr:
8045 case Instruction::IndirectBr:
8046 case Instruction::Switch:
8047 case Instruction::Unreachable:
8048 case Instruction::Fence:
8049 case Instruction::AtomicRMW:
8050 case Instruction::AtomicCmpXchg:
8051 case Instruction::LandingPad:
8052 case Instruction::Resume:
8053 case Instruction::CatchSwitch:
8054 case Instruction::CatchPad:
8055 case Instruction::CatchRet:
8056 case Instruction::CleanupPad:
8057 case Instruction::CleanupRet:
8058 return false; // Misc instructions which have effects
8059 }
8060}
8061
8063 if (I.mayReadOrWriteMemory())
8064 // Memory dependency possible
8065 return true;
8067 // Can't move above a maythrow call or infinite loop. Or if an
8068 // inalloca alloca, above a stacksave call.
8069 return true;
8071 // 1) Can't reorder two inf-loop calls, even if readonly
8072 // 2) Also can't reorder an inf-loop call below a instruction which isn't
8073 // safe to speculative execute. (Inverse of above)
8074 return true;
8075 return false;
8076}
8077
8078/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
8092
8093/// Combine constant ranges from computeConstantRange() and computeKnownBits().
8096 bool ForSigned,
8097 const SimplifyQuery &SQ) {
8098 ConstantRange CR1 =
8099 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
8100 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
8103 return CR1.intersectWith(CR2, RangeType);
8104}
8105
8107 const Value *RHS,
8108 const SimplifyQuery &SQ,
8109 bool IsNSW) {
8110 ConstantRange LHSRange =
8111 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
8112 ConstantRange RHSRange =
8113 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
8114
8115 // mul nsw of two non-negative numbers is also nuw.
8116 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
8118
8119 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
8120}
8121
8123 const Value *RHS,
8124 const SimplifyQuery &SQ) {
8125 // Multiplying n * m significant bits yields a result of n + m significant
8126 // bits. If the total number of significant bits does not exceed the
8127 // result bit width (minus 1), there is no overflow.
8128 // This means if we have enough leading sign bits in the operands
8129 // we can guarantee that the result does not overflow.
8130 // Ref: "Hacker's Delight" by Henry Warren
8131 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
8132
8133 // Note that underestimating the number of sign bits gives a more
8134 // conservative answer.
8135 unsigned SignBits =
8136 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
8137
8138 // First handle the easy case: if we have enough sign bits there's
8139 // definitely no overflow.
8140 if (SignBits > BitWidth + 1)
8142
8143 // There are two ambiguous cases where there can be no overflow:
8144 // SignBits == BitWidth + 1 and
8145 // SignBits == BitWidth
8146 // The second case is difficult to check, therefore we only handle the
8147 // first case.
8148 if (SignBits == BitWidth + 1) {
8149 // It overflows only when both arguments are negative and the true
8150 // product is exactly the minimum negative number.
8151 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
8152 // For simplicity we just check if at least one side is not negative.
8153 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
8154 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
8155 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
8157 }
8159}
8160
8163 const WithCache<const Value *> &RHS,
8164 const SimplifyQuery &SQ) {
8165 ConstantRange LHSRange =
8166 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
8167 ConstantRange RHSRange =
8168 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
8169 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
8170}
8171
8172static OverflowResult
8175 const AddOperator *Add, const SimplifyQuery &SQ) {
8176 if (Add && Add->hasNoSignedWrap()) {
8178 }
8179
8180 // If LHS and RHS each have at least two sign bits, the addition will look
8181 // like
8182 //
8183 // XX..... +
8184 // YY.....
8185 //
8186 // If the carry into the most significant position is 0, X and Y can't both
8187 // be 1 and therefore the carry out of the addition is also 0.
8188 //
8189 // If the carry into the most significant position is 1, X and Y can't both
8190 // be 0 and therefore the carry out of the addition is also 1.
8191 //
8192 // Since the carry into the most significant position is always equal to
8193 // the carry out of the addition, there is no signed overflow.
8194 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
8196
8197 ConstantRange LHSRange =
8198 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
8199 ConstantRange RHSRange =
8200 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
8201 OverflowResult OR =
8202 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
8204 return OR;
8205
8206 // The remaining code needs Add to be available. Early returns if not so.
8207 if (!Add)
8209
8210 // If the sign of Add is the same as at least one of the operands, this add
8211 // CANNOT overflow. If this can be determined from the known bits of the
8212 // operands the above signedAddMayOverflow() check will have already done so.
8213 // The only other way to improve on the known bits is from an assumption, so
8214 // call computeKnownBitsFromContext() directly.
8215 bool LHSOrRHSKnownNonNegative =
8216 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
8217 bool LHSOrRHSKnownNegative =
8218 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
8219 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
8220 KnownBits AddKnown(LHSRange.getBitWidth());
8221 computeKnownBitsFromContext(Add, AddKnown, SQ);
8222 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
8223 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
8225 }
8226
8228}
8229
8231 const Value *RHS,
8232 const SimplifyQuery &SQ) {
8233 // X - (X % ?)
8234 // The remainder of a value can't have greater magnitude than itself,
8235 // so the subtraction can't overflow.
8236
8237 // X - (X -nuw ?)
8238 // In the minimal case, this would simplify to "?", so there's no subtract
8239 // at all. But if this analysis is used to peek through casts, for example,
8240 // then determining no-overflow may allow other transforms.
8241
8242 // TODO: There are other patterns like this.
8243 // See simplifyICmpWithBinOpOnLHS() for candidates.
8244 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
8245 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
8246 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8248
8249 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
8250 SQ.DL)) {
8251 if (*C)
8254 }
8255
8256 ConstantRange LHSRange =
8257 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
8258 ConstantRange RHSRange =
8259 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
8260 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
8261}
8262
8264 const Value *RHS,
8265 const SimplifyQuery &SQ) {
8266 // X - (X % ?)
8267 // The remainder of a value can't have greater magnitude than itself,
8268 // so the subtraction can't overflow.
8269
8270 // X - (X -nsw ?)
8271 // In the minimal case, this would simplify to "?", so there's no subtract
8272 // at all. But if this analysis is used to peek through casts, for example,
8273 // then determining no-overflow may allow other transforms.
8274 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
8275 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
8276 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8278
8279 // If LHS and RHS each have at least two sign bits, the subtraction
8280 // cannot overflow.
8281 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
8283
8284 ConstantRange LHSRange =
8285 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
8286 ConstantRange RHSRange =
8287 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
8288 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
8289}
8290
8292 const DominatorTree &DT) {
8293 SmallVector<const CondBrInst *, 2> GuardingBranches;
8295
8296 for (const User *U : WO->users()) {
8297 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
8298 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
8299
8300 if (EVI->getIndices()[0] == 0)
8301 Results.push_back(EVI);
8302 else {
8303 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
8304
8305 for (const auto *U : EVI->users())
8306 if (const auto *B = dyn_cast<CondBrInst>(U))
8307 GuardingBranches.push_back(B);
8308 }
8309 } else {
8310 // We are using the aggregate directly in a way we don't want to analyze
8311 // here (storing it to a global, say).
8312 return false;
8313 }
8314 }
8315
8316 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8317 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8318
8319 // Check if all users of the add are provably no-wrap.
8320 for (const auto *Result : Results) {
8321 // If the extractvalue itself is not executed on overflow, the we don't
8322 // need to check each use separately, since domination is transitive.
8323 if (DT.dominates(NoWrapEdge, Result->getParent()))
8324 continue;
8325
8326 for (const auto &RU : Result->uses())
8327 if (!DT.dominates(NoWrapEdge, RU))
8328 return false;
8329 }
8330
8331 return true;
8332 };
8333
8334 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8335}
8336
8337/// Shifts return poison if shiftwidth is larger than the bitwidth.
8338static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8339 auto *C = dyn_cast<Constant>(ShiftAmount);
8340 if (!C)
8341 return false;
8342
8343 // Shifts return poison if shiftwidth is larger than the bitwidth.
8345 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8346 unsigned NumElts = FVTy->getNumElements();
8347 for (unsigned i = 0; i < NumElts; ++i)
8348 ShiftAmounts.push_back(C->getAggregateElement(i));
8349 } else if (isa<ScalableVectorType>(C->getType()))
8350 return false; // Can't tell, just return false to be safe
8351 else
8352 ShiftAmounts.push_back(C);
8353
8354 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8355 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8356 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8357 });
8358
8359 return Safe;
8360}
8361
8363 bool ConsiderFlagsAndMetadata) {
8364 const auto *CB = dyn_cast<CallBase>(Op);
8365 bool CBHasNoUndef = CB && CB->hasRetAttr(Attribute::NoUndef);
8366 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8367 Op->hasPoisonGeneratingAnnotations() && !CBHasNoUndef)
8368 return true;
8369
8370 unsigned Opcode = Op->getOpcode();
8371
8372 // Check whether opcode is a poison/undef-generating operation
8373 switch (Opcode) {
8374 case Instruction::Shl:
8375 case Instruction::AShr:
8376 case Instruction::LShr:
8377 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8378 case Instruction::FPToSI:
8379 case Instruction::FPToUI:
8380 // fptosi/ui yields poison if the resulting value does not fit in the
8381 // destination type.
8382 return true;
8383 case Instruction::Call:
8384 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8385 switch (II->getIntrinsicID()) {
8386 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8387 case Intrinsic::ctlz:
8388 case Intrinsic::cttz:
8389 case Intrinsic::abs:
8390 // We're not considering flags so it is safe to just return false.
8391 return false;
8392 case Intrinsic::sshl_sat:
8393 case Intrinsic::ushl_sat:
8394 if (!includesPoison(Kind) ||
8395 shiftAmountKnownInRange(II->getArgOperand(1)))
8396 return false;
8397 break;
8398 }
8399 }
8400 [[fallthrough]];
8401 case Instruction::CallBr:
8402 case Instruction::Invoke: {
8403 return !CBHasNoUndef && !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8404 }
8405 case Instruction::InsertElement:
8406 case Instruction::ExtractElement: {
8407 // If index exceeds the length of the vector, it returns poison
8408 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8409 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8410 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8411 if (includesPoison(Kind))
8412 return !Idx ||
8413 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8414 return false;
8415 }
8416 case Instruction::ShuffleVector: {
8418 ? cast<ConstantExpr>(Op)->getShuffleMask()
8419 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8420 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8421 }
8422 case Instruction::FNeg:
8423 case Instruction::PHI:
8424 case Instruction::Select:
8425 case Instruction::ExtractValue:
8426 case Instruction::InsertValue:
8427 case Instruction::Freeze:
8428 case Instruction::ICmp:
8429 case Instruction::FCmp:
8430 case Instruction::GetElementPtr:
8431 return false;
8432 case Instruction::AddrSpaceCast:
8433 return true;
8434 default: {
8435 const auto *CE = dyn_cast<ConstantExpr>(Op);
8436 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8437 return false;
8438 else if (Instruction::isBinaryOp(Opcode))
8439 return false;
8440 // Be conservative and return true.
8441 return true;
8442 }
8443 }
8444}
8445
8447 bool ConsiderFlagsAndMetadata) {
8448 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8449 ConsiderFlagsAndMetadata);
8450}
8451
8452bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8453 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8454 ConsiderFlagsAndMetadata);
8455}
8456
8457static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8458 unsigned Depth) {
8459 if (ValAssumedPoison == V)
8460 return true;
8461
8462 const unsigned MaxDepth = 2;
8463 if (Depth >= MaxDepth)
8464 return false;
8465
8466 if (const auto *I = dyn_cast<Instruction>(V)) {
8467 if (any_of(I->operands(), [=](const Use &Op) {
8468 return propagatesPoison(Op) &&
8469 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8470 }))
8471 return true;
8472
8473 // V = extractvalue V0, idx
8474 // V2 = extractvalue V0, idx2
8475 // V0's elements are all poison or not. (e.g., add_with_overflow)
8476 const WithOverflowInst *II;
8478 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8479 llvm::is_contained(II->args(), ValAssumedPoison)))
8480 return true;
8481 }
8482 return false;
8483}
8484
8485static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8486 unsigned Depth) {
8487 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8488 return true;
8489
8490 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8491 return true;
8492
8493 const unsigned MaxDepth = 2;
8494 if (Depth >= MaxDepth)
8495 return false;
8496
8497 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8498 if (I && !canCreatePoison(cast<Operator>(I))) {
8499 return all_of(I->operands(), [=](const Value *Op) {
8500 return impliesPoison(Op, V, Depth + 1);
8501 });
8502 }
8503 return false;
8504}
8505
8506bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8507 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8508}
8509
8510static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8511
8513 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8514 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8516 return false;
8517
8519 return false;
8520
8521 if (const auto *A = dyn_cast<Argument>(V)) {
8522 if (A->hasAttribute(Attribute::NoUndef) ||
8523 A->hasAttribute(Attribute::Dereferenceable) ||
8524 A->hasAttribute(Attribute::DereferenceableOrNull))
8525 return true;
8526 }
8527
8528 if (auto *C = dyn_cast<Constant>(V)) {
8529 if (isa<PoisonValue>(C))
8530 return !includesPoison(Kind);
8531
8532 if (isa<UndefValue>(C))
8533 return !includesUndef(Kind);
8534
8537 return true;
8538
8539 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8540 if (isa<ConstantExpr>(C)) {
8541 // Scalable vectors can use a ConstantExpr to build a splat.
8542 if (Constant *SplatC = C->getSplatValue())
8543 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8544 return true;
8545 } else if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
8546 return all_of(CA->operands(), [&](const Use &Op) {
8547 return isGuaranteedNotToBeUndefOrPoison(Op.get(), AC, CtxI, DT,
8548 Depth + 1, Kind);
8549 });
8550 }
8551 }
8552 }
8553
8554 // Strip cast operations from a pointer value.
8555 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8556 // inbounds with zero offset. To guarantee that the result isn't poison, the
8557 // stripped pointer is checked as it has to be pointing into an allocated
8558 // object or be null `null` to ensure `inbounds` getelement pointers with a
8559 // zero offset could not produce poison.
8560 // It can strip off addrspacecast that do not change bit representation as
8561 // well. We believe that such addrspacecast is equivalent to no-op.
8562 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8563 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8564 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8565 return true;
8566
8567 auto OpCheck = [&](const Value *V) {
8568 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8569 };
8570
8571 if (auto *Opr = dyn_cast<Operator>(V)) {
8572 // If the value is a freeze instruction, then it can never
8573 // be undef or poison.
8574 if (isa<FreezeInst>(V))
8575 return true;
8576
8577 if (const auto *CB = dyn_cast<CallBase>(V)) {
8578 if (CB->hasRetAttr(Attribute::NoUndef) ||
8579 CB->hasRetAttr(Attribute::Dereferenceable) ||
8580 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8581 return true;
8582 }
8583
8584 if (!::canCreateUndefOrPoison(Opr, Kind,
8585 /*ConsiderFlagsAndMetadata=*/true)) {
8586 if (const auto *PN = dyn_cast<PHINode>(V)) {
8587 unsigned Num = PN->getNumIncomingValues();
8588 bool IsWellDefined = true;
8589 for (unsigned i = 0; i < Num; ++i) {
8590 if (PN == PN->getIncomingValue(i))
8591 continue;
8592 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8593 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8594 DT, Depth + 1, Kind)) {
8595 IsWellDefined = false;
8596 break;
8597 }
8598 }
8599 if (IsWellDefined)
8600 return true;
8601 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8602 : nullptr) {
8603 // For splats we only need to check the value being splatted.
8604 if (OpCheck(Splat))
8605 return true;
8606 } else if (all_of(Opr->operands(), OpCheck))
8607 return true;
8608 }
8609 }
8610
8611 if (auto *I = dyn_cast<LoadInst>(V))
8612 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8613 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8614 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8615 return true;
8616
8618 return true;
8619
8620 // CtxI may be null or a cloned instruction.
8621 if (!CtxI || !CtxI->getParent() || !DT)
8622 return false;
8623
8624 auto *DNode = DT->getNode(CtxI->getParent());
8625 if (!DNode)
8626 // Unreachable block
8627 return false;
8628
8629 // If V is used as a branch condition before reaching CtxI, V cannot be
8630 // undef or poison.
8631 // br V, BB1, BB2
8632 // BB1:
8633 // CtxI ; V cannot be undef or poison here
8634 auto *Dominator = DNode->getIDom();
8635 // This check is purely for compile time reasons: we can skip the IDom walk
8636 // if what we are checking for includes undef and the value is not an integer.
8637 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8638 while (Dominator) {
8639 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8640
8641 Value *Cond = nullptr;
8642 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8643 Cond = BI->getCondition();
8644 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8645 Cond = SI->getCondition();
8646 }
8647
8648 if (Cond) {
8649 if (Cond == V)
8650 return true;
8651 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8652 // For poison, we can analyze further
8653 auto *Opr = cast<Operator>(Cond);
8654 if (any_of(Opr->operands(), [V](const Use &U) {
8655 return V == U && propagatesPoison(U);
8656 }))
8657 return true;
8658 }
8659 }
8660
8661 Dominator = Dominator->getIDom();
8662 }
8663
8664 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8665 return true;
8666
8667 return false;
8668}
8669
8671 const Instruction *CtxI,
8672 const DominatorTree *DT,
8673 unsigned Depth) {
8674 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8676}
8677
8679 const Instruction *CtxI,
8680 const DominatorTree *DT, unsigned Depth) {
8681 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8683}
8684
8686 const Instruction *CtxI,
8687 const DominatorTree *DT, unsigned Depth) {
8688 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8690}
8691
8692/// Return true if undefined behavior would provably be executed on the path to
8693/// OnPathTo if Root produced a posion result. Note that this doesn't say
8694/// anything about whether OnPathTo is actually executed or whether Root is
8695/// actually poison. This can be used to assess whether a new use of Root can
8696/// be added at a location which is control equivalent with OnPathTo (such as
8697/// immediately before it) without introducing UB which didn't previously
8698/// exist. Note that a false result conveys no information.
8700 Instruction *OnPathTo,
8701 DominatorTree *DT) {
8702 // Basic approach is to assume Root is poison, propagate poison forward
8703 // through all users we can easily track, and then check whether any of those
8704 // users are provable UB and must execute before out exiting block might
8705 // exit.
8706
8707 // The set of all recursive users we've visited (which are assumed to all be
8708 // poison because of said visit)
8711 Worklist.push_back(Root);
8712 while (!Worklist.empty()) {
8713 const Instruction *I = Worklist.pop_back_val();
8714
8715 // If we know this must trigger UB on a path leading our target.
8716 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8717 return true;
8718
8719 // If we can't analyze propagation through this instruction, just skip it
8720 // and transitive users. Safe as false is a conservative result.
8721 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8722 return KnownPoison.contains(U) && propagatesPoison(U);
8723 }))
8724 continue;
8725
8726 if (KnownPoison.insert(I).second)
8727 for (const User *User : I->users())
8728 Worklist.push_back(cast<Instruction>(User));
8729 }
8730
8731 // Might be non-UB, or might have a path we couldn't prove must execute on
8732 // way to exiting bb.
8733 return false;
8734}
8735
8737 const SimplifyQuery &SQ) {
8738 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8739 Add, SQ);
8740}
8741
8744 const WithCache<const Value *> &RHS,
8745 const SimplifyQuery &SQ) {
8746 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8747}
8748
8750 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8751 // of time because it's possible for another thread to interfere with it for an
8752 // arbitrary length of time, but programs aren't allowed to rely on that.
8753
8754 // If there is no successor, then execution can't transfer to it.
8755 if (isa<ReturnInst>(I))
8756 return false;
8758 return false;
8759
8760 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8761 // Instruction::willReturn.
8762 //
8763 // FIXME: Move this check into Instruction::willReturn.
8764 if (isa<CatchPadInst>(I)) {
8765 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8766 default:
8767 // A catchpad may invoke exception object constructors and such, which
8768 // in some languages can be arbitrary code, so be conservative by default.
8769 return false;
8771 // For CoreCLR, it just involves a type test.
8772 return true;
8773 }
8774 }
8775
8776 // An instruction that returns without throwing must transfer control flow
8777 // to a successor.
8778 return !I->mayThrow() && I->willReturn();
8779}
8780
8782 // TODO: This is slightly conservative for invoke instruction since exiting
8783 // via an exception *is* normal control for them.
8784 for (const Instruction &I : *BB)
8786 return false;
8787 return true;
8788}
8789
8796
8799 assert(ScanLimit && "scan limit must be non-zero");
8800 for (const Instruction &I : Range) {
8801 if (--ScanLimit == 0)
8802 return false;
8804 return false;
8805 }
8806 return true;
8807}
8808
8810 const Loop *L) {
8811 // The loop header is guaranteed to be executed for every iteration.
8812 //
8813 // FIXME: Relax this constraint to cover all basic blocks that are
8814 // guaranteed to be executed at every iteration.
8815 if (I->getParent() != L->getHeader()) return false;
8816
8817 for (const Instruction &LI : *L->getHeader()) {
8818 if (&LI == I) return true;
8819 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8820 }
8821 llvm_unreachable("Instruction not contained in its own parent basic block.");
8822}
8823
8825 switch (IID) {
8826 // TODO: Add more intrinsics.
8827 case Intrinsic::sadd_with_overflow:
8828 case Intrinsic::ssub_with_overflow:
8829 case Intrinsic::smul_with_overflow:
8830 case Intrinsic::uadd_with_overflow:
8831 case Intrinsic::usub_with_overflow:
8832 case Intrinsic::umul_with_overflow:
8833 // If an input is a vector containing a poison element, the
8834 // two output vectors (calculated results, overflow bits)'
8835 // corresponding lanes are poison.
8836 return true;
8837 case Intrinsic::ctpop:
8838 case Intrinsic::ctlz:
8839 case Intrinsic::cttz:
8840 case Intrinsic::abs:
8841 case Intrinsic::smax:
8842 case Intrinsic::smin:
8843 case Intrinsic::umax:
8844 case Intrinsic::umin:
8845 case Intrinsic::scmp:
8846 case Intrinsic::smulh:
8847 case Intrinsic::umulh:
8848 case Intrinsic::is_fpclass:
8849 case Intrinsic::ptrmask:
8850 case Intrinsic::ucmp:
8851 case Intrinsic::bitreverse:
8852 case Intrinsic::bswap:
8853 case Intrinsic::sadd_sat:
8854 case Intrinsic::ssub_sat:
8855 case Intrinsic::sshl_sat:
8856 case Intrinsic::uadd_sat:
8857 case Intrinsic::usub_sat:
8858 case Intrinsic::ushl_sat:
8859 case Intrinsic::smul_fix:
8860 case Intrinsic::smul_fix_sat:
8861 case Intrinsic::umul_fix:
8862 case Intrinsic::umul_fix_sat:
8863 case Intrinsic::pow:
8864 case Intrinsic::experimental_constrained_pow:
8865 case Intrinsic::powi:
8866 case Intrinsic::experimental_constrained_powi:
8867 case Intrinsic::sin:
8868 case Intrinsic::experimental_constrained_sin:
8869 case Intrinsic::sinh:
8870 case Intrinsic::experimental_constrained_sinh:
8871 case Intrinsic::cos:
8872 case Intrinsic::experimental_constrained_cos:
8873 case Intrinsic::cosh:
8874 case Intrinsic::experimental_constrained_cosh:
8875 case Intrinsic::sincos:
8876 case Intrinsic::sincospi:
8877 case Intrinsic::tan:
8878 case Intrinsic::experimental_constrained_tan:
8879 case Intrinsic::tanh:
8880 case Intrinsic::experimental_constrained_tanh:
8881 case Intrinsic::asin:
8882 case Intrinsic::experimental_constrained_asin:
8883 case Intrinsic::acos:
8884 case Intrinsic::experimental_constrained_acos:
8885 case Intrinsic::atan:
8886 case Intrinsic::experimental_constrained_atan:
8887 case Intrinsic::atan2:
8888 case Intrinsic::experimental_constrained_atan2:
8889 case Intrinsic::canonicalize:
8890 case Intrinsic::sqrt:
8891 case Intrinsic::experimental_constrained_sqrt:
8892 case Intrinsic::fma:
8893 case Intrinsic::experimental_constrained_fma:
8894 case Intrinsic::fmuladd:
8895 case Intrinsic::experimental_constrained_fmuladd:
8896 case Intrinsic::exp:
8897 case Intrinsic::experimental_constrained_exp:
8898 case Intrinsic::exp2:
8899 case Intrinsic::experimental_constrained_exp2:
8900 case Intrinsic::exp10:
8901 case Intrinsic::log:
8902 case Intrinsic::experimental_constrained_log:
8903 case Intrinsic::log2:
8904 case Intrinsic::experimental_constrained_log2:
8905 case Intrinsic::log10:
8906 case Intrinsic::experimental_constrained_log10:
8907 case Intrinsic::modf:
8908 case Intrinsic::floor:
8909 case Intrinsic::experimental_constrained_floor:
8910 case Intrinsic::ceil:
8911 case Intrinsic::experimental_constrained_ceil:
8912 case Intrinsic::trunc:
8913 case Intrinsic::experimental_constrained_trunc:
8914 case Intrinsic::rint:
8915 case Intrinsic::experimental_constrained_rint:
8916 case Intrinsic::nearbyint:
8917 case Intrinsic::experimental_constrained_nearbyint:
8918 case Intrinsic::round:
8919 case Intrinsic::experimental_constrained_round:
8920 case Intrinsic::roundeven:
8921 case Intrinsic::experimental_constrained_roundeven:
8922 case Intrinsic::lrint:
8923 case Intrinsic::experimental_constrained_lrint:
8924 case Intrinsic::llrint:
8925 case Intrinsic::experimental_constrained_llrint:
8926 case Intrinsic::lround:
8927 case Intrinsic::experimental_constrained_lround:
8928 case Intrinsic::llround:
8929 case Intrinsic::experimental_constrained_llround:
8930 case Intrinsic::fshl:
8931 case Intrinsic::fshr:
8932 case Intrinsic::frexp:
8933 case Intrinsic::ldexp:
8934 case Intrinsic::experimental_constrained_ldexp:
8935 case Intrinsic::get_active_lane_mask:
8936 case Intrinsic::mask_beforefirst:
8937 return true;
8938 default:
8939 return false;
8940 }
8941}
8942
8943bool llvm::propagatesPoison(const Use &PoisonOp) {
8944 const Operator *I = cast<Operator>(PoisonOp.getUser());
8945 switch (I->getOpcode()) {
8946 case Instruction::Freeze:
8947 case Instruction::PHI:
8948 case Instruction::Invoke:
8949 return false;
8950 case Instruction::Select:
8951 return PoisonOp.getOperandNo() == 0;
8952 case Instruction::Call:
8953 if (auto *II = dyn_cast<IntrinsicInst>(I))
8954 return intrinsicPropagatesPoison(II->getIntrinsicID());
8955 return false;
8956 case Instruction::ICmp:
8957 case Instruction::FCmp:
8958 case Instruction::GetElementPtr:
8959 return true;
8960 default:
8962 return true;
8963
8964 // Be conservative and return false.
8965 return false;
8966 }
8967}
8968
8969/// Enumerates all operands of \p I that are guaranteed to not be undef or
8970/// poison. If the callback \p Handle returns true, stop processing and return
8971/// true. Otherwise, return false.
8972template <typename CallableT>
8974 const CallableT &Handle) {
8975 switch (I->getOpcode()) {
8976 case Instruction::Store:
8977 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8978 return true;
8979 break;
8980
8981 case Instruction::Load:
8982 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8983 return true;
8984 break;
8985
8986 // Since dereferenceable attribute imply noundef, atomic operations
8987 // also implicitly have noundef pointers too
8988 case Instruction::AtomicCmpXchg:
8990 return true;
8991 break;
8992
8993 case Instruction::AtomicRMW:
8994 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8995 return true;
8996 break;
8997
8998 case Instruction::Call:
8999 case Instruction::Invoke: {
9000 const CallBase *CB = cast<CallBase>(I);
9001 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
9002 return true;
9003 for (unsigned i = 0; i < CB->arg_size(); ++i)
9004 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
9005 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
9006 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
9007 Handle(CB->getArgOperand(i)))
9008 return true;
9009 break;
9010 }
9011 case Instruction::Ret:
9012 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
9013 Handle(I->getOperand(0)))
9014 return true;
9015 break;
9016 case Instruction::Switch:
9017 if (Handle(cast<SwitchInst>(I)->getCondition()))
9018 return true;
9019 break;
9020 case Instruction::CondBr:
9021 if (Handle(cast<CondBrInst>(I)->getCondition()))
9022 return true;
9023 break;
9024 default:
9025 break;
9026 }
9027
9028 return false;
9029}
9030
9031/// Enumerates all operands of \p I that are guaranteed to not be poison.
9032template <typename CallableT>
9034 const CallableT &Handle) {
9035 if (handleGuaranteedWellDefinedOps(I, Handle))
9036 return true;
9037 switch (I->getOpcode()) {
9038 // Divisors of these operations are allowed to be partially undef.
9039 case Instruction::UDiv:
9040 case Instruction::SDiv:
9041 case Instruction::URem:
9042 case Instruction::SRem:
9043 return Handle(I->getOperand(1));
9044 default:
9045 return false;
9046 }
9047}
9048
9050 const SmallPtrSetImpl<const Value *> &KnownPoison) {
9052 I, [&](const Value *V) { return KnownPoison.count(V); });
9053}
9054
9056 bool PoisonOnly) {
9057 // We currently only look for uses of values within the same basic
9058 // block, as that makes it easier to guarantee that the uses will be
9059 // executed given that Inst is executed.
9060 //
9061 // FIXME: Expand this to consider uses beyond the same basic block. To do
9062 // this, look out for the distinction between post-dominance and strong
9063 // post-dominance.
9064 const BasicBlock *BB = nullptr;
9066 if (const auto *Inst = dyn_cast<Instruction>(V)) {
9067 BB = Inst->getParent();
9068 Begin = Inst->getIterator();
9069 Begin++;
9070 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
9071 if (Arg->getParent()->isDeclaration())
9072 return false;
9073 BB = &Arg->getParent()->getEntryBlock();
9074 Begin = BB->begin();
9075 } else {
9076 return false;
9077 }
9078
9079 // Limit number of instructions we look at, to avoid scanning through large
9080 // blocks. The current limit is chosen arbitrarily.
9081 unsigned ScanLimit = 32;
9083
9084 if (!PoisonOnly) {
9085 // Since undef does not propagate eagerly, be conservative & just check
9086 // whether a value is directly passed to an instruction that must take
9087 // well-defined operands.
9088
9089 for (const auto &I : make_range(Begin, End)) {
9090 if (--ScanLimit == 0)
9091 break;
9092
9093 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
9094 return WellDefinedOp == V;
9095 }))
9096 return true;
9097
9099 break;
9100 }
9101 return false;
9102 }
9103
9104 // Set of instructions that we have proved will yield poison if Inst
9105 // does.
9106 SmallPtrSet<const Value *, 16> YieldsPoison;
9108
9109 YieldsPoison.insert(V);
9110 Visited.insert(BB);
9111
9112 while (true) {
9113 for (const auto &I : make_range(Begin, End)) {
9114 if (--ScanLimit == 0)
9115 return false;
9116 if (mustTriggerUB(&I, YieldsPoison))
9117 return true;
9119 return false;
9120
9121 // If an operand is poison and propagates it, mark I as yielding poison.
9122 for (const Use &Op : I.operands()) {
9123 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
9124 YieldsPoison.insert(&I);
9125 break;
9126 }
9127 }
9128
9129 // Special handling for select, which returns poison if its operand 0 is
9130 // poison (handled in the loop above) *or* if both its true/false operands
9131 // are poison (handled here).
9132 if (I.getOpcode() == Instruction::Select &&
9133 YieldsPoison.count(I.getOperand(1)) &&
9134 YieldsPoison.count(I.getOperand(2))) {
9135 YieldsPoison.insert(&I);
9136 }
9137 }
9138
9139 BB = BB->getSingleSuccessor();
9140 if (!BB || !Visited.insert(BB).second)
9141 break;
9142
9143 Begin = BB->getFirstNonPHIIt();
9144 End = BB->end();
9145 }
9146 return false;
9147}
9148
9150 return ::programUndefinedIfUndefOrPoison(Inst, false);
9151}
9152
9154 return ::programUndefinedIfUndefOrPoison(Inst, true);
9155}
9156
9157static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
9158 if (FMF.noNaNs())
9159 return true;
9160
9161 if (auto *C = dyn_cast<ConstantFP>(V))
9162 return !C->isNaN();
9163
9164 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
9165 if (!C->getElementType()->isFloatingPointTy())
9166 return false;
9167 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
9168 if (C->getElementAsAPFloat(I).isNaN())
9169 return false;
9170 }
9171 return true;
9172 }
9173
9175 return true;
9176
9177 return false;
9178}
9179
9180static bool isKnownNonZero(const Value *V) {
9181 if (auto *C = dyn_cast<ConstantFP>(V))
9182 return !C->isZero();
9183
9184 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
9185 if (!C->getElementType()->isFloatingPointTy())
9186 return false;
9187 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
9188 if (C->getElementAsAPFloat(I).isZero())
9189 return false;
9190 }
9191 return true;
9192 }
9193
9194 return false;
9195}
9196
9197/// Match clamp pattern for float types without care about NaNs or signed zeros.
9198/// Given non-min/max outer cmp/select from the clamp pattern this
9199/// function recognizes if it can be substitued by a "canonical" min/max
9200/// pattern.
9202 Value *CmpLHS, Value *CmpRHS,
9203 Value *TrueVal, Value *FalseVal,
9204 Value *&LHS, Value *&RHS) {
9205 // Try to match
9206 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
9207 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
9208 // and return description of the outer Max/Min.
9209
9210 // First, check if select has inverse order:
9211 if (CmpRHS == FalseVal) {
9212 std::swap(TrueVal, FalseVal);
9214 }
9215
9216 // Assume success now. If there's no match, callers should not use these anyway.
9217 LHS = TrueVal;
9218 RHS = FalseVal;
9219
9220 const APFloat *FC1;
9221 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
9222 return {SPF_UNKNOWN, SPNB_NA, false};
9223
9224 const APFloat *FC2;
9225 switch (Pred) {
9226 case CmpInst::FCMP_OLT:
9227 case CmpInst::FCMP_OLE:
9228 case CmpInst::FCMP_ULT:
9229 case CmpInst::FCMP_ULE:
9230 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
9231 *FC1 < *FC2)
9232 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
9233 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
9234 *FC1 < *FC2)
9235 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
9236 break;
9237 case CmpInst::FCMP_OGT:
9238 case CmpInst::FCMP_OGE:
9239 case CmpInst::FCMP_UGT:
9240 case CmpInst::FCMP_UGE:
9241 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
9242 *FC1 > *FC2)
9243 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
9244 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
9245 *FC1 > *FC2)
9246 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
9247 break;
9248 default:
9249 break;
9250 }
9251
9252 return {SPF_UNKNOWN, SPNB_NA, false};
9253}
9254
9255/// Recognize variations of:
9256/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
9258 Value *CmpLHS, Value *CmpRHS,
9259 Value *TrueVal, Value *FalseVal) {
9260 // Swap the select operands and predicate to match the patterns below.
9261 if (CmpRHS != TrueVal) {
9263 std::swap(TrueVal, FalseVal);
9264 }
9265 const APInt *C1;
9266 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
9267 const APInt *C2;
9268 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
9269 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
9270 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
9271 return {SPF_SMAX, SPNB_NA, false};
9272
9273 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
9274 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9275 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
9276 return {SPF_SMIN, SPNB_NA, false};
9277
9278 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
9279 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
9280 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
9281 return {SPF_UMAX, SPNB_NA, false};
9282
9283 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
9284 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9285 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
9286 return {SPF_UMIN, SPNB_NA, false};
9287 }
9288 return {SPF_UNKNOWN, SPNB_NA, false};
9289}
9290
9291/// If the input value is the result of a 'not' op, constant integer, or vector
9292/// splat of a constant integer, return the bitwise-not source value.
9293/// TODO: This could be extended to handle non-splat vector integer constants.
9295 Value *NotV;
9296 if (match(V, m_Not(m_Value(NotV))))
9297 return NotV;
9298
9299 const APInt *C;
9300 if (match(V, m_APInt(C)))
9301 return ConstantInt::get(V->getType(), ~(*C));
9302
9303 return nullptr;
9304}
9305
9306/// Match non-obvious integer minimum and maximum sequences.
9308 Value *CmpRHS, Value *TrueVal,
9309 Value *FalseVal, Value *&LHS,
9310 Value *&RHS) {
9311 // Assume success. If there's no match, callers should not use these anyway.
9312 LHS = TrueVal;
9313 RHS = FalseVal;
9314
9315 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9317 return SPR;
9318
9319 // Look through 'not' ops to find disguised min/max.
9320 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9321 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9322 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9323 switch (Pred) {
9324 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9325 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9326 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9327 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9328 default: break;
9329 }
9330 }
9331
9332 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9333 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9334 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9335 switch (Pred) {
9336 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9337 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9338 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9339 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9340 default: break;
9341 }
9342 }
9343
9345 return {SPF_UNKNOWN, SPNB_NA, false};
9346
9347 const APInt *C1;
9348 if (!match(CmpRHS, m_APInt(C1)))
9349 return {SPF_UNKNOWN, SPNB_NA, false};
9350
9351 // An unsigned min/max can be written with a signed compare.
9352 const APInt *C2;
9353 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9354 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9355 // Is the sign bit set?
9356 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9357 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9358 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9359 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9360
9361 // Is the sign bit clear?
9362 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9363 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9364 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9365 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9366 }
9367
9368 return {SPF_UNKNOWN, SPNB_NA, false};
9369}
9370
9371bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9372 bool AllowPoison) {
9373 assert(X && Y && "Invalid operand");
9374
9375 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9376 if (!match(X, m_Neg(m_Specific(Y))))
9377 return false;
9378
9379 auto *BO = cast<BinaryOperator>(X);
9380 if (NeedNSW && !BO->hasNoSignedWrap())
9381 return false;
9382
9383 auto *Zero = cast<Constant>(BO->getOperand(0));
9384 if (!AllowPoison && !Zero->isNullValue())
9385 return false;
9386
9387 return true;
9388 };
9389
9390 // X = -Y or Y = -X
9391 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9392 return true;
9393
9394 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9395 Value *A, *B;
9396 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9397 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9398 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9400}
9401
9402bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9403 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9404 Value *A, *B, *C;
9405 CmpPredicate Pred1, Pred2;
9406 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9407 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9408 return false;
9409
9410 // They must both have samesign flag or not.
9411 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9412 return false;
9413
9414 if (B == C)
9415 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9416
9417 // Try to infer the relationship from constant ranges.
9418 const APInt *RHSC1, *RHSC2;
9419 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9420 return false;
9421
9422 // Sign bits of two RHSCs should match.
9423 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9424 return false;
9425
9426 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9427 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9428
9429 return CR1.inverse() == CR2;
9430}
9431
9433 SelectPatternNaNBehavior NaNBehavior,
9434 bool Ordered) {
9435 switch (Pred) {
9436 default:
9437 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9438 case ICmpInst::ICMP_UGT:
9439 case ICmpInst::ICMP_UGE:
9440 return {SPF_UMAX, SPNB_NA, false};
9441 case ICmpInst::ICMP_SGT:
9442 case ICmpInst::ICMP_SGE:
9443 return {SPF_SMAX, SPNB_NA, false};
9444 case ICmpInst::ICMP_ULT:
9445 case ICmpInst::ICMP_ULE:
9446 return {SPF_UMIN, SPNB_NA, false};
9447 case ICmpInst::ICMP_SLT:
9448 case ICmpInst::ICMP_SLE:
9449 return {SPF_SMIN, SPNB_NA, false};
9450 case FCmpInst::FCMP_UGT:
9451 case FCmpInst::FCMP_UGE:
9452 case FCmpInst::FCMP_OGT:
9453 case FCmpInst::FCMP_OGE:
9454 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9455 case FCmpInst::FCMP_ULT:
9456 case FCmpInst::FCMP_ULE:
9457 case FCmpInst::FCMP_OLT:
9458 case FCmpInst::FCMP_OLE:
9459 return {SPF_FMINNUM, NaNBehavior, Ordered};
9460 }
9461}
9462
9463std::optional<std::pair<CmpPredicate, Constant *>>
9466 "Only for relational integer predicates.");
9467 if (isa<UndefValue>(C))
9468 return std::nullopt;
9469
9470 Type *Type = C->getType();
9471 bool IsSigned = ICmpInst::isSigned(Pred);
9472
9474 bool WillIncrement =
9475 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9476
9477 // Check if the constant operand can be safely incremented/decremented
9478 // without overflowing/underflowing.
9479 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9480 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9481 return false;
9482
9483 if (!Pred.hasSameSign())
9484 return true;
9485
9486 // Crossing the corresponding boundary in the other ordering changes the
9487 // sign bit, and therefore changes the poison domain.
9488 return WillIncrement ? !C->isMaxValue(!IsSigned)
9489 : !C->isMinValue(!IsSigned);
9490 };
9491
9492 Constant *SafeReplacementConstant = nullptr;
9493 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9494 // Bail out if the constant can't be safely incremented/decremented.
9495 if (!ConstantIsOk(CI))
9496 return std::nullopt;
9497 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9498 unsigned NumElts = FVTy->getNumElements();
9499 for (unsigned i = 0; i != NumElts; ++i) {
9500 Constant *Elt = C->getAggregateElement(i);
9501 if (!Elt)
9502 return std::nullopt;
9503
9504 if (isa<UndefValue>(Elt))
9505 continue;
9506
9507 // Bail out if we can't determine if this constant is min/max or if we
9508 // know that this constant is min/max.
9509 auto *CI = dyn_cast<ConstantInt>(Elt);
9510 if (!CI || !ConstantIsOk(CI))
9511 return std::nullopt;
9512
9513 if (!SafeReplacementConstant)
9514 SafeReplacementConstant = CI;
9515 }
9516 } else if (isa<VectorType>(C->getType())) {
9517 // Handle scalable splat
9518 Value *SplatC = C->getSplatValue();
9519 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9520 // Bail out if the constant can't be safely incremented/decremented.
9521 if (!CI || !ConstantIsOk(CI))
9522 return std::nullopt;
9523 } else {
9524 // ConstantExpr?
9525 return std::nullopt;
9526 }
9527
9528 // It may not be safe to change a compare predicate in the presence of
9529 // undefined elements, so replace those elements with the first safe constant
9530 // that we found.
9531 // TODO: in case of poison, it is safe; let's replace undefs only.
9532 if (C->containsUndefOrPoisonElement()) {
9533 assert(SafeReplacementConstant && "Replacement constant not set");
9534 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9535 }
9536
9538 Pred.hasSameSign());
9539
9540 // Increment or decrement the constant.
9541 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9542 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9543
9544 return std::make_pair(NewPred, NewC);
9545}
9546
9548 FastMathFlags FMF, Value *CmpLHS,
9549 Value *CmpRHS, Value *TrueVal,
9550 Value *FalseVal, Value *&LHS,
9551 Value *&RHS) {
9553 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9554 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9555 // purpose of identifying min/max. Disregard vector constants with undefined
9556 // elements because those can not be back-propagated for analysis.
9557 Value *OutputZeroVal = nullptr;
9558 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9559 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9560 OutputZeroVal = TrueVal;
9561 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9562 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9563 OutputZeroVal = FalseVal;
9564
9565 if (OutputZeroVal) {
9566 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9567 CmpLHS = OutputZeroVal;
9568 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9569 CmpRHS = OutputZeroVal;
9570 }
9571 }
9572
9573 LHS = CmpLHS;
9574 RHS = CmpRHS;
9575
9576 // Signed zero may return inconsistent results between implementations.
9577 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9578 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9579 // Therefore, we behave conservatively and only proceed if at least one of the
9580 // operands is known to not be zero or if we don't care about signed zero.
9582 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9583 !isKnownNonZero(CmpRHS))
9584 return {SPF_UNKNOWN, SPNB_NA, false};
9585 }
9586
9587 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9588 bool Ordered = false;
9589
9590 // When given one NaN and one non-NaN input:
9591 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9592 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9593 // ordered comparison fails), which could be NaN or non-NaN.
9594 // so here we discover exactly what NaN behavior is required/accepted.
9596 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9597 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9598
9599 if (LHSSafe && RHSSafe) {
9600 // Both operands are known non-NaN.
9601 NaNBehavior = SPNB_RETURNS_ANY;
9602 Ordered = CmpInst::isOrdered(Pred);
9603 } else if (CmpInst::isOrdered(Pred)) {
9604 // An ordered comparison will return false when given a NaN, so it
9605 // returns the RHS.
9606 Ordered = true;
9607 if (LHSSafe)
9608 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9609 NaNBehavior = SPNB_RETURNS_NAN;
9610 else if (RHSSafe)
9611 NaNBehavior = SPNB_RETURNS_OTHER;
9612 else
9613 // Completely unsafe.
9614 return {SPF_UNKNOWN, SPNB_NA, false};
9615 } else {
9616 Ordered = false;
9617 // An unordered comparison will return true when given a NaN, so it
9618 // returns the LHS.
9619 if (LHSSafe)
9620 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9621 NaNBehavior = SPNB_RETURNS_OTHER;
9622 else if (RHSSafe)
9623 NaNBehavior = SPNB_RETURNS_NAN;
9624 else
9625 // Completely unsafe.
9626 return {SPF_UNKNOWN, SPNB_NA, false};
9627 }
9628 }
9629
9630 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9631 std::swap(CmpLHS, CmpRHS);
9633 if (NaNBehavior == SPNB_RETURNS_NAN)
9634 NaNBehavior = SPNB_RETURNS_OTHER;
9635 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9636 NaNBehavior = SPNB_RETURNS_NAN;
9637 Ordered = !Ordered;
9638 }
9639
9640 // ([if]cmp X, Y) ? X : Y
9641 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9642 return getSelectPattern(Pred, NaNBehavior, Ordered);
9643
9644 if (isKnownNegation(TrueVal, FalseVal)) {
9645 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9646 // match against either LHS or sign-preserving operations on LHS, like
9647 // sext(LHS), or binary ops that do not wrap in signed sense.
9648 auto CmpLHSOrSExt =
9649 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9650 auto MaybeSExtOrMulCmpLHS =
9651 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9652 m_NSWShl(CmpLHSOrSExt, m_Value()));
9653 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9654 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9655 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9656 // Set the return values. If the compare uses the negated value (-X >s 0),
9657 // swap the return values because the negated value is always 'RHS'.
9658 LHS = TrueVal;
9659 RHS = FalseVal;
9660 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9661 std::swap(LHS, RHS);
9662
9663 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9664 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9665 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9666 return {SPF_ABS, SPNB_NA, false};
9667
9668 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9669 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9670 return {SPF_ABS, SPNB_NA, false};
9671
9672 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9673 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9674 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9675 return {SPF_NABS, SPNB_NA, false};
9676 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9677 // Set the return values. If the compare uses the negated value (-X >s 0),
9678 // swap the return values because the negated value is always 'RHS'.
9679 LHS = FalseVal;
9680 RHS = TrueVal;
9681 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9682 std::swap(LHS, RHS);
9683
9684 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9685 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9686 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9687 return {SPF_NABS, SPNB_NA, false};
9688
9689 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9690 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9691 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9692 return {SPF_ABS, SPNB_NA, false};
9693 }
9694 }
9695
9697 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9698
9699 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9700 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9701 // semantics than minNum. Be conservative in such case.
9702 if (NaNBehavior != SPNB_RETURNS_ANY ||
9703 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9704 !isKnownNonZero(CmpRHS)))
9705 return {SPF_UNKNOWN, SPNB_NA, false};
9706
9707 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9708}
9709
9711 Instruction::CastOps *CastOp) {
9712 const DataLayout &DL = CmpI->getDataLayout();
9713
9714 Constant *CastedTo = nullptr;
9715 switch (*CastOp) {
9716 case Instruction::ZExt:
9717 if (CmpI->isUnsigned())
9718 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9719 break;
9720 case Instruction::SExt:
9721 if (CmpI->isSigned())
9722 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9723 break;
9724 case Instruction::Trunc:
9725 Constant *CmpConst;
9726 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9727 CmpConst->getType() == SrcTy) {
9728 // Here we have the following case:
9729 //
9730 // %cond = cmp iN %x, CmpConst
9731 // %tr = trunc iN %x to iK
9732 // %narrowsel = select i1 %cond, iK %t, iK C
9733 //
9734 // We can always move trunc after select operation:
9735 //
9736 // %cond = cmp iN %x, CmpConst
9737 // %widesel = select i1 %cond, iN %x, iN CmpConst
9738 // %tr = trunc iN %widesel to iK
9739 //
9740 // Note that C could be extended in any way because we don't care about
9741 // upper bits after truncation. It can't be abs pattern, because it would
9742 // look like:
9743 //
9744 // select i1 %cond, x, -x.
9745 //
9746 // So only min/max pattern could be matched. Such match requires widened C
9747 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9748 // CmpConst == C is checked below.
9749 CastedTo = CmpConst;
9750 } else {
9751 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9752 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9753 }
9754 break;
9755 case Instruction::FPTrunc:
9756 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9757 break;
9758 case Instruction::FPExt:
9759 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9760 break;
9761 case Instruction::FPToUI:
9762 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9763 break;
9764 case Instruction::FPToSI:
9765 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9766 break;
9767 case Instruction::UIToFP:
9768 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9769 break;
9770 case Instruction::SIToFP:
9771 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9772 break;
9773 default:
9774 break;
9775 }
9776
9777 if (!CastedTo)
9778 return nullptr;
9779
9780 // Make sure the cast doesn't lose any information.
9781 Constant *CastedBack =
9782 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9783 if (CastedBack && CastedBack != C)
9784 return nullptr;
9785
9786 return CastedTo;
9787}
9788
9789/// Helps to match a select pattern in case of a type mismatch.
9790///
9791/// The function processes the case when type of true and false values of a
9792/// select instruction differs from type of the cmp instruction operands because
9793/// of a cast instruction. The function checks if it is legal to move the cast
9794/// operation after "select". If yes, it returns the new second value of
9795/// "select" (with the assumption that cast is moved):
9796/// 1. As operand of cast instruction when both values of "select" are same cast
9797/// instructions.
9798/// 2. As restored constant (by applying reverse cast operation) when the first
9799/// value of the "select" is a cast operation and the second value is a
9800/// constant. It is implemented in lookThroughCastConst().
9801/// 3. As one operand is cast instruction and the other is not. The operands in
9802/// sel(cmp) are in different type integer.
9803/// NOTE: We return only the new second value because the first value could be
9804/// accessed as operand of cast instruction.
9806 Instruction::CastOps *CastOp) {
9807 auto *Cast1 = dyn_cast<CastInst>(V1);
9808 if (!Cast1)
9809 return nullptr;
9810
9811 *CastOp = Cast1->getOpcode();
9812 Type *SrcTy = Cast1->getSrcTy();
9813 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9814 // If V1 and V2 are both the same cast from the same type, look through V1.
9815 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9816 return Cast2->getOperand(0);
9817 return nullptr;
9818 }
9819
9820 auto *C = dyn_cast<Constant>(V2);
9821 if (C)
9822 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9823
9824 Value *CastedTo = nullptr;
9825 if (*CastOp == Instruction::Trunc) {
9826 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9827 // Here we have the following case:
9828 // %y_ext = sext iK %y to iN
9829 // %cond = cmp iN %x, %y_ext
9830 // %tr = trunc iN %x to iK
9831 // %narrowsel = select i1 %cond, iK %tr, iK %y
9832 //
9833 // We can always move trunc after select operation:
9834 // %y_ext = sext iK %y to iN
9835 // %cond = cmp iN %x, %y_ext
9836 // %widesel = select i1 %cond, iN %x, iN %y_ext
9837 // %tr = trunc iN %widesel to iK
9838 assert(V2->getType() == Cast1->getType() &&
9839 "V2 and Cast1 should be the same type.");
9840 CastedTo = CmpI->getOperand(1);
9841 }
9842 }
9843
9844 return CastedTo;
9845}
9847 Instruction::CastOps *CastOp) {
9849 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9850
9851 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9852 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9853
9854 Value *TrueVal = SI->getTrueValue();
9855 Value *FalseVal = SI->getFalseValue();
9856
9858 CmpI, TrueVal, FalseVal, LHS, RHS, SI->getFastMathFlagsOrNone(), CastOp);
9859}
9860
9862 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9863 FastMathFlags FMF, Instruction::CastOps *CastOp) {
9864 CmpInst::Predicate Pred = CmpI->getPredicate();
9865 Value *CmpLHS = CmpI->getOperand(0);
9866 Value *CmpRHS = CmpI->getOperand(1);
9867 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9868 FMF.setNoNaNs();
9869
9870 // Bail out early.
9871 if (CmpI->isEquality())
9872 return {SPF_UNKNOWN, SPNB_NA, false};
9873
9874 // Deal with type mismatches.
9875 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9876 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9877 // If this is a potential fmin/fmax with a cast to integer, then ignore
9878 // -0.0 because there is no corresponding integer value.
9879 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9880 FMF.setNoSignedZeros();
9881 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9882 cast<CastInst>(TrueVal)->getOperand(0), C,
9883 LHS, RHS);
9884 }
9885 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9886 // If this is a potential fmin/fmax with a cast to integer, then ignore
9887 // -0.0 because there is no corresponding integer value.
9888 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9889 FMF.setNoSignedZeros();
9890 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, C,
9891 cast<CastInst>(FalseVal)->getOperand(0), LHS,
9892 RHS);
9893 }
9894 }
9895 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS,
9896 RHS);
9897}
9898
9900 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9901 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9902 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9903 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9904 if (SPF == SPF_FMINNUM)
9905 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9906 if (SPF == SPF_FMAXNUM)
9907 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9908 llvm_unreachable("unhandled!");
9909}
9910
9912 switch (SPF) {
9914 return Intrinsic::umin;
9916 return Intrinsic::umax;
9918 return Intrinsic::smin;
9920 return Intrinsic::smax;
9921 default:
9922 llvm_unreachable("Unexpected SPF");
9923 }
9924}
9925
9927 if (SPF == SPF_SMIN) return SPF_SMAX;
9928 if (SPF == SPF_UMIN) return SPF_UMAX;
9929 if (SPF == SPF_SMAX) return SPF_SMIN;
9930 if (SPF == SPF_UMAX) return SPF_UMIN;
9931 llvm_unreachable("unhandled!");
9932}
9933
9935 switch (MinMaxID) {
9936 case Intrinsic::smax: return Intrinsic::smin;
9937 case Intrinsic::smin: return Intrinsic::smax;
9938 case Intrinsic::umax: return Intrinsic::umin;
9939 case Intrinsic::umin: return Intrinsic::umax;
9940 // Please note that next four intrinsics may produce the same result for
9941 // original and inverted case even if X != Y due to NaN is handled specially.
9942 case Intrinsic::maximum: return Intrinsic::minimum;
9943 case Intrinsic::minimum: return Intrinsic::maximum;
9944 case Intrinsic::maxnum: return Intrinsic::minnum;
9945 case Intrinsic::minnum: return Intrinsic::maxnum;
9946 case Intrinsic::maximumnum:
9947 return Intrinsic::minimumnum;
9948 case Intrinsic::minimumnum:
9949 return Intrinsic::maximumnum;
9950 default: llvm_unreachable("Unexpected intrinsic");
9951 }
9952}
9953
9955 switch (SPF) {
9958 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9959 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9960 default: llvm_unreachable("Unexpected flavor");
9961 }
9962}
9963
9964std::pair<Intrinsic::ID, bool>
9966 // Check if VL contains select instructions that can be folded into a min/max
9967 // vector intrinsic and return the intrinsic if it is possible.
9968 // TODO: Support floating point min/max.
9969 bool AllCmpSingleUse = true;
9970 SelectPatternResult SelectPattern;
9971 SelectPattern.Flavor = SPF_UNKNOWN;
9972 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9973 Value *LHS, *RHS;
9974 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9975 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9976 return false;
9977 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9978 SelectPattern.Flavor != CurrentPattern.Flavor)
9979 return false;
9980 SelectPattern = CurrentPattern;
9981 AllCmpSingleUse &=
9983 return true;
9984 })) {
9985 switch (SelectPattern.Flavor) {
9986 case SPF_SMIN:
9987 return {Intrinsic::smin, AllCmpSingleUse};
9988 case SPF_UMIN:
9989 return {Intrinsic::umin, AllCmpSingleUse};
9990 case SPF_SMAX:
9991 return {Intrinsic::smax, AllCmpSingleUse};
9992 case SPF_UMAX:
9993 return {Intrinsic::umax, AllCmpSingleUse};
9994 case SPF_FMAXNUM:
9995 return {Intrinsic::maxnum, AllCmpSingleUse};
9996 case SPF_FMINNUM:
9997 return {Intrinsic::minnum, AllCmpSingleUse};
9998 default:
9999 llvm_unreachable("unexpected select pattern flavor");
10000 }
10001 }
10002 return {Intrinsic::not_intrinsic, false};
10003}
10004
10005template <typename InstTy>
10006static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
10007 Value *&Init, Value *&OtherOp) {
10008 // Handle the case of a simple two-predecessor recurrence PHI.
10009 // There's a lot more that could theoretically be done here, but
10010 // this is sufficient to catch some interesting cases.
10011 // TODO: Expand list -- gep, uadd.sat etc.
10012 if (PN->getNumIncomingValues() != 2)
10013 return false;
10014
10015 for (unsigned I = 0; I != 2; ++I) {
10016 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
10017 Operation && Operation->getNumOperands() >= 2) {
10018 Value *LHS = Operation->getOperand(0);
10019 Value *RHS = Operation->getOperand(1);
10020 if (LHS != PN && RHS != PN)
10021 continue;
10022
10023 Inst = Operation;
10024 Init = PN->getIncomingValue(!I);
10025 OtherOp = (LHS == PN) ? RHS : LHS;
10026 return true;
10027 }
10028 }
10029 return false;
10030}
10031
10032template <typename InstTy>
10033static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
10034 Value *&Init, Value *&OtherOp0,
10035 Value *&OtherOp1) {
10036 if (PN->getNumIncomingValues() != 2)
10037 return false;
10038
10039 for (unsigned I = 0; I != 2; ++I) {
10040 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
10041 Operation && Operation->getNumOperands() >= 3) {
10042 Value *Op0 = Operation->getOperand(0);
10043 Value *Op1 = Operation->getOperand(1);
10044 Value *Op2 = Operation->getOperand(2);
10045
10046 if (Op0 != PN && Op1 != PN && Op2 != PN)
10047 continue;
10048
10049 Inst = Operation;
10050 Init = PN->getIncomingValue(!I);
10051 if (Op0 == PN) {
10052 OtherOp0 = Op1;
10053 OtherOp1 = Op2;
10054 } else if (Op1 == PN) {
10055 OtherOp0 = Op0;
10056 OtherOp1 = Op2;
10057 } else {
10058 OtherOp0 = Op0;
10059 OtherOp1 = Op1;
10060 }
10061 return true;
10062 }
10063 }
10064 return false;
10065}
10067 Value *&Start, Value *&Step) {
10068 // We try to match a recurrence of the form:
10069 // %iv = [Start, %entry], [%iv.next, %backedge]
10070 // %iv.next = binop %iv, Step
10071 // Or:
10072 // %iv = [Start, %entry], [%iv.next, %backedge]
10073 // %iv.next = binop Step, %iv
10074 return matchTwoInputRecurrence(P, BO, Start, Step);
10075}
10076
10078 Value *&Start, Value *&Step) {
10079 BinaryOperator *BO = nullptr;
10080 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
10081 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
10082}
10083
10085 PHINode *&P, Value *&Init,
10086 Value *&OtherOp) {
10087 // Binary intrinsics only supported for now.
10088 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
10089 I->getType() != I->getArgOperand(1)->getType())
10090 return false;
10091
10092 IntrinsicInst *II = nullptr;
10093 P = dyn_cast<PHINode>(I->getArgOperand(0));
10094 if (!P)
10095 P = dyn_cast<PHINode>(I->getArgOperand(1));
10096
10097 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
10098}
10099
10101 PHINode *&P, Value *&Init,
10102 Value *&OtherOp0,
10103 Value *&OtherOp1) {
10104 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
10105 I->getType() != I->getArgOperand(1)->getType() ||
10106 I->getType() != I->getArgOperand(2)->getType())
10107 return false;
10108 IntrinsicInst *II = nullptr;
10109 P = dyn_cast<PHINode>(I->getArgOperand(0));
10110 if (!P) {
10111 P = dyn_cast<PHINode>(I->getArgOperand(1));
10112 if (!P)
10113 P = dyn_cast<PHINode>(I->getArgOperand(2));
10114 }
10115 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
10116 II == I;
10117}
10118
10119/// Return true if "icmp Pred LHS RHS" is always true.
10121 const Value *RHS) {
10123 return true;
10124
10125 switch (Pred) {
10126 default:
10127 return false;
10128
10129 case CmpInst::ICMP_SLE: {
10130 const APInt *C;
10131
10132 // LHS s<= LHS +_{nsw} C if C >= 0
10133 // LHS s<= LHS | C if C >= 0
10134 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
10136 return !C->isNegative();
10137
10138 // LHS s<= smax(LHS, V) for any V
10140 return true;
10141
10142 // smin(RHS, V) s<= RHS for any V
10144 return true;
10145
10146 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
10147 const Value *X;
10148 const APInt *CLHS, *CRHS;
10149 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
10151 return CLHS->sle(*CRHS);
10152
10153 return false;
10154 }
10155
10156 case CmpInst::ICMP_ULE: {
10157 // LHS u<= LHS +_{nuw} V for any V
10158 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
10160 return true;
10161
10162 // LHS u<= LHS | V for any V
10163 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
10164 return true;
10165
10166 // LHS u<= umax(LHS, V) for any V
10168 return true;
10169
10170 // RHS >> V u<= RHS for any V
10171 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
10172 return true;
10173
10174 // RHS u/ C_ugt_1 u<= RHS
10175 const APInt *C;
10176 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
10177 return true;
10178
10179 // RHS & V u<= RHS for any V
10181 return true;
10182
10183 // umin(RHS, V) u<= RHS for any V
10185 return true;
10186
10187 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
10188 const Value *X;
10189 const APInt *CLHS, *CRHS;
10190 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
10192 return CLHS->ule(*CRHS);
10193
10194 return false;
10195 }
10196 }
10197}
10198
10199/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
10200/// ALHS ARHS" is true. Otherwise, return std::nullopt.
10201static std::optional<bool>
10203 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
10204 switch (Pred) {
10205 default:
10206 return std::nullopt;
10207
10208 case CmpInst::ICMP_SLT:
10209 case CmpInst::ICMP_SLE:
10210 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
10212 return true;
10213 return std::nullopt;
10214
10215 case CmpInst::ICMP_SGT:
10216 case CmpInst::ICMP_SGE:
10217 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
10219 return true;
10220 return std::nullopt;
10221
10222 case CmpInst::ICMP_ULT:
10223 case CmpInst::ICMP_ULE:
10224 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
10226 return true;
10227 return std::nullopt;
10228
10229 case CmpInst::ICMP_UGT:
10230 case CmpInst::ICMP_UGE:
10231 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
10233 return true;
10234 return std::nullopt;
10235 }
10236}
10237
10238/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
10239/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
10240/// Otherwise, return std::nullopt if we can't infer anything.
10241static std::optional<bool>
10243 CmpPredicate RPred, const ConstantRange &RCR) {
10244 auto CRImpliesPred = [&](ConstantRange CR,
10245 CmpInst::Predicate Pred) -> std::optional<bool> {
10246 // If all true values for lhs and true for rhs, lhs implies rhs
10247 if (CR.icmp(Pred, RCR))
10248 return true;
10249
10250 // If there is no overlap, lhs implies not rhs
10252 return false;
10253
10254 return std::nullopt;
10255 };
10256 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10257 RPred))
10258 return Res;
10259 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
10261 : LPred.dropSameSign();
10263 : RPred.dropSameSign();
10264 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10265 RPred);
10266 }
10267 return std::nullopt;
10268}
10269
10270/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10271/// is true. Return false if LHS implies RHS is false. Otherwise, return
10272/// std::nullopt if we can't infer anything.
10273static std::optional<bool>
10274isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
10275 CmpPredicate RPred, const Value *R0, const Value *R1,
10276 const DataLayout &DL, bool LHSIsTrue) {
10277 // The rest of the logic assumes the LHS condition is true. If that's not the
10278 // case, invert the predicate to make it so.
10279 if (!LHSIsTrue)
10280 LPred = ICmpInst::getInverseCmpPredicate(LPred);
10281
10282 // We can have non-canonical operands, so try to normalize any common operand
10283 // to L0/R0.
10284 if (L0 == R1) {
10285 std::swap(R0, R1);
10286 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10287 }
10288 if (R0 == L1) {
10289 std::swap(L0, L1);
10290 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10291 }
10292 if (L1 == R1) {
10293 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10294 if (L0 != R0 || match(L0, m_ImmConstant())) {
10295 std::swap(L0, L1);
10296 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10297 std::swap(R0, R1);
10298 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10299 }
10300 }
10301
10302 // See if we can infer anything if operand-0 matches and we have at least one
10303 // constant.
10304 const APInt *Unused;
10305 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10306 // Potential TODO: We could also further use the constant range of L0/R0 to
10307 // further constraint the constant ranges. At the moment this leads to
10308 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10309 // C1` (see discussion: D58633).
10310 SimplifyQuery SQ(DL);
10315
10316 // Even if L1/R1 are not both constant, we can still sometimes deduce
10317 // relationship from a single constant. For example X u> Y implies X != 0.
10318 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10319 return R;
10320 // If both L1/R1 were exact constant ranges and we didn't get anything
10321 // here, we won't be able to deduce this.
10322 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10323 return std::nullopt;
10324 }
10325
10326 // Can we infer anything when the two compares have matching operands?
10327 if (L0 == R0 && L1 == R1)
10328 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10329
10330 // It only really makes sense in the context of signed comparison for "X - Y
10331 // must be positive if X >= Y and no overflow".
10332 // Take SGT as an example: L0:x > L1:y and C >= 0
10333 // ==> R0:(x -nsw y) < R1:(-C) is false
10334 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10335 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10336 SignedLPred == ICmpInst::ICMP_SGE) &&
10337 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10338 if (match(R1, m_NonPositive()) &&
10339 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10340 return false;
10341 }
10342
10343 // Take SLT as an example: L0:x < L1:y and C <= 0
10344 // ==> R0:(x -nsw y) < R1:(-C) is true
10345 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10346 SignedLPred == ICmpInst::ICMP_SLE) &&
10347 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10348 if (match(R1, m_NonNegative()) &&
10349 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10350 return true;
10351 }
10352
10353 // (a - b) pred C -> a != b, if 0 pred C is false
10354 // (ptrtoint(a) - ptrtoint(b)) pred C -> a != b, if 0 pred C is false
10355 Value *A, *B;
10356 if (ICmpInst::isEquality(RPred) && cmpExcludesZero(LPred, L1) &&
10357 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10358 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10363 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10364 }
10365
10366 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10367 if (L0 == R0 &&
10368 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10369 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10370 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10371 return CmpPredicate::getMatching(LPred, RPred).has_value();
10372
10373 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10374 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10375
10376 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10377 // Example: L0 u< 13 => (L0 & 16) == 0
10378 const APInt *LC, *RC, *MaskC;
10379 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10380 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10382 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10383 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10384 return true;
10385 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10386 ConstantRange(*RC)))
10387 return false;
10388 }
10389
10390 return std::nullopt;
10391}
10392
10393/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10394/// is true. Return false if LHS implies RHS is false. Otherwise, return
10395/// std::nullopt if we can't infer anything.
10396static std::optional<bool>
10398 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10399 const DataLayout &DL, bool LHSIsTrue) {
10400 // The rest of the logic assumes the LHS condition is true. If that's not the
10401 // case, invert the predicate to make it so.
10402 if (!LHSIsTrue)
10403 LPred = FCmpInst::getInversePredicate(LPred);
10404
10405 // We can have non-canonical operands, so try to normalize any common operand
10406 // to L0/R0.
10407 if (L0 == R1) {
10408 std::swap(R0, R1);
10409 RPred = FCmpInst::getSwappedPredicate(RPred);
10410 }
10411 if (R0 == L1) {
10412 std::swap(L0, L1);
10413 LPred = FCmpInst::getSwappedPredicate(LPred);
10414 }
10415 if (L1 == R1) {
10416 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10417 if (L0 != R0 || match(L0, m_ImmConstant())) {
10418 std::swap(L0, L1);
10419 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10420 std::swap(R0, R1);
10421 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10422 }
10423 }
10424
10425 // Can we infer anything when the two compares have matching operands?
10426 if (L0 == R0 && L1 == R1) {
10427 if ((LPred & RPred) == LPred)
10428 return true;
10429 if ((LPred & ~RPred) == LPred)
10430 return false;
10431 }
10432
10433 // See if we can infer anything if operand-0 matches and we have at least one
10434 // constant.
10435 const APFloat *L1C, *R1C;
10436 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10437 if (std::optional<ConstantFPRange> DomCR =
10439 if (std::optional<ConstantFPRange> ImpliedCR =
10441 if (ImpliedCR->contains(*DomCR))
10442 return true;
10443 }
10444 if (std::optional<ConstantFPRange> ImpliedCR =
10446 FCmpInst::getInversePredicate(RPred), *R1C)) {
10447 if (ImpliedCR->contains(*DomCR))
10448 return false;
10449 }
10450 }
10451 }
10452
10453 return std::nullopt;
10454}
10455
10456/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10457/// false. Otherwise, return std::nullopt if we can't infer anything. We
10458/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10459/// instruction.
10460static std::optional<bool>
10462 const Value *RHSOp0, const Value *RHSOp1,
10463 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10464 // The LHS must be an 'or', 'and', or a 'select' instruction.
10465 assert((LHS->getOpcode() == Instruction::And ||
10466 LHS->getOpcode() == Instruction::Or ||
10467 LHS->getOpcode() == Instruction::Select) &&
10468 "Expected LHS to be 'and', 'or', or 'select'.");
10469
10470 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10471
10472 // If the result of an 'or' is false, then we know both legs of the 'or' are
10473 // false. Similarly, if the result of an 'and' is true, then we know both
10474 // legs of the 'and' are true.
10475 const Value *ALHS, *ARHS;
10476 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10477 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10478 // FIXME: Make this non-recursion.
10479 if (std::optional<bool> Implication = isImpliedCondition(
10480 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10481 return Implication;
10482 if (std::optional<bool> Implication = isImpliedCondition(
10483 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10484 return Implication;
10485 return std::nullopt;
10486 }
10487 return std::nullopt;
10488}
10489
10490std::optional<bool>
10492 const Value *RHSOp0, const Value *RHSOp1,
10493 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10494 // Bail out when we hit the limit.
10496 return std::nullopt;
10497
10498 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10499 // example.
10500 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10501 return std::nullopt;
10502
10503 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10504 "Expected integer type only!");
10505
10506 // Match not
10507 if (match(LHS, m_Not(m_Value(LHS))))
10508 LHSIsTrue = !LHSIsTrue;
10509
10510 // Both LHS and RHS are icmps.
10511 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10512 CmpPredicate LHSPred;
10513 Value *LHSOp0, *LHSOp1;
10514 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10515 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10516 RHSOp1, DL, LHSIsTrue);
10517 } else {
10518 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10519 "Expected floating point type only!");
10520 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10521 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10522 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10523 DL, LHSIsTrue);
10524 }
10525
10526 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10527 /// the RHS to be an icmp.
10528 /// FIXME: Add support for and/or/select on the RHS.
10529 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10530 if ((LHSI->getOpcode() == Instruction::And ||
10531 LHSI->getOpcode() == Instruction::Or ||
10532 LHSI->getOpcode() == Instruction::Select))
10533 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10534 Depth);
10535 }
10536 return std::nullopt;
10537}
10538
10539std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10540 const DataLayout &DL,
10541 bool LHSIsTrue, unsigned Depth) {
10542 // LHS ==> RHS by definition
10543 if (LHS == RHS)
10544 return LHSIsTrue;
10545
10546 // Match not
10547 bool InvertRHS = false;
10548 if (match(RHS, m_Not(m_Value(RHS)))) {
10549 if (LHS == RHS)
10550 return !LHSIsTrue;
10551 InvertRHS = true;
10552 }
10553
10554 CmpPredicate RHSPred;
10555 Value *RHSOp0, *RHSOp1;
10556 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10557 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10558 LHSIsTrue, Depth))
10559 return InvertRHS ? !*Implied : *Implied;
10560 return std::nullopt;
10561 }
10562 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10563 if (auto Implied = isImpliedCondition(
10564 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10565 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10566 return InvertRHS ? !*Implied : *Implied;
10567 return std::nullopt;
10568 }
10569
10571 return std::nullopt;
10572
10573 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10574 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10575 const Value *RHS1, *RHS2;
10576 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10577 if (std::optional<bool> Imp =
10578 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10579 if (*Imp == true)
10580 return !InvertRHS;
10581 if (std::optional<bool> Imp =
10582 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10583 if (*Imp == true)
10584 return !InvertRHS;
10585 }
10586 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10587 if (std::optional<bool> Imp =
10588 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10589 if (*Imp == false)
10590 return InvertRHS;
10591 if (std::optional<bool> Imp =
10592 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10593 if (*Imp == false)
10594 return InvertRHS;
10595 }
10596
10597 return std::nullopt;
10598}
10599
10600// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10601// condition dominating ContextI or nullptr, if no condition is found.
10602static std::pair<Value *, bool>
10604 if (!ContextI || !ContextI->getParent())
10605 return {nullptr, false};
10606
10607 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10608 // dominator tree (eg, from a SimplifyQuery) instead?
10609 const BasicBlock *ContextBB = ContextI->getParent();
10610 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10611 if (!PredBB)
10612 return {nullptr, false};
10613
10614 // We need a conditional branch in the predecessor.
10615 Value *PredCond;
10616 BasicBlock *TrueBB, *FalseBB;
10617 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10618 return {nullptr, false};
10619
10620 // The branch should get simplified. Don't bother simplifying this condition.
10621 if (TrueBB == FalseBB)
10622 return {nullptr, false};
10623
10624 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10625 "Predecessor block does not point to successor?");
10626
10627 // Is this condition implied by the predecessor condition?
10628 return {PredCond, TrueBB == ContextBB};
10629}
10630
10631std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10632 const Instruction *ContextI,
10633 const DataLayout &DL) {
10634 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10635 auto PredCond = getDomPredecessorCondition(ContextI);
10636 if (PredCond.first)
10637 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10638 return std::nullopt;
10639}
10640
10642 const Value *LHS,
10643 const Value *RHS,
10644 const Instruction *ContextI,
10645 const DataLayout &DL) {
10646 auto PredCond = getDomPredecessorCondition(ContextI);
10647 if (PredCond.first)
10648 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10649 PredCond.second);
10650 return std::nullopt;
10651}
10652
10654 APInt &Upper, const InstrInfoQuery &IIQ,
10655 bool PreferSignedRange) {
10656 unsigned Width = Lower.getBitWidth();
10657 const APInt *C;
10658 switch (BO.getOpcode()) {
10659 case Instruction::Sub:
10660 if (match(BO.getOperand(0), m_APInt(C))) {
10661 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10662 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10663
10664 // If the caller expects a signed compare, then try to use a signed range.
10665 // Otherwise if both no-wraps are set, use the unsigned range because it
10666 // is never larger than the signed range. Example:
10667 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10668 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10669 if (PreferSignedRange && HasNSW && HasNUW)
10670 HasNUW = false;
10671
10672 if (HasNUW) {
10673 // 'sub nuw c, x' produces [0, C].
10674 Upper = *C + 1;
10675 } else if (HasNSW) {
10676 if (C->isNegative()) {
10677 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10679 Upper = *C - APInt::getSignedMaxValue(Width);
10680 } else {
10681 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10682 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10683 Lower = *C - APInt::getSignedMaxValue(Width);
10685 }
10686 }
10687 }
10688 break;
10689 case Instruction::Add:
10690 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10691 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10692 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10693
10694 // If the caller expects a signed compare, then try to use a signed
10695 // range. Otherwise if both no-wraps are set, use the unsigned range
10696 // because it is never larger than the signed range. Example: "add nuw
10697 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10698 if (PreferSignedRange && HasNSW && HasNUW)
10699 HasNUW = false;
10700
10701 if (HasNUW) {
10702 // 'add nuw x, C' produces [C, UINT_MAX].
10703 Lower = *C;
10704 } else if (HasNSW) {
10705 if (C->isNegative()) {
10706 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10708 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10709 } else {
10710 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10711 Lower = APInt::getSignedMinValue(Width) + *C;
10712 Upper = APInt::getSignedMaxValue(Width) + 1;
10713 }
10714 }
10715 }
10716 break;
10717
10718 case Instruction::And:
10719 if (match(BO.getOperand(1), m_APInt(C)))
10720 // 'and x, C' produces [0, C].
10721 Upper = *C + 1;
10722 // X & -X is a power of two or zero. So we can cap the value at max power of
10723 // two.
10724 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10725 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10726 Upper = APInt::getSignedMinValue(Width) + 1;
10727 break;
10728
10729 case Instruction::Or:
10730 if (match(BO.getOperand(1), m_APInt(C)))
10731 // 'or x, C' produces [C, UINT_MAX].
10732 Lower = *C;
10733 break;
10734
10735 case Instruction::AShr:
10736 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10737 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10739 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10740 } else if (match(BO.getOperand(0), m_APInt(C))) {
10741 unsigned ShiftAmount = Width - 1;
10742 if (!C->isZero() && IIQ.isExact(&BO))
10743 ShiftAmount = C->countr_zero();
10744 if (C->isNegative()) {
10745 // 'ashr C, x' produces [C, C >> (Width-1)]
10746 Lower = *C;
10747 Upper = C->ashr(ShiftAmount) + 1;
10748 } else {
10749 // 'ashr C, x' produces [C >> (Width-1), C]
10750 Lower = C->ashr(ShiftAmount);
10751 Upper = *C + 1;
10752 }
10753 }
10754 break;
10755
10756 case Instruction::LShr:
10757 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10758 // 'lshr x, C' produces [0, UINT_MAX >> C].
10759 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10760 } else if (match(BO.getOperand(0), m_APInt(C))) {
10761 // 'lshr C, x' produces [C >> (Width-1), C].
10762 unsigned ShiftAmount = Width - 1;
10763 if (!C->isZero() && IIQ.isExact(&BO))
10764 ShiftAmount = C->countr_zero();
10765 Lower = C->lshr(ShiftAmount);
10766 Upper = *C + 1;
10767 }
10768 break;
10769
10770 case Instruction::Shl:
10771 if (match(BO.getOperand(0), m_APInt(C))) {
10772 if (IIQ.hasNoUnsignedWrap(&BO)) {
10773 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10774 Lower = *C;
10775 Upper = Lower.shl(Lower.countl_zero()) + 1;
10776 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10777 if (C->isNegative()) {
10778 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10779 unsigned ShiftAmount = C->countl_one() - 1;
10780 Lower = C->shl(ShiftAmount);
10781 Upper = *C + 1;
10782 } else {
10783 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10784 unsigned ShiftAmount = C->countl_zero() - 1;
10785 Lower = *C;
10786 Upper = C->shl(ShiftAmount) + 1;
10787 }
10788 } else {
10789 // If lowbit is set, value can never be zero.
10790 if ((*C)[0])
10791 Lower = APInt::getOneBitSet(Width, 0);
10792 // If we are shifting a constant the largest it can be is if the longest
10793 // sequence of consecutive ones is shifted to the highbits (breaking
10794 // ties for which sequence is higher). At the moment we take a liberal
10795 // upper bound on this by just popcounting the constant.
10796 // TODO: There may be a bitwise trick for it longest/highest
10797 // consecutative sequence of ones (naive method is O(Width) loop).
10798 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10799 }
10800 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10801 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10802 }
10803 break;
10804
10805 case Instruction::SDiv:
10806 if (match(BO.getOperand(1), m_APInt(C))) {
10807 APInt IntMin = APInt::getSignedMinValue(Width);
10808 APInt IntMax = APInt::getSignedMaxValue(Width);
10809 if (C->isAllOnes()) {
10810 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10811 // where C != -1 and C != 0 and C != 1
10812 Lower = IntMin + 1;
10813 Upper = IntMax + 1;
10814 } else if (C->countl_zero() < Width - 1) {
10815 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10816 // where C != -1 and C != 0 and C != 1
10817 Lower = IntMin.sdiv(*C);
10818 Upper = IntMax.sdiv(*C);
10819 if (Lower.sgt(Upper))
10821 Upper = Upper + 1;
10822 assert(Upper != Lower && "Upper part of range has wrapped!");
10823 }
10824 } else if (match(BO.getOperand(0), m_APInt(C))) {
10825 if (C->isMinSignedValue()) {
10826 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10827 Lower = *C;
10828 Upper = Lower.lshr(1) + 1;
10829 } else {
10830 // 'sdiv C, x' produces [-|C|, |C|].
10831 Upper = C->abs() + 1;
10832 Lower = (-Upper) + 1;
10833 }
10834 }
10835 break;
10836
10837 case Instruction::UDiv:
10838 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10839 // 'udiv x, C' produces [0, UINT_MAX / C].
10840 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10841 } else if (match(BO.getOperand(0), m_APInt(C))) {
10842 // 'udiv C, x' produces [0, C].
10843 Upper = *C + 1;
10844 }
10845 break;
10846
10847 case Instruction::SRem:
10848 if (match(BO.getOperand(1), m_APInt(C))) {
10849 // 'srem x, C' produces (-|C|, |C|).
10850 Upper = C->abs();
10851 Lower = (-Upper) + 1;
10852 } else if (match(BO.getOperand(0), m_APInt(C))) {
10853 if (C->isNegative()) {
10854 // 'srem -|C|, x' produces [-|C|, 0].
10855 Upper = 1;
10856 Lower = *C;
10857 } else {
10858 // 'srem |C|, x' produces [0, |C|].
10859 Upper = *C + 1;
10860 }
10861 }
10862 break;
10863
10864 case Instruction::URem:
10865 if (match(BO.getOperand(1), m_APInt(C)))
10866 // 'urem x, C' produces [0, C).
10867 Upper = *C;
10868 else if (match(BO.getOperand(0), m_APInt(C)))
10869 // 'urem C, x' produces [0, C].
10870 Upper = *C + 1;
10871 break;
10872
10873 default:
10874 break;
10875 }
10876}
10877
10879 bool UseInstrInfo) {
10880 unsigned Width = II.getType()->getScalarSizeInBits();
10881 const APInt *C;
10882 switch (II.getIntrinsicID()) {
10883 case Intrinsic::ctlz:
10884 case Intrinsic::cttz: {
10885 APInt Upper(Width, Width);
10886 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10887 Upper += 1;
10888 // Maximum of set/clear bits is the bit width.
10890 }
10891 case Intrinsic::ctpop:
10892 // Maximum of set/clear bits is the bit width.
10894 APInt(Width, Width) + 1);
10895 case Intrinsic::uadd_sat:
10896 // uadd.sat(x, C) produces [C, UINT_MAX].
10897 if (match(II.getOperand(0), m_APInt(C)) ||
10898 match(II.getOperand(1), m_APInt(C)))
10900 break;
10901 case Intrinsic::sadd_sat:
10902 if (match(II.getOperand(0), m_APInt(C)) ||
10903 match(II.getOperand(1), m_APInt(C))) {
10904 if (C->isNegative())
10905 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10907 APInt::getSignedMaxValue(Width) + *C +
10908 1);
10909
10910 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10912 APInt::getSignedMaxValue(Width) + 1);
10913 }
10914 break;
10915 case Intrinsic::usub_sat:
10916 // usub.sat(C, x) produces [0, C].
10917 if (match(II.getOperand(0), m_APInt(C)))
10918 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10919
10920 // usub.sat(x, C) produces [0, UINT_MAX - C].
10921 if (match(II.getOperand(1), m_APInt(C)))
10923 APInt::getMaxValue(Width) - *C + 1);
10924 break;
10925 case Intrinsic::ssub_sat:
10926 if (match(II.getOperand(0), m_APInt(C))) {
10927 if (C->isNegative())
10928 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10930 *C - APInt::getSignedMinValue(Width) +
10931 1);
10932
10933 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10935 APInt::getSignedMaxValue(Width) + 1);
10936 } else if (match(II.getOperand(1), m_APInt(C))) {
10937 if (C->isNegative())
10938 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10940 APInt::getSignedMaxValue(Width) + 1);
10941
10942 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10944 APInt::getSignedMaxValue(Width) - *C +
10945 1);
10946 }
10947 break;
10948 case Intrinsic::ushl_sat:
10949 if (match(II.getOperand(0), m_APInt(C)))
10951 break;
10952 case Intrinsic::sshl_sat:
10953 if (match(II.getOperand(0), m_APInt(C))) {
10954 if (C->isNegative())
10956 *C + 1);
10958 APInt::getSignedMaxValue(Width) + 1);
10959 }
10960 break;
10961 case Intrinsic::umin:
10962 case Intrinsic::umax:
10963 case Intrinsic::smin:
10964 case Intrinsic::smax:
10965 if (!match(II.getOperand(0), m_APInt(C)) &&
10966 !match(II.getOperand(1), m_APInt(C)))
10967 break;
10968
10969 switch (II.getIntrinsicID()) {
10970 case Intrinsic::umin:
10971 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10972 case Intrinsic::umax:
10974 case Intrinsic::smin:
10976 *C + 1);
10977 case Intrinsic::smax:
10979 APInt::getSignedMaxValue(Width) + 1);
10980 default:
10981 llvm_unreachable("Must be min/max intrinsic");
10982 }
10983 break;
10984 case Intrinsic::abs:
10985 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10986 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10987 if (match(II.getOperand(1), m_One()))
10989 APInt::getSignedMaxValue(Width) + 1);
10990
10992 APInt::getSignedMinValue(Width) + 1);
10993 case Intrinsic::vscale:
10994 if (!II.getParent() || !II.getFunction())
10995 break;
10996 return getVScaleRange(II.getFunction(), Width);
10997 case Intrinsic::read_register:
10998 case Intrinsic::read_volatile_register: {
10999 const Module *M = II.getModule();
11000 if (!M || !M->getTargetTriple().isRISCV())
11001 break;
11002 if (II.getFunction() && isReadVLENB(II))
11003 return getRISCVVLENBRange(II, Width);
11004 break;
11005 }
11006 default:
11007 break;
11008 }
11009
11010 return ConstantRange::getFull(Width);
11011}
11012
11014 const InstrInfoQuery &IIQ) {
11015 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
11016 const Value *LHS = nullptr, *RHS = nullptr;
11018 if (R.Flavor == SPF_UNKNOWN)
11019 return ConstantRange::getFull(BitWidth);
11020
11021 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
11022 // If the negation part of the abs (in RHS) has the NSW flag,
11023 // then the result of abs(X) is [0..SIGNED_MAX],
11024 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
11025 if (match(RHS, m_Neg(m_Specific(LHS))) &&
11029
11032 }
11033
11034 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
11035 // The result of -abs(X) is <= 0.
11037 APInt(BitWidth, 1));
11038 }
11039
11040 const APInt *C;
11041 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
11042 return ConstantRange::getFull(BitWidth);
11043
11044 switch (R.Flavor) {
11045 case SPF_UMIN:
11047 case SPF_UMAX:
11049 case SPF_SMIN:
11051 *C + 1);
11052 case SPF_SMAX:
11055 default:
11056 return ConstantRange::getFull(BitWidth);
11057 }
11058}
11059
11061 // The maximum representable value of a half is 65504. For floats the maximum
11062 // value is 3.4e38 which requires roughly 129 bits.
11063 unsigned BitWidth = I->getType()->getScalarSizeInBits();
11064 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
11065 return;
11066 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
11067 Lower = APInt(BitWidth, -65504, true);
11068 Upper = APInt(BitWidth, 65505);
11069 }
11070
11071 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
11072 // For a fptoui the lower limit is left as 0.
11073 Upper = APInt(BitWidth, 65505);
11074 }
11075}
11076
11078 const SimplifyQuery &SQ,
11079 unsigned Depth) {
11080 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
11081
11083 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
11084
11085 if (auto *C = dyn_cast<Constant>(V))
11086 return C->toConstantRange();
11087
11088 unsigned BitWidth = V->getType()->getScalarSizeInBits();
11089 ConstantRange CR = ConstantRange::getFull(BitWidth);
11090 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
11091 APInt Lower = APInt(BitWidth, 0);
11092 APInt Upper = APInt(BitWidth, 0);
11093 // TODO: Return ConstantRange.
11094 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
11096 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
11098 else if (auto *SI = dyn_cast<SelectInst>(V)) {
11099 ConstantRange CRTrue =
11100 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
11101 ConstantRange CRFalse =
11102 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
11103 CR = CRTrue.unionWith(CRFalse, ForSigned ? ConstantRange::Signed
11106 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
11107 ConstantRange SrcCR =
11108 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
11109 CR = SrcCR.truncate(BitWidth);
11110 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
11111 ConstantRange SrcCR =
11112 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
11113 CR = SrcCR.zeroExtend(BitWidth);
11114 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
11115 ConstantRange SrcCR =
11116 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
11117 CR = SrcCR.signExtend(BitWidth);
11118 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
11119 APInt Lower = APInt(BitWidth, 0);
11120 APInt Upper = APInt(BitWidth, 0);
11121 // TODO: Return ConstantRange.
11124 } else if (const auto *A = dyn_cast<Argument>(V))
11125 if (std::optional<ConstantRange> Range = A->getRange())
11126 CR = *Range;
11127
11128 if (auto *I = dyn_cast<Instruction>(V)) {
11129 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
11131
11132 Value *FrexpSrc;
11133 if (const auto *CB = dyn_cast<CallBase>(V)) {
11134 if (std::optional<ConstantRange> Range = CB->getRange())
11135 CR = CR.intersectWith(*Range);
11137 m_Value(FrexpSrc))))) {
11138 const fltSemantics &FltSem =
11139 FrexpSrc->getType()->getScalarType()->getFltSemantics();
11140 // It should be possible to implement this for any type, but this logic
11141 // only computes the range assuming standard subnormal handling.
11142 if (APFloat::isIEEELikeFP(FltSem)) {
11144 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
11145
11146 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
11147 // constrain its range when the source can be neither.
11148 if (KnownSrc.isKnownNeverInfOrNaN()) {
11149 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
11150
11151 // Offset to find the true minimum exponent value for a denormal.
11152 if (!KnownSrc.isKnownNeverSubnormal())
11153 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
11154
11155 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
11156
11157 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
11159
11160 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
11161 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
11162
11163 MinExp = std::max(AdjustedMin, MinExp);
11164 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
11165 MaxExp);
11166
11168 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
11169 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
11170 /*isSigned=*/true));
11171 }
11172 }
11173 }
11174 }
11175
11176 if (SQ.CtxI && SQ.AC) {
11177 // Try to restrict the range based on information from assumptions.
11178 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
11179 if (!AssumeVH)
11180 continue;
11181 CallInst *I = cast<CallInst>(AssumeVH);
11182 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
11183 "Got assumption for the wrong function!");
11184 assert(I->getIntrinsicID() == Intrinsic::assume &&
11185 "must be an assume intrinsic");
11186
11187 if (AssumeVH.Index != AssumptionCache::ExprResultIdx) {
11188 auto OBU = I->getOperandBundleAt(AssumeVH.Index);
11189 if (getBundleAttrFromOBU(OBU) == BundleAttr::Range) {
11190 auto [Val, Range] = getAssumeRangeInfo(OBU);
11191 if (Val == V && isValidAssumeForContext(I, SQ))
11192 CR = CR.intersectWith(Range);
11193 }
11194 continue;
11195 }
11196
11197 if (!isValidAssumeForContext(I, SQ))
11198 continue;
11199 Value *Arg = I->getArgOperand(0);
11200 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
11201 // Currently we just use information from comparisons.
11202 if (!Cmp || Cmp->getOperand(0) != V)
11203 continue;
11204 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
11205 ConstantRange RHS =
11206 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
11207 SQ.getWithInstruction(I), Depth + 1);
11208 CR = CR.intersectWith(
11209 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
11210 }
11211 }
11212
11213 return CR;
11214}
11215
11216static void
11218 function_ref<void(Value *)> InsertAffected) {
11219 assert(V != nullptr);
11220 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
11221 InsertAffected(V);
11222 } else if (auto *I = dyn_cast<Instruction>(V)) {
11223 InsertAffected(V);
11224
11225 // Peek through unary operators to find the source of the condition.
11226 Value *Op;
11228 m_Trunc(m_Value(Op))))) {
11230 InsertAffected(Op);
11231 }
11232 }
11233}
11234
11236 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
11237 auto AddAffected = [&InsertAffected](Value *V) {
11238 addValueAffectedByCondition(V, InsertAffected);
11239 };
11240
11241 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
11242 if (IsAssume) {
11243 AddAffected(LHS);
11244 AddAffected(RHS);
11245 } else if (match(RHS, m_Constant()))
11246 AddAffected(LHS);
11247 };
11248
11249 SmallVector<Value *, 8> Worklist;
11251 Worklist.push_back(Cond);
11252 while (!Worklist.empty()) {
11253 Value *V = Worklist.pop_back_val();
11254 if (!Visited.insert(V).second)
11255 continue;
11256
11257 CmpPredicate Pred;
11258 Value *A, *B, *X;
11259
11260 if (IsAssume) {
11261 AddAffected(V);
11262 if (match(V, m_Not(m_Value(X))))
11263 AddAffected(X);
11264 }
11265
11266 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
11267 // assume(A && B) is split to -> assume(A); assume(B);
11268 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
11269 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
11270 // enough information to be worth handling (intersection of information as
11271 // opposed to union).
11272 if (!IsAssume) {
11273 Worklist.push_back(A);
11274 Worklist.push_back(B);
11275 }
11276 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
11277 bool HasRHSC = match(B, m_ConstantInt());
11278 if (ICmpInst::isEquality(Pred)) {
11279 AddAffected(A);
11280 if (IsAssume)
11281 AddAffected(B);
11282
11283 // If the remainder is zero, then the division is exact.
11284 Value *RemLHS, *RemRHS;
11285 if (match(B, m_Zero()) &&
11286 match(A, m_IRem(m_Value(RemLHS), m_Value(RemRHS)))) {
11287 AddAffected(RemLHS);
11288 AddAffected(RemRHS);
11289 }
11290
11291 if (HasRHSC) {
11292 Value *Y;
11293 // (X << C) or (X >>_s C) or (X >>_u C).
11294 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
11295 AddAffected(X);
11296 // (X & C) or (X | C).
11297 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11298 match(A, m_Or(m_Value(X), m_Value(Y)))) {
11299 AddAffected(X);
11300 AddAffected(Y);
11301 }
11302 // X - Y
11303 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11304 AddAffected(X);
11305 AddAffected(Y);
11306 }
11307 }
11308 } else {
11309 AddCmpOperands(A, B);
11310 if (HasRHSC) {
11311 Value *Y;
11312 // Handle (A + C1) u< C2, which is the canonical form of
11313 // A > C3 && A < C4.
11315 AddAffected(X);
11316 // X - Y pred C, which implies X != Y if 0 pred C is false.
11317 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11318 AddAffected(X);
11319 AddAffected(Y);
11320 }
11321
11322 if (ICmpInst::isUnsigned(Pred)) {
11323 // X & Y u> C -> X >u C && Y >u C
11324 // X | Y u< C -> X u< C && Y u< C
11325 // X nuw+ Y u< C -> X u< C && Y u< C
11326 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11327 match(A, m_Or(m_Value(X), m_Value(Y))) ||
11328 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
11329 AddAffected(X);
11330 AddAffected(Y);
11331 }
11332 }
11333 }
11334
11335 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11336 // by computeKnownFPClass().
11338 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11339 InsertAffected(X);
11340 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11341 InsertAffected(X);
11342 }
11343 }
11344
11345 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11346 Value *SquareOp = nullptr;
11347 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11348 AddAffected(SquareOp);
11349 };
11350 AddNuwSquareOperand(A);
11351 AddNuwSquareOperand(B);
11352
11353 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11354 AddAffected(X);
11355 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11356 AddCmpOperands(A, B);
11357
11358 // fcmp fneg(x), y
11359 // fcmp fabs(x), y
11360 // fcmp fneg(fabs(x)), y
11361 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
11363 AddAffected(A);
11364 if (match(A, m_FAbs(m_Value(A))))
11365 AddAffected(A);
11366
11368 m_Value()))) {
11369 // Handle patterns that computeKnownFPClass() support.
11370 AddAffected(A);
11371 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11372 // Assume is checked here as X is already added above for assumes in
11373 // addValueAffectedByCondition
11374 AddAffected(X);
11375 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11376 // Assume is checked here to avoid issues with ephemeral values
11377 Worklist.push_back(X);
11378 }
11379 }
11380}
11381
11383 // (X >> C) or/add (X & mask(C) != 0)
11384 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11385 if (BO->getOpcode() == Instruction::Add ||
11386 BO->getOpcode() == Instruction::Or) {
11387 const Value *X;
11388 const APInt *C1, *C2;
11389 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11393 m_Zero())))) &&
11394 C2->popcount() == C1->getZExtValue())
11395 return X;
11396 }
11397 }
11398
11399 // select(cond, X, -X)
11400 {
11401 const Value *X;
11402 if (match(V, m_c_Select(m_Value(X), m_Neg(m_Deferred(X)))))
11403 return X;
11404 }
11405
11406 return nullptr;
11407}
11408
11410 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11411}
11412
11415 unsigned MaxCount, bool AllowUndefOrPoison) {
11418 auto Push = [&](const Value *V) -> bool {
11419 Constant *C;
11420 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11421 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11422 return false;
11423 // Check existence first to avoid unnecessary allocations.
11424 if (Constants.contains(C))
11425 return true;
11426 if (Constants.size() == MaxCount)
11427 return false;
11428 Constants.insert(C);
11429 return true;
11430 }
11431
11432 if (auto *Inst = dyn_cast<Instruction>(V)) {
11433 if (Visited.insert(Inst).second)
11434 Worklist.push_back(Inst);
11435 return true;
11436 }
11437 return false;
11438 };
11439 if (!Push(V))
11440 return false;
11441 while (!Worklist.empty()) {
11442 const Instruction *CurInst = Worklist.pop_back_val();
11443 switch (CurInst->getOpcode()) {
11444 case Instruction::Select:
11445 if (!Push(CurInst->getOperand(1)))
11446 return false;
11447 if (!Push(CurInst->getOperand(2)))
11448 return false;
11449 break;
11450 case Instruction::PHI:
11451 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11452 // Fast path for recurrence PHI.
11453 if (IncomingValue == CurInst)
11454 continue;
11455 if (!Push(IncomingValue))
11456 return false;
11457 }
11458 break;
11459 default:
11460 return false;
11461 }
11462 }
11463 return true;
11464}
const TargetLowering & TLI
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t 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...
bpf unwind BPF Unwind Lower
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
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
if(PassOpts->AAPipeline)
R600 Clause Merge
SmallVector< MachineOperand, 4 > Cond
int64_t C1
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 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 const Instruction * safeCtxI(const Value *V, const Instruction *CtxI)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static bool isNonZeroAddrPlusOffset(const SimplifyQuery &Q, Value *X, Value *Y)
Return true if "addr(P) + Off" cannot be zero.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void computeKnownBitsFromEuclideanRem(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Infer non-negativity for R + (R < 0 ?
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 bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
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 void computeKnownFPClassForFPTrunc(const Operator *Op, RoundingMode RM, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
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 SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match non-obvious integer minimum and maximum sequences.
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 void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CtxI, KnownFPClass &KnownFromContext, unsigned Depth=0)
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 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 void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownFPClassForFAddSub(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth, bool IsAdd, bool IsStrict)
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 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 computeKnownFPClassForFRem(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:643
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:618
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:639
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:614
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:610
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:647
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:635
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:660
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:651
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:6401
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1683
bool isFinite() const
Definition APFloat.h:1617
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1271
bool isInteger() const
Definition APFloat.h:1629
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2018
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:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1405
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
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:1253
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:1170
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
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:352
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
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:107
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:263
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
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 bool isEntryBlock() const
Return true if this is the entry block of the containing function.
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 ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
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.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
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:44
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:65
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:220
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:521
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:794
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:803
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.
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode)
Report known values for atan2.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode)
Report known values for fma.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy, RoundingMode RM, DenormalMode DstMode, DenormalMode SrcMode)
Propagate known class for fptrunc and fptrunc_round.
static constexpr FPClassTest OrderedLessThanZeroMask
static LLVM_ABI KnownFPClass trunc(const KnownFPClass &Src, DenormalMode Mode)
Propagate known class for trunc.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, RoundingMode RM, DenormalMode Mode)
Report known values for fadd.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, RoundingMode RM, DenormalMode Mode)
Report known values for fsub.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode)
Report known values for fma squared, squared, addend.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, RoundingMode RM, DenormalMode Mode)
Report known values for fadd x, x.
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 frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode)
Report known values for frem.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode)
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode)
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode)
Propagate known class for rounding intrinsics (rint, nearbyint, round, roundeven).
static LLVM_ABI KnownFPClass sinpi(const KnownFPClass &Src, bool IsMultiUnitFPType)
Report known values for sinpi.
static LLVM_ABI KnownFPClass fmuladd(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode)
Report known values for fmuladd.
static LLVM_ABI KnownFPClass ceil(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode)
Propagate known class for ceil.
static LLVM_ABI KnownFPClass fmuladd_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode)
Report known values for fmuladd squared, squared, addend.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy, DenormalMode DstMode, DenormalMode SrcMode)
Propagate known class for fpext.
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.
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
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.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode Mode)
void knownNot(FPClassMask RuleOut)
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, const fltSemantics &Flt, DenormalMode Mode)
Apply the canonicalize intrinsic to this value.
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 floor(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode)
Propagate known class for floor.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static KnownFPClass getEmpty()
static LLVM_ABI KnownFPClass cospi(const KnownFPClass &Src, bool IsMultiUnitFPType)
Report known values for cospi.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
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.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode)
Report known values for fdiv x, x.
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 isKnownNever(FPClassMask Mask) const
Return true if it's known this can never be one of the mask entries.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
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 square(const KnownFPClass &Src, DenormalMode Mode)
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode, bool IsMultiUnitFPType)
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode)
Report known values for frem x, x. Valid for all rounding modes.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode)
Report known values for fdiv.
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode)
Report known values for fmul.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
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.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
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:1087
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1443
Root of the metadata hierarchy.
Definition Metadata.h:65
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.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
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:589
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:746
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:777
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.
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 uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:292
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
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
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:298
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
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:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
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:3052
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
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)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
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().
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
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)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
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)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
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)
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.
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:680
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)
@ 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
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 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
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 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 const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
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:2229
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 void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 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)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1736
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 isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=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.
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.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
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 isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=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 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,...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
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 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.
FPOp
The floating-point operations supported by the folding helpers.
Definition FPFold.h:25
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 isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
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 bool programUndefinedIfPoison(const Instruction *Inst)
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.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
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 const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
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 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 Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
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 bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
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 isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
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:246
RoundingMode
Rounding mode.
@ NearestTiesToEven
roundTiesToEven.
@ Dynamic
Denotes mode unknown at compile time.
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 bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
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.
LLVM_ABI AssumeRangeInfo getAssumeRangeInfo(OperandBundleUse)
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...
LLVM_ABI std::optional< RoundingMode > convertStrToRoundingMode(StringRef)
Returns a valid RoundingMode enumerator when given a string that is valid as input in constrained int...
Definition FPEnv.cpp:25
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...
auto predecessors(const MachineBasicBlock *BB)
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...
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)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
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:202
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.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
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 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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
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:881
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...
LLVM_ABI KnownBits ctlz(bool ZeroIsPoison=false) const
Compute known bits for the count of leading zeros.
KnownBits byteSwap() const
Definition KnownBits.h:562
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:566
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:62
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
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
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 DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const Instruction * CtxI
const Function * getFunction() const
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1067