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/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/ScopeExit.h"
23#include "llvm/ADT/StringRef.h"
33#include "llvm/Analysis/Loads.h"
38#include "llvm/IR/Argument.h"
39#include "llvm/IR/Attributes.h"
40#include "llvm/IR/BasicBlock.h"
42#include "llvm/IR/Constant.h"
45#include "llvm/IR/Constants.h"
48#include "llvm/IR/Dominators.h"
50#include "llvm/IR/Function.h"
52#include "llvm/IR/GlobalAlias.h"
53#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/InstrTypes.h"
56#include "llvm/IR/Instruction.h"
59#include "llvm/IR/Intrinsics.h"
60#include "llvm/IR/IntrinsicsAArch64.h"
61#include "llvm/IR/IntrinsicsAMDGPU.h"
62#include "llvm/IR/IntrinsicsRISCV.h"
63#include "llvm/IR/IntrinsicsX86.h"
64#include "llvm/IR/LLVMContext.h"
65#include "llvm/IR/Metadata.h"
66#include "llvm/IR/Module.h"
67#include "llvm/IR/Operator.h"
69#include "llvm/IR/Type.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
81#include <algorithm>
82#include <cassert>
83#include <cstdint>
84#include <optional>
85#include <utility>
86
87using namespace llvm;
88using namespace llvm::PatternMatch;
89
90// Controls the number of uses of the value searched for possible
91// dominating comparisons.
92static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
93 cl::Hidden, cl::init(20));
94
95/// Maximum number of instructions to check between assume and context
96/// instruction.
97static constexpr unsigned MaxInstrsToCheckForFree = 32;
98
99/// Returns the bitwidth of the given scalar or pointer type. For vector types,
100/// returns the element type's bitwidth.
101static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
102 if (unsigned BitWidth = Ty->getScalarSizeInBits())
103 return BitWidth;
104
105 return DL.getPointerTypeSizeInBits(Ty);
106}
107
108// Given the provided Value and, potentially, a context instruction, return
109// the preferred context instruction (if any).
110static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
111 // If we've been provided with a context instruction, then use that (provided
112 // it has been inserted).
113 if (CxtI && CxtI->getParent())
114 return CxtI;
115
116 // If the value is really an already-inserted instruction, then use that.
117 CxtI = dyn_cast<Instruction>(V);
118 if (CxtI && CxtI->getParent())
119 return CxtI;
120
121 return nullptr;
122}
123
125 const APInt &DemandedElts,
126 APInt &DemandedLHS, APInt &DemandedRHS) {
127 if (isa<ScalableVectorType>(Shuf->getType())) {
128 assert(DemandedElts == APInt(1,1));
129 DemandedLHS = DemandedRHS = DemandedElts;
130 return true;
131 }
132
133 int NumElts =
134 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
135 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
136 DemandedElts, DemandedLHS, DemandedRHS);
137}
138
139static void computeKnownBits(const Value *V, const APInt &DemandedElts,
140 KnownBits &Known, const SimplifyQuery &Q,
141 unsigned Depth);
142
144 const SimplifyQuery &Q, unsigned Depth) {
145 // Since the number of lanes in a scalable vector is unknown at compile time,
146 // we track one bit which is implicitly broadcast to all lanes. This means
147 // that all lanes in a scalable vector are considered demanded.
148 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
149 APInt DemandedElts =
150 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
151 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
152}
153
155 const DataLayout &DL, AssumptionCache *AC,
156 const Instruction *CxtI, const DominatorTree *DT,
157 bool UseInstrInfo, unsigned Depth) {
159 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
160 Depth);
161}
162
164 AssumptionCache *AC, const Instruction *CxtI,
165 const DominatorTree *DT, bool UseInstrInfo,
166 unsigned Depth) {
167 return computeKnownBits(
168 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
169}
170
171KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
172 const DataLayout &DL, AssumptionCache *AC,
173 const Instruction *CxtI,
174 const DominatorTree *DT, bool UseInstrInfo,
175 unsigned Depth) {
176 return computeKnownBits(
177 V, DemandedElts,
178 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
179}
180
183 const SimplifyQuery &SQ) {
184 // Look for an inverted mask: (X & ~M) op (Y & M).
185 {
186 Value *M;
187 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
189 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
192 }
193
194 // X op (Y & ~X)
196 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
199
200 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
201 // for constant Y.
202 Value *Y;
203 if (match(RHS,
205 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
206 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
207 return IsNoUndef ? NoCommonBitsSetResult::Known
209 }
210
211 // Peek through extends to find a 'not' of the other side:
212 // (ext Y) op ext(~Y)
213 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
215 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
218
219 // Look for: (A & B) op ~(A | B)
220 {
221 Value *A, *B;
222 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
224 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
225 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
226 return IsNoUndef ? NoCommonBitsSetResult::Known
228 }
229 }
230
231 // Look for: (X << V) op (Y >> (BitWidth - V))
232 // or (X >> V) op (Y << (BitWidth - V))
233 {
234 const Value *V;
235 const APInt *R;
236 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
237 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
238 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
239 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
240 R->uge(LHS->getType()->getScalarSizeInBits()))
242 }
243
245}
246
249 const WithCache<const Value *> &RHSCache,
250 const SimplifyQuery &SQ) {
251 const Value *LHS = LHSCache.getValue();
252 const Value *RHS = RHSCache.getValue();
253
254 assert(LHS->getType() == RHS->getType() &&
255 "LHS and RHS should have the same type");
256 assert(LHS->getType()->isIntOrIntVectorTy() &&
257 "LHS and RHS should be integers");
258
260 if (Result == NoCommonBitsSetResult::Known)
262
263 NoCommonBitsSetResult CommuteResult =
265 if (CommuteResult == NoCommonBitsSetResult::Known)
267
269 RHSCache.getKnownBits(SQ)))
271
275
277}
278
280 const WithCache<const Value *> &RHSCache,
281 const SimplifyQuery &SQ) {
282 NoCommonBitsSetResult Result =
283 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
284 return Result == NoCommonBitsSetResult::Known;
285}
286
288 return !I->user_empty() &&
289 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
290}
291
293 return !I->user_empty() && all_of(I->users(), [](const User *U) {
294 CmpPredicate P;
295 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
296 });
297}
298
300 bool OrZero, AssumptionCache *AC,
301 const Instruction *CxtI,
302 const DominatorTree *DT, bool UseInstrInfo,
303 unsigned Depth) {
304 return ::isKnownToBeAPowerOfTwo(
305 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
306 Depth);
307}
308
309static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
310 const SimplifyQuery &Q, unsigned Depth);
311
313 unsigned Depth) {
314 return computeKnownBits(V, SQ, Depth).isNonNegative();
315}
316
318 unsigned Depth) {
319 if (auto *CI = dyn_cast<ConstantInt>(V))
320 return CI->getValue().isStrictlyPositive();
321
322 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
323 // this updated.
325 return Known.isNonNegative() &&
326 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
327}
328
330 unsigned Depth) {
331 return computeKnownBits(V, SQ, Depth).isNegative();
332}
333
334static bool isKnownNonEqual(const Value *V1, const Value *V2,
335 const APInt &DemandedElts, const SimplifyQuery &Q,
336 unsigned Depth);
337
338bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
339 const SimplifyQuery &Q, unsigned Depth) {
340 // We don't support looking through casts.
341 if (V1 == V2 || V1->getType() != V2->getType())
342 return false;
343 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
344 APInt DemandedElts =
345 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
346 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
347}
348
349bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
350 const SimplifyQuery &SQ, unsigned Depth) {
351 KnownBits Known(Mask.getBitWidth());
353 return Mask.isSubsetOf(Known.Zero);
354}
355
356static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
357 const SimplifyQuery &Q, unsigned Depth);
358
359static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
360 unsigned Depth = 0) {
361 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
362 APInt DemandedElts =
363 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
364 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
365}
366
367unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
368 AssumptionCache *AC, const Instruction *CxtI,
369 const DominatorTree *DT, bool UseInstrInfo,
370 unsigned Depth) {
371 return ::ComputeNumSignBits(
372 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
373}
374
376 AssumptionCache *AC,
377 const Instruction *CxtI,
378 const DominatorTree *DT,
379 unsigned Depth) {
380 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
381 return V->getType()->getScalarSizeInBits() - SignBits + 1;
382}
383
384/// Try to detect the lerp pattern: a * (b - c) + c * d
385/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
386///
387/// In that particular case, we can use the following chain of reasoning:
388///
389/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
390///
391/// Since that is true for arbitrary a, b, c and d within our constraints, we
392/// can conclude that:
393///
394/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
395///
396/// Considering that any result of the lerp would be less or equal to U, it
397/// would have at least the number of leading 0s as in U.
398///
399/// While being quite a specific situation, it is fairly common in computer
400/// graphics in the shape of alpha blending.
401///
402/// Modifies given KnownOut in-place with the inferred information.
403static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
404 const APInt &DemandedElts,
405 KnownBits &KnownOut,
406 const SimplifyQuery &Q,
407 unsigned Depth) {
408
409 Type *Ty = Op0->getType();
410 const unsigned BitWidth = Ty->getScalarSizeInBits();
411
412 // Only handle scalar types for now
413 if (Ty->isVectorTy())
414 return;
415
416 // Try to match: a * (b - c) + c * d.
417 // When a == 1 => A == nullptr, the same applies to d/D as well.
418 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
419 const Instruction *SubBC = nullptr;
420
421 const auto MatchSubBC = [&]() {
422 // (b - c) can have two forms that interest us:
423 //
424 // 1. sub nuw %b, %c
425 // 2. xor %c, %b
426 //
427 // For the first case, nuw flag guarantees our requirement b >= c.
428 //
429 // The second case might happen when the analysis can infer that b is a mask
430 // for c and we can transform sub operation into xor (that is usually true
431 // for constant b's). Even though xor is symmetrical, canonicalization
432 // ensures that the constant will be the RHS. We have additional checks
433 // later on to ensure that this xor operation is equivalent to subtraction.
435 m_Xor(m_Value(C), m_Value(B))));
436 };
437
438 const auto MatchASubBC = [&]() {
439 // Cases:
440 // - a * (b - c)
441 // - (b - c) * a
442 // - (b - c) <- a implicitly equals 1
443 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
444 };
445
446 const auto MatchCD = [&]() {
447 // Cases:
448 // - d * c
449 // - c * d
450 // - c <- d implicitly equals 1
452 };
453
454 const auto Match = [&](const Value *LHS, const Value *RHS) {
455 // We do use m_Specific(C) in MatchCD, so we have to make sure that
456 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
457 // has to evaluate first and return true.
458 //
459 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
460 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
461 };
462
463 if (!Match(Op0, Op1) && !Match(Op1, Op0))
464 return;
465
466 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
467 // For some of the values we use the convention of leaving
468 // it nullptr to signify an implicit constant 1.
469 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
471 };
472
473 // Check that all operands are non-negative
474 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
475 if (!KnownA.isNonNegative())
476 return;
477
478 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
479 if (!KnownD.isNonNegative())
480 return;
481
482 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
483 if (!KnownB.isNonNegative())
484 return;
485
486 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
487 if (!KnownC.isNonNegative())
488 return;
489
490 // If we matched subtraction as xor, we need to actually check that xor
491 // is semantically equivalent to subtraction.
492 //
493 // For that to be true, b has to be a mask for c or that b's known
494 // ones cover all known and possible ones of c.
495 if (SubBC->getOpcode() == Instruction::Xor &&
496 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
497 return;
498
499 const APInt MaxA = KnownA.getMaxValue();
500 const APInt MaxD = KnownD.getMaxValue();
501 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
502 const APInt MaxB = KnownB.getMaxValue();
503
504 // We can't infer leading zeros info if the upper-bound estimate wraps.
505 bool Overflow;
506 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
507
508 if (Overflow)
509 return;
510
511 // If we know that x <= y and both are positive than x has at least the same
512 // number of leading zeros as y.
513 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
514 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
515}
516
517static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
518 bool NSW, bool NUW,
519 const APInt &DemandedElts,
520 KnownBits &KnownOut, KnownBits &Known2,
521 const SimplifyQuery &Q, unsigned Depth) {
522 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
523
524 // If one operand is unknown and we have no nowrap information,
525 // the result will be unknown independently of the second operand.
526 if (KnownOut.isUnknown() && !NSW && !NUW)
527 return;
528
529 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
530 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
531
532 if (!Add && NSW && !KnownOut.isNonNegative() &&
534 .value_or(false) ||
535 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
536 KnownOut.makeNonNegative();
537
538 if (Add)
539 // Try to match lerp pattern and combine results
540 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
541}
542
543static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
544 bool NUW, const APInt &DemandedElts,
545 KnownBits &Known, KnownBits &Known2,
546 const SimplifyQuery &Q, unsigned Depth) {
547 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
548 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
549
550 bool isKnownNegative = false;
551 bool isKnownNonNegative = false;
552 // If the multiplication is known not to overflow, compute the sign bit.
553 if (NSW) {
554 if (Op0 == Op1) {
555 // The product of a number with itself is non-negative.
556 isKnownNonNegative = true;
557 } else {
558 bool isKnownNonNegativeOp1 = Known.isNonNegative();
559 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
560 bool isKnownNegativeOp1 = Known.isNegative();
561 bool isKnownNegativeOp0 = Known2.isNegative();
562 // The product of two numbers with the same sign is non-negative.
563 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
564 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
565 if (!isKnownNonNegative && NUW) {
566 // mul nuw nsw with a factor > 1 is non-negative.
567 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
568 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
569 KnownBits::sgt(Known2, One).value_or(false);
570 }
571
572 // The product of a negative number and a non-negative number is either
573 // negative or zero.
576 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
577 Known2.isNonZero()) ||
578 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
579 }
580 }
581
582 bool SelfMultiply = Op0 == Op1;
583 if (SelfMultiply)
584 SelfMultiply &=
585 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
586 Known = KnownBits::mul(Known, Known2, SelfMultiply);
587
588 if (SelfMultiply) {
589 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
590 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
591 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
592
593 if (OutValidBits < TyBits) {
594 APInt KnownZeroMask =
595 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
596 Known.Zero |= KnownZeroMask;
597 }
598 }
599
600 // Only make use of no-wrap flags if we failed to compute the sign bit
601 // directly. This matters if the multiplication always overflows, in
602 // which case we prefer to follow the result of the direct computation,
603 // though as the program is invoking undefined behaviour we can choose
604 // whatever we like here.
605 if (isKnownNonNegative && !Known.isNegative())
606 Known.makeNonNegative();
607 else if (isKnownNegative && !Known.isNonNegative())
608 Known.makeNegative();
609}
610
612 KnownBits &Known) {
613 unsigned BitWidth = Known.getBitWidth();
614 unsigned NumRanges = Ranges.getNumOperands() / 2;
615 assert(NumRanges >= 1);
616
617 Known.setAllConflict();
618
619 for (unsigned i = 0; i < NumRanges; ++i) {
621 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
624 ConstantRange Range(Lower->getValue(), Upper->getValue());
625 // BitWidth must equal the Ranges BitWidth for the correct number of high
626 // bits to be set.
627 assert(BitWidth == Range.getBitWidth() &&
628 "Known bit width must match range bit width!");
629
630 // The first CommonPrefixBits of all values in Range are equal.
631 unsigned CommonPrefixBits =
632 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
633 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
634 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
635 Known.One &= UnsignedMax & Mask;
636 Known.Zero &= ~UnsignedMax & Mask;
637 }
638}
639
640static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
641 // The instruction defining an assumption's condition itself is always
642 // considered ephemeral to that assumption (even if it has other
643 // non-ephemeral users). See r246696's test case for an example.
644 if (is_contained(I->operands(), E))
645 return true;
646
647 const auto *EI = dyn_cast<Instruction>(E);
648 if (!EI)
649 return false;
650
651 if (EI == I)
652 return true;
653
656 Visited.insert(EI);
657 WorkList.push_back(EI);
658 bool ReachesI = false;
659 while (!WorkList.empty()) {
660 const Instruction *V = WorkList.pop_back_val();
661 for (const User *U : V->users()) {
662 const auto *UI = cast<Instruction>(U);
663 if (UI == I) {
664 ReachesI = true;
665 continue;
666 }
667 if (UI->mayHaveSideEffects() || UI->isTerminator())
668 return false;
669 if (Visited.insert(UI).second)
670 WorkList.push_back(UI);
671 }
672 }
673 return ReachesI;
674}
675
676// Is this an intrinsic that cannot be speculated but also cannot trap?
678 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
679 return CI->isAssumeLikeIntrinsic();
680
681 return false;
682}
683
685 const Instruction *CxtI,
686 const DominatorTree *DT,
687 bool AllowEphemerals) {
688 // There are two restrictions on the use of an assume:
689 // 1. The assume must dominate the context (or the control flow must
690 // reach the assume whenever it reaches the context).
691 // 2. The context must not be in the assume's set of ephemeral values
692 // (otherwise we will use the assume to prove that the condition
693 // feeding the assume is trivially true, thus causing the removal of
694 // the assume).
695
696 if (Inv->getParent() == CxtI->getParent()) {
697 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
698 // in the BB.
699 if (Inv->comesBefore(CxtI))
700 return true;
701
702 // Don't let an assume affect itself - this would cause the problems
703 // `isEphemeralValueOf` is trying to prevent, and it would also make
704 // the loop below go out of bounds.
705 if (!AllowEphemerals && Inv == CxtI)
706 return false;
707
708 // The context comes first, but they're both in the same block.
709 // Make sure there is nothing in between that might interrupt
710 // the control flow, not even CxtI itself.
711 // We limit the scan distance between the assume and its context instruction
712 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
713 // it can be adjusted if needed (could be turned into a cl::opt).
714 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
716 return false;
717
718 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
719 }
720
721 // Inv and CxtI are in different blocks.
722 if (DT) {
723 if (DT->dominates(Inv, CxtI))
724 return true;
725 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
726 Inv->getParent()->isEntryBlock()) {
727 // We don't have a DT, but this trivially dominates.
728 return true;
729 }
730
731 return false;
732}
733
735 const Instruction *CtxI) {
736 // Helper to check if there are any calls in the range that may free memory.
737 unsigned NumChecked = 0;
738 auto hasNoFreeInRange = [&NumChecked](auto Range) {
739 for (const Instruction &I : Range) {
740 if (NumChecked++ > MaxInstrsToCheckForFree)
741 return false;
742
743 if (auto *CB = dyn_cast<CallBase>(&I)) {
744 if (!CB->hasFnAttr(Attribute::NoFree))
745 return false;
746 } else if (I.maySynchronize())
747 return false;
748 }
749 return true;
750 };
751
752 const BasicBlock *CtxBB = CtxI->getParent();
753 const BasicBlock *AssumeBB = Assume->getParent();
754 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
755 if (CtxBB == AssumeBB) {
756 // Same block case: check that Assume comes before CtxI.
757 if (Assume != CtxI && !Assume->comesBefore(CtxI))
758 return false;
759 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
760 }
761
762 // Handle chain of single-predecessor blocks.
763 const BasicBlock *CurBB = CtxBB;
764 while (true) {
765 if (CurBB == AssumeBB)
766 return hasNoFreeInRange(
767 make_range(Assume->getIterator(), AssumeBB->end()));
768
769 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
770 if (!PredBB)
771 return false;
772
773 if (!hasNoFreeInRange(make_range(CurBB->begin(),
774 CurBB == CtxBB ? CtxIter : CurBB->end())))
775 return false;
776 CurBB = PredBB;
777 }
778}
779
780// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
781// we still have enough information about `RHS` to conclude non-zero. For
782// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
783// so the extra compile time may not be worth it, but possibly a second API
784// should be created for use outside of loops.
785static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
786 // v u> y implies v != 0.
787 if (Pred == ICmpInst::ICMP_UGT)
788 return true;
789
790 // Special-case v != 0 to also handle v != null.
791 if (Pred == ICmpInst::ICMP_NE)
792 return match(RHS, m_Zero());
793
794 // All other predicates - rely on generic ConstantRange handling.
795 const APInt *C;
796 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
797 if (match(RHS, m_APInt(C))) {
799 return !TrueValues.contains(Zero);
800 }
801
803 if (VC == nullptr)
804 return false;
805
806 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
807 ++ElemIdx) {
809 Pred, VC->getElementAsAPInt(ElemIdx));
810 if (TrueValues.contains(Zero))
811 return false;
812 }
813 return true;
814}
815
816static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
817 Value *&ValOut, Instruction *&CtxIOut,
818 const PHINode **PhiOut = nullptr) {
819 ValOut = U->get();
820 if (ValOut == PHI)
821 return;
822 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
823 if (PhiOut)
824 *PhiOut = PHI;
825 Value *V;
826 // If the Use is a select of this phi, compute analysis on other arm to break
827 // recursion.
828 // TODO: Min/Max
829 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
830 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
831 ValOut = V;
832
833 // Same for select, if this phi is 2-operand phi, compute analysis on other
834 // incoming value to break recursion.
835 // TODO: We could handle any number of incoming edges as long as we only have
836 // two unique values.
837 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
838 IncPhi && IncPhi->getNumIncomingValues() == 2) {
839 for (int Idx = 0; Idx < 2; ++Idx) {
840 if (IncPhi->getIncomingValue(Idx) == PHI) {
841 ValOut = IncPhi->getIncomingValue(1 - Idx);
842 if (PhiOut)
843 *PhiOut = IncPhi;
844 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
845 break;
846 }
847 }
848 }
849}
850
851static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
852 // Use of assumptions is context-sensitive. If we don't have a context, we
853 // cannot use them!
854 if (!Q.AC || !Q.CxtI)
855 return false;
856
857 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
858 if (!Elem.Assume)
859 continue;
860
861 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
862 assert(I->getFunction() == Q.CxtI->getFunction() &&
863 "Got assumption for the wrong function!");
864
865 if (Elem.Index != AssumptionCache::ExprResultIdx) {
867 I->getOperandBundleAt(Elem.Index)) &&
869 return true;
870 continue;
871 }
872
873 // Warning: This loop can end up being somewhat performance sensitive.
874 // We're running this loop for once for each value queried resulting in a
875 // runtime of ~O(#assumes * #values).
876
877 Value *RHS;
878 CmpPredicate Pred;
879 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
880 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
881 continue;
882
884 return true;
885 }
886
887 return false;
888}
889
892 const SimplifyQuery &Q) {
893 if (RHS->getType()->isPointerTy()) {
894 // Handle comparison of pointer to null explicitly, as it will not be
895 // covered by the m_APInt() logic below.
896 if (LHS == V && match(RHS, m_Zero())) {
897 switch (Pred) {
899 Known.setAllZero();
900 break;
903 Known.makeNonNegative();
904 break;
906 Known.makeNegative();
907 break;
908 default:
909 break;
910 }
911 }
912 return;
913 }
914
915 unsigned BitWidth = Known.getBitWidth();
916 auto m_V =
918
919 Value *Y;
920 const APInt *Mask, *C;
921 if (!match(RHS, m_APInt(C)))
922 return;
923
924 uint64_t ShAmt;
925 switch (Pred) {
927 // assume(V = C)
928 if (match(LHS, m_V)) {
929 Known = Known.unionWith(KnownBits::makeConstant(*C));
930 // assume(V & Mask = C)
931 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
932 // For one bits in Mask, we can propagate bits from C to V.
933 Known.One |= *C;
934 if (match(Y, m_APInt(Mask)))
935 Known.Zero |= ~*C & *Mask;
936 // assume(V | Mask = C)
937 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
938 // For zero bits in Mask, we can propagate bits from C to V.
939 Known.Zero |= ~*C;
940 if (match(Y, m_APInt(Mask)))
941 Known.One |= *C & ~*Mask;
942 // assume(V << ShAmt = C)
943 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
944 ShAmt < BitWidth) {
945 // For those bits in C that are known, we can propagate them to known
946 // bits in V shifted to the right by ShAmt.
948 RHSKnown >>= ShAmt;
949 Known = Known.unionWith(RHSKnown);
950 // assume(V >> ShAmt = C)
951 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
952 ShAmt < BitWidth) {
953 // For those bits in RHS that are known, we can propagate them to known
954 // bits in V shifted to the right by C.
956 RHSKnown <<= ShAmt;
957 Known = Known.unionWith(RHSKnown);
958 }
959 break;
960 case ICmpInst::ICMP_NE: {
961 // assume (V & B != 0) where B is a power of 2
962 const APInt *BPow2;
963 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
964 Known.One |= *BPow2;
965 break;
966 }
967 default: {
968 const APInt *Offset = nullptr;
969 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
971 if (Offset)
972 LHSRange = LHSRange.sub(*Offset);
973 Known = Known.unionWith(LHSRange.toKnownBits());
974 }
975 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
976 // X & Y u> C -> X u> C && Y u> C
977 // X nuw- Y u> C -> X u> C
978 if (match(LHS, m_c_And(m_V, m_Value())) ||
979 match(LHS, m_NUWSub(m_V, m_Value())))
980 Known.One.setHighBits(
981 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
982 }
983 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
984 // X | Y u< C -> X u< C && Y u< C
985 // X nuw+ Y u< C -> X u< C && Y u< C
986 if (match(LHS, m_c_Or(m_V, m_Value())) ||
987 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
988 Known.Zero.setHighBits(
989 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
990 }
991 }
992 } break;
993 }
994}
995
996static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
998 const SimplifyQuery &SQ, bool Invert) {
1000 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1001 Value *LHS = Cmp->getOperand(0);
1002 Value *RHS = Cmp->getOperand(1);
1003
1004 // Handle icmp pred (trunc V), C
1005 if (match(LHS, m_Trunc(m_Specific(V)))) {
1006 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1007 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1009 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1010 else
1011 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1012 return;
1013 }
1014
1015 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1016}
1017
1019 KnownBits &Known, const SimplifyQuery &SQ,
1020 bool Invert, unsigned Depth) {
1021 Value *A, *B;
1024 KnownBits Known2(Known.getBitWidth());
1025 KnownBits Known3(Known.getBitWidth());
1026 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1027 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1028 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1030 Known2 = Known2.unionWith(Known3);
1031 else
1032 Known2 = Known2.intersectWith(Known3);
1033 Known = Known.unionWith(Known2);
1034 return;
1035 }
1036
1037 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1038 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1039 return;
1040 }
1041
1042 if (match(Cond, m_Trunc(m_Specific(V)))) {
1043 KnownBits DstKnown(1);
1044 if (Invert) {
1045 DstKnown.setAllZero();
1046 } else {
1047 DstKnown.setAllOnes();
1048 }
1050 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1051 return;
1052 }
1053 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1054 return;
1055 }
1056
1058 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1059}
1060
1062 const SimplifyQuery &Q, unsigned Depth) {
1063 // Handle injected condition.
1064 if (Q.CC && Q.CC->AffectedValues.contains(V))
1066
1067 if (!Q.CxtI)
1068 return;
1069
1070 if (Q.DC && Q.DT) {
1071 // Handle dominating conditions.
1072 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1073 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1074 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1075 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1076 /*Invert*/ false, Depth);
1077
1078 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1079 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1080 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1081 /*Invert*/ true, Depth);
1082 }
1083
1084 if (Known.hasConflict())
1085 Known.resetAll();
1086 }
1087
1088 if (!Q.AC)
1089 return;
1090
1091 unsigned BitWidth = Known.getBitWidth();
1092
1093 // Note that the patterns below need to be kept in sync with the code
1094 // in AssumptionCache::updateAffectedValues.
1095
1096 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1097 if (!Elem.Assume)
1098 continue;
1099
1100 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1101 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1102 "Got assumption for the wrong function!");
1103
1104 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1105 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1106 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1107 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1108 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1110 Known.Zero |= (*Alignment - 1) & ~*Offset;
1111 Known.One |= (*Alignment - 1) & *Offset;
1112 }
1113 }
1114 continue;
1115 }
1116
1117 // Warning: This loop can end up being somewhat performance sensitive.
1118 // We're running this loop for once for each value queried resulting in a
1119 // runtime of ~O(#assumes * #values).
1120
1121 Value *Arg = I->getArgOperand(0);
1122
1123 if (Arg == V && isValidAssumeForContext(I, Q)) {
1124 assert(BitWidth == 1 && "assume operand is not i1?");
1125 (void)BitWidth;
1126 Known.setAllOnes();
1127 return;
1128 }
1129 if (match(Arg, m_Not(m_Specific(V))) &&
1131 assert(BitWidth == 1 && "assume operand is not i1?");
1132 (void)BitWidth;
1133 Known.setAllZero();
1134 return;
1135 }
1136 auto *Trunc = dyn_cast<TruncInst>(Arg);
1137 if (Trunc && Trunc->getOperand(0) == V &&
1139 if (Trunc->hasNoUnsignedWrap()) {
1141 return;
1142 }
1143 Known.One.setBit(0);
1144 return;
1145 }
1146
1147 // The remaining tests are all recursive, so bail out if we hit the limit.
1149 continue;
1150
1151 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1152 if (!Cmp)
1153 continue;
1154
1155 if (!isValidAssumeForContext(I, Q))
1156 continue;
1157
1158 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1159 }
1160
1161 // Conflicting assumption: Undefined behavior will occur on this execution
1162 // path.
1163 if (Known.hasConflict())
1164 Known.resetAll();
1165}
1166
1167/// Compute known bits from a shift operator, including those with a
1168/// non-constant shift amount. Known is the output of this function. Known2 is a
1169/// pre-allocated temporary with the same bit width as Known and on return
1170/// contains the known bit of the shift value source. KF is an
1171/// operator-specific function that, given the known-bits and a shift amount,
1172/// compute the implied known-bits of the shift operator's result respectively
1173/// for that shift amount. The results from calling KF are conservatively
1174/// combined for all permitted shift amounts.
1176 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1177 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1178 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1179 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1180 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1181 // To limit compile-time impact, only query isKnownNonZero() if we know at
1182 // least something about the shift amount.
1183 bool ShAmtNonZero =
1184 Known.isNonZero() ||
1185 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1186 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1187 Known = KF(Known2, Known, ShAmtNonZero);
1188}
1189
1190static KnownBits
1191getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1192 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1193 const SimplifyQuery &Q, unsigned Depth) {
1194 unsigned BitWidth = KnownLHS.getBitWidth();
1195 KnownBits KnownOut(BitWidth);
1196 bool IsAnd = false;
1197 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1198 Value *X = nullptr, *Y = nullptr;
1199
1200 switch (I->getOpcode()) {
1201 case Instruction::And:
1202 KnownOut = KnownLHS & KnownRHS;
1203 IsAnd = true;
1204 // and(x, -x) is common idioms that will clear all but lowest set
1205 // bit. If we have a single known bit in x, we can clear all bits
1206 // above it.
1207 // TODO: instcombine often reassociates independent `and` which can hide
1208 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1209 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1210 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1211 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1212 KnownOut = KnownLHS.blsi();
1213 else
1214 KnownOut = KnownRHS.blsi();
1215 }
1216 break;
1217 case Instruction::Or:
1218 KnownOut = KnownLHS | KnownRHS;
1219 break;
1220 case Instruction::Xor:
1221 KnownOut = KnownLHS ^ KnownRHS;
1222 // xor(x, x-1) is common idioms that will clear all but lowest set
1223 // bit. If we have a single known bit in x, we can clear all bits
1224 // above it.
1225 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1226 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1227 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1228 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1229 if (HasKnownOne &&
1231 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1232 KnownOut = XBits.blsmsk();
1233 }
1234 break;
1235 default:
1236 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1237 }
1238
1239 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1240 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1241 // here we handle the more general case of adding any odd number by
1242 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1243 // TODO: This could be generalized to clearing any bit set in y where the
1244 // following bit is known to be unset in y.
1245 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1249 KnownBits KnownY(BitWidth);
1250 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1251 if (KnownY.countMinTrailingOnes() > 0) {
1252 if (IsAnd)
1253 KnownOut.Zero.setBit(0);
1254 else
1255 KnownOut.One.setBit(0);
1256 }
1257 }
1258 return KnownOut;
1259}
1260
1262 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1263 unsigned Depth,
1264 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1265 KnownBitsFunc) {
1266 APInt DemandedEltsLHS, DemandedEltsRHS;
1268 DemandedElts, DemandedEltsLHS,
1269 DemandedEltsRHS);
1270
1271 const auto ComputeForSingleOpFunc =
1272 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1273 return KnownBitsFunc(
1274 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1275 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1276 };
1277
1278 if (DemandedEltsRHS.isZero())
1279 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1280 if (DemandedEltsLHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1282
1283 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1284 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1285}
1286
1287// Public so this can be used in `SimplifyDemandedUseBits`.
1289 const KnownBits &KnownLHS,
1290 const KnownBits &KnownRHS,
1291 const SimplifyQuery &SQ,
1292 unsigned Depth) {
1293 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1294 APInt DemandedElts =
1295 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1296
1297 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1298 Depth);
1299}
1300
1302 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1303 // Without vscale_range, we only know that vscale is non-zero.
1304 if (!Attr.isValid())
1306
1307 unsigned AttrMin = Attr.getVScaleRangeMin();
1308 // Minimum is larger than vscale width, result is always poison.
1309 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1310 return ConstantRange::getEmpty(BitWidth);
1311
1312 APInt Min(BitWidth, AttrMin);
1313 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1314 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1316
1317 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1318}
1319
1321 Value *Arm, bool Invert,
1322 const SimplifyQuery &Q, unsigned Depth) {
1323 // If we have a constant arm, we are done.
1324 if (Known.isConstant())
1325 return;
1326
1327 // See what condition implies about the bits of the select arm.
1328 KnownBits CondRes(Known.getBitWidth());
1329 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1330 // If we don't get any information from the condition, no reason to
1331 // proceed.
1332 if (CondRes.isUnknown())
1333 return;
1334
1335 // We can have conflict if the condition is dead. I.e if we have
1336 // (x | 64) < 32 ? (x | 64) : y
1337 // we will have conflict at bit 6 from the condition/the `or`.
1338 // In that case just return. Its not particularly important
1339 // what we do, as this select is going to be simplified soon.
1340 CondRes = CondRes.unionWith(Known);
1341 if (CondRes.hasConflict())
1342 return;
1343
1344 // Finally make sure the information we found is valid. This is relatively
1345 // expensive so it's left for the very end.
1346 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1347 return;
1348
1349 // Finally, we know we get information from the condition and its valid,
1350 // so return it.
1351 Known = std::move(CondRes);
1352}
1353
1354// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1355// Returns the input and lower/upper bounds.
1356static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1357 const APInt *&CLow, const APInt *&CHigh) {
1359 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1360 "Input should be a Select!");
1361
1362 const Value *LHS = nullptr, *RHS = nullptr;
1364 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1365 return false;
1366
1367 if (!match(RHS, m_APInt(CLow)))
1368 return false;
1369
1370 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1372 if (getInverseMinMaxFlavor(SPF) != SPF2)
1373 return false;
1374
1375 if (!match(RHS2, m_APInt(CHigh)))
1376 return false;
1377
1378 if (SPF == SPF_SMIN)
1379 std::swap(CLow, CHigh);
1380
1381 In = LHS2;
1382 return CLow->sle(*CHigh);
1383}
1384
1386 const APInt *&CLow,
1387 const APInt *&CHigh) {
1388 assert((II->getIntrinsicID() == Intrinsic::smin ||
1389 II->getIntrinsicID() == Intrinsic::smax) &&
1390 "Must be smin/smax");
1391
1392 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1393 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1394 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1395 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1396 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1397 return false;
1398
1399 if (II->getIntrinsicID() == Intrinsic::smin)
1400 std::swap(CLow, CHigh);
1401 return CLow->sle(*CHigh);
1402}
1403
1405 KnownBits &Known) {
1406 const APInt *CLow, *CHigh;
1407 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1408 Known = Known.unionWith(
1409 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1410}
1411
1413 const APInt &DemandedElts,
1415 const SimplifyQuery &Q,
1416 unsigned Depth) {
1417 unsigned BitWidth = Known.getBitWidth();
1418
1419 KnownBits Known2(BitWidth);
1420 switch (I->getOpcode()) {
1421 default: break;
1422 case Instruction::Load:
1423 if (MDNode *MD =
1424 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1426 break;
1427 case Instruction::And:
1428 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1429 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1430
1431 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1432 break;
1433 case Instruction::Or:
1434 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1435 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1436
1437 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1438 break;
1439 case Instruction::Xor:
1440 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1441 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1442
1443 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1444 break;
1445 case Instruction::Mul: {
1448 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1449 DemandedElts, Known, Known2, Q, Depth);
1450 break;
1451 }
1452 case Instruction::UDiv: {
1453 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1454 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1455 Known =
1457 break;
1458 }
1459 case Instruction::SDiv: {
1460 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1461 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1462 Known =
1464 break;
1465 }
1466 case Instruction::Select: {
1467 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1468 KnownBits Res(Known.getBitWidth());
1469 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1470 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1471 return Res;
1472 };
1473 // Only known if known in both the LHS and RHS.
1474 Known =
1475 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1476 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1477 break;
1478 }
1479 case Instruction::FPTrunc:
1480 case Instruction::FPExt:
1481 case Instruction::FPToUI:
1482 case Instruction::FPToSI:
1483 case Instruction::SIToFP:
1484 case Instruction::UIToFP:
1485 break; // Can't work with floating point.
1486 case Instruction::PtrToInt:
1487 case Instruction::PtrToAddr:
1488 case Instruction::IntToPtr:
1489 // Fall through and handle them the same as zext/trunc.
1490 [[fallthrough]];
1491 case Instruction::ZExt:
1492 case Instruction::Trunc: {
1493 Type *SrcTy = I->getOperand(0)->getType();
1494
1495 unsigned SrcBitWidth;
1496 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1497 // which fall through here.
1498 Type *ScalarTy = SrcTy->getScalarType();
1499 SrcBitWidth = ScalarTy->isPointerTy() ?
1500 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1501 Q.DL.getTypeSizeInBits(ScalarTy);
1502
1503 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1504 Known = Known.anyextOrTrunc(SrcBitWidth);
1505 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1506 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1507 Inst && Inst->hasNonNeg() && !Known.isNegative())
1508 Known.makeNonNegative();
1509 Known = Known.zextOrTrunc(BitWidth);
1510 break;
1511 }
1512 case Instruction::BitCast: {
1513 Type *SrcTy = I->getOperand(0)->getType();
1514 if (SrcTy->isIntOrPtrTy() &&
1515 // TODO: For now, not handling conversions like:
1516 // (bitcast i64 %x to <2 x i32>)
1517 !I->getType()->isVectorTy()) {
1518 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1519 break;
1520 }
1521
1522 const Value *V;
1523 // Handle bitcast from floating point to integer.
1524 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1525 V->getType()->isFPOrFPVectorTy()) {
1526 Type *FPType = V->getType()->getScalarType();
1527 KnownFPClass Result =
1528 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1529 FPClassTest FPClasses = Result.KnownFPClasses;
1530
1531 // TODO: Treat it as zero/poison if the use of I is unreachable.
1532 if (FPClasses == fcNone)
1533 break;
1534
1535 if (Result.isKnownNever(fcNormal | fcSubnormal | fcNan)) {
1536 Known.setAllConflict();
1537
1538 if (FPClasses & fcInf)
1539 Known = Known.intersectWith(KnownBits::makeConstant(
1540 APFloat::getInf(FPType->getFltSemantics()).bitcastToAPInt()));
1541
1542 if (FPClasses & fcZero)
1543 Known = Known.intersectWith(KnownBits::makeConstant(
1544 APInt::getZero(FPType->getScalarSizeInBits())));
1545
1546 Known.Zero.clearSignBit();
1547 Known.One.clearSignBit();
1548 }
1549
1550 if (Result.SignBit) {
1551 if (*Result.SignBit)
1552 Known.makeNegative();
1553 else
1554 Known.makeNonNegative();
1555 }
1556
1557 break;
1558 }
1559
1560 // Handle cast from vector integer type to scalar or vector integer.
1561 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1562 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1563 !I->getType()->isIntOrIntVectorTy() ||
1564 isa<ScalableVectorType>(I->getType()))
1565 break;
1566
1567 unsigned NumElts = DemandedElts.getBitWidth();
1568 bool IsLE = Q.DL.isLittleEndian();
1569 // Look through a cast from narrow vector elements to wider type.
1570 // Examples: v4i32 -> v2i64, v3i8 -> v24
1571 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1572 if (BitWidth % SubBitWidth == 0) {
1573 // Known bits are automatically intersected across demanded elements of a
1574 // vector. So for example, if a bit is computed as known zero, it must be
1575 // zero across all demanded elements of the vector.
1576 //
1577 // For this bitcast, each demanded element of the output is sub-divided
1578 // across a set of smaller vector elements in the source vector. To get
1579 // the known bits for an entire element of the output, compute the known
1580 // bits for each sub-element sequentially. This is done by shifting the
1581 // one-set-bit demanded elements parameter across the sub-elements for
1582 // consecutive calls to computeKnownBits. We are using the demanded
1583 // elements parameter as a mask operator.
1584 //
1585 // The known bits of each sub-element are then inserted into place
1586 // (dependent on endian) to form the full result of known bits.
1587 unsigned SubScale = BitWidth / SubBitWidth;
1588 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1589 for (unsigned i = 0; i != NumElts; ++i) {
1590 if (DemandedElts[i])
1591 SubDemandedElts.setBit(i * SubScale);
1592 }
1593
1594 KnownBits KnownSrc(SubBitWidth);
1595 for (unsigned i = 0; i != SubScale; ++i) {
1596 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1597 Depth + 1);
1598 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1599 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1600 }
1601 }
1602 // Look through a cast from wider vector elements to narrow type.
1603 // Examples: v2i64 -> v4i32
1604 if (SubBitWidth % BitWidth == 0) {
1605 unsigned SubScale = SubBitWidth / BitWidth;
1606 KnownBits KnownSrc(SubBitWidth);
1607 APInt SubDemandedElts =
1608 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1609 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1610 Depth + 1);
1611
1612 Known.setAllConflict();
1613 for (unsigned i = 0; i != NumElts; ++i) {
1614 if (DemandedElts[i]) {
1615 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1616 unsigned Offset = (Shifts % SubScale) * BitWidth;
1617 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1618 if (Known.isUnknown())
1619 break;
1620 }
1621 }
1622 }
1623 break;
1624 }
1625 case Instruction::SExt: {
1626 // Compute the bits in the result that are not present in the input.
1627 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1628
1629 Known = Known.trunc(SrcBitWidth);
1630 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1631 // If the sign bit of the input is known set or clear, then we know the
1632 // top bits of the result.
1633 Known = Known.sext(BitWidth);
1634 break;
1635 }
1636 case Instruction::Shl: {
1639 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1640 bool ShAmtNonZero) {
1641 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1642 };
1643 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1644 KF);
1645 // Trailing zeros of a right-shifted constant never decrease.
1646 const APInt *C;
1647 if (match(I->getOperand(0), m_APInt(C)))
1648 Known.Zero.setLowBits(C->countr_zero());
1649
1650 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1651 // lands at bit Y, when BitWidth is a power of 2.
1652 const APInt *YC;
1653 Value *X = I->getOperand(0);
1654 if (isPowerOf2_32(BitWidth) &&
1655 match(I->getOperand(1),
1657 m_SpecificInt(BitWidth - 1)))) &&
1658 YC->ult(BitWidth - 1)) {
1659 unsigned Y = YC->getZExtValue();
1660 Known.One.setBit(Y);
1661 Known.Zero.setBitsFrom(Y + 1);
1662 }
1663 break;
1664 }
1665 case Instruction::LShr: {
1666 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1667 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1668 bool ShAmtNonZero) {
1669 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1670 };
1671 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1672 KF);
1673 // Leading zeros of a left-shifted constant never decrease.
1674 const APInt *C;
1675 if (match(I->getOperand(0), m_APInt(C)))
1676 Known.Zero.setHighBits(C->countl_zero());
1677 break;
1678 }
1679 case Instruction::AShr: {
1680 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1681 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1682 bool ShAmtNonZero) {
1683 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1684 };
1685 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1686 KF);
1687 break;
1688 }
1689 case Instruction::Sub: {
1692 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1693 DemandedElts, Known, Known2, Q, Depth);
1694 break;
1695 }
1696 case Instruction::Add: {
1699 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1700 DemandedElts, Known, Known2, Q, Depth);
1701 break;
1702 }
1703 case Instruction::SRem:
1704 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1705 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1706 Known = KnownBits::srem(Known, Known2);
1707 break;
1708
1709 case Instruction::URem:
1710 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1711 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1712 Known = KnownBits::urem(Known, Known2);
1713 break;
1714 case Instruction::Alloca:
1715 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1716 break;
1717 case Instruction::GetElementPtr: {
1718 // Analyze all of the subscripts of this getelementptr instruction
1719 // to determine if we can prove known low zero bits.
1720 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1721 // Accumulate the constant indices in a separate variable
1722 // to minimize the number of calls to computeForAddSub.
1723 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1724 APInt AccConstIndices(IndexWidth, 0);
1725
1726 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1727 if (IndexWidth == BitWidth) {
1728 // Note that inbounds does *not* guarantee nsw for the addition, as only
1729 // the offset is signed, while the base address is unsigned.
1730 Known = KnownBits::add(Known, IndexBits);
1731 } else {
1732 // If the index width is smaller than the pointer width, only add the
1733 // value to the low bits.
1734 assert(IndexWidth < BitWidth &&
1735 "Index width can't be larger than pointer width");
1736 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1737 }
1738 };
1739
1741 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1742 // TrailZ can only become smaller, short-circuit if we hit zero.
1743 if (Known.isUnknown())
1744 break;
1745
1746 Value *Index = I->getOperand(i);
1747
1748 // Handle case when index is zero.
1749 Constant *CIndex = dyn_cast<Constant>(Index);
1750 if (CIndex && CIndex->isNullValue())
1751 continue;
1752
1753 if (StructType *STy = GTI.getStructTypeOrNull()) {
1754 // Handle struct member offset arithmetic.
1755
1756 assert(CIndex &&
1757 "Access to structure field must be known at compile time");
1758
1759 if (CIndex->getType()->isVectorTy())
1760 Index = CIndex->getSplatValue();
1761
1762 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1763 const StructLayout *SL = Q.DL.getStructLayout(STy);
1764 uint64_t Offset = SL->getElementOffset(Idx);
1765 AccConstIndices += Offset;
1766 continue;
1767 }
1768
1769 // Handle array index arithmetic.
1770 Type *IndexedTy = GTI.getIndexedType();
1771 if (!IndexedTy->isSized()) {
1772 Known.resetAll();
1773 break;
1774 }
1775
1776 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1777 uint64_t StrideInBytes = Stride.getKnownMinValue();
1778 if (!Stride.isScalable()) {
1779 // Fast path for constant offset.
1780 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1781 AccConstIndices +=
1782 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1783 continue;
1784 }
1785 }
1786
1787 KnownBits IndexBits =
1788 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1789 KnownBits ScalingFactor(IndexWidth);
1790 // Multiply by current sizeof type.
1791 // &A[i] == A + i * sizeof(*A[i]).
1792 if (Stride.isScalable()) {
1793 // For scalable types the only thing we know about sizeof is
1794 // that this is a multiple of the minimum size.
1795 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1796 } else {
1797 ScalingFactor =
1798 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1799 }
1800 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1801 }
1802 if (!Known.isUnknown() && !AccConstIndices.isZero())
1803 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1804 break;
1805 }
1806 case Instruction::PHI: {
1807 const PHINode *P = cast<PHINode>(I);
1808 BinaryOperator *BO = nullptr;
1809 Value *R = nullptr, *L = nullptr;
1810 if (matchSimpleRecurrence(P, BO, R, L)) {
1811 // Handle the case of a simple two-predecessor recurrence PHI.
1812 // There's a lot more that could theoretically be done here, but
1813 // this is sufficient to catch some interesting cases.
1814 unsigned Opcode = BO->getOpcode();
1815
1816 switch (Opcode) {
1817 // If this is a shift recurrence, we know the bits being shifted in. We
1818 // can combine that with information about the start value of the
1819 // recurrence to conclude facts about the result. If this is a udiv
1820 // recurrence, we know that the result can never exceed either the
1821 // numerator or the start value, whichever is greater.
1822 case Instruction::LShr:
1823 case Instruction::AShr:
1824 case Instruction::Shl:
1825 case Instruction::UDiv:
1826 if (BO->getOperand(0) != I)
1827 break;
1828 [[fallthrough]];
1829
1830 // For a urem recurrence, the result can never exceed the start value. The
1831 // phi could either be the numerator or the denominator.
1832 case Instruction::URem: {
1833 // We have matched a recurrence of the form:
1834 // %iv = [R, %entry], [%iv.next, %backedge]
1835 // %iv.next = shift_op %iv, L
1836
1837 // Recurse with the phi context to avoid concern about whether facts
1838 // inferred hold at original context instruction. TODO: It may be
1839 // correct to use the original context. IF warranted, explore and
1840 // add sufficient tests to cover.
1842 RecQ.CxtI = P;
1843 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1844 switch (Opcode) {
1845 case Instruction::Shl:
1846 // A shl recurrence will only increase the tailing zeros
1847 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1848 break;
1849 case Instruction::LShr:
1850 case Instruction::UDiv:
1851 case Instruction::URem:
1852 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1853 // the start value.
1854 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1855 break;
1856 case Instruction::AShr:
1857 // An ashr recurrence will extend the initial sign bit
1858 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1859 Known.One.setHighBits(Known2.countMinLeadingOnes());
1860 break;
1861 }
1862 break;
1863 }
1864
1865 // Check for operations that have the property that if
1866 // both their operands have low zero bits, the result
1867 // will have low zero bits.
1868 case Instruction::Add:
1869 case Instruction::Sub:
1870 case Instruction::And:
1871 case Instruction::Or:
1872 case Instruction::Mul: {
1873 // Change the context instruction to the "edge" that flows into the
1874 // phi. This is important because that is where the value is actually
1875 // "evaluated" even though it is used later somewhere else. (see also
1876 // D69571).
1878
1879 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1880 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1881 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1882
1883 // Ok, we have a PHI of the form L op= R. Check for low
1884 // zero bits.
1885 RecQ.CxtI = RInst;
1886 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1887
1888 // We need to take the minimum number of known bits
1889 KnownBits Known3(BitWidth);
1890 RecQ.CxtI = LInst;
1891 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1892
1893 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1894 Known3.countMinTrailingZeros()));
1895
1896 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1897 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1898 break;
1899
1900 switch (Opcode) {
1901 // If initial value of recurrence is nonnegative, and we are adding
1902 // a nonnegative number with nsw, the result can only be nonnegative
1903 // or poison value regardless of the number of times we execute the
1904 // add in phi recurrence. If initial value is negative and we are
1905 // adding a negative number with nsw, the result can only be
1906 // negative or poison value. Similar arguments apply to sub and mul.
1907 //
1908 // (add non-negative, non-negative) --> non-negative
1909 // (add negative, negative) --> negative
1910 case Instruction::Add: {
1911 if (Known2.isNonNegative() && Known3.isNonNegative())
1912 Known.makeNonNegative();
1913 else if (Known2.isNegative() && Known3.isNegative())
1914 Known.makeNegative();
1915 break;
1916 }
1917
1918 // (sub nsw non-negative, negative) --> non-negative
1919 // (sub nsw negative, non-negative) --> negative
1920 case Instruction::Sub: {
1921 if (BO->getOperand(0) != I)
1922 break;
1923 if (Known2.isNonNegative() && Known3.isNegative())
1924 Known.makeNonNegative();
1925 else if (Known2.isNegative() && Known3.isNonNegative())
1926 Known.makeNegative();
1927 break;
1928 }
1929
1930 // (mul nsw non-negative, non-negative) --> non-negative
1931 case Instruction::Mul:
1932 if (Known2.isNonNegative() && Known3.isNonNegative())
1933 Known.makeNonNegative();
1934 break;
1935
1936 default:
1937 break;
1938 }
1939 break;
1940 }
1941
1942 default:
1943 break;
1944 }
1945 }
1946
1947 // Unreachable blocks may have zero-operand PHI nodes.
1948 if (P->getNumIncomingValues() == 0)
1949 break;
1950
1951 // Otherwise take the unions of the known bit sets of the operands,
1952 // taking conservative care to avoid excessive recursion.
1953 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1954 // Skip if every incoming value references to ourself.
1955 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1956 break;
1957
1958 Known.setAllConflict();
1959 for (const Use &U : P->operands()) {
1960 Value *IncValue;
1961 const PHINode *CxtPhi;
1962 Instruction *CxtI;
1963 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1964 // Skip direct self references.
1965 if (IncValue == P)
1966 continue;
1967
1968 // Change the context instruction to the "edge" that flows into the
1969 // phi. This is important because that is where the value is actually
1970 // "evaluated" even though it is used later somewhere else. (see also
1971 // D69571).
1973
1974 Known2 = KnownBits(BitWidth);
1975
1976 // Recurse, but cap the recursion to one level, because we don't
1977 // want to waste time spinning around in loops.
1978 // TODO: See if we can base recursion limiter on number of incoming phi
1979 // edges so we don't overly clamp analysis.
1980 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1982
1983 // See if we can further use a conditional branch into the phi
1984 // to help us determine the range of the value.
1985 if (!Known2.isConstant()) {
1986 CmpPredicate Pred;
1987 const APInt *RHSC;
1988 BasicBlock *TrueSucc, *FalseSucc;
1989 // TODO: Use RHS Value and compute range from its known bits.
1990 if (match(RecQ.CxtI,
1991 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1992 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1993 // Check for cases of duplicate successors.
1994 if ((TrueSucc == CxtPhi->getParent()) !=
1995 (FalseSucc == CxtPhi->getParent())) {
1996 // If we're using the false successor, invert the predicate.
1997 if (FalseSucc == CxtPhi->getParent())
1998 Pred = CmpInst::getInversePredicate(Pred);
1999 // Get the knownbits implied by the incoming phi condition.
2000 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2001 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2002 // We can have conflicts here if we are analyzing deadcode (its
2003 // impossible for us reach this BB based the icmp).
2004 if (KnownUnion.hasConflict()) {
2005 // No reason to continue analyzing in a known dead region, so
2006 // just resetAll and break. This will cause us to also exit the
2007 // outer loop.
2008 Known.resetAll();
2009 break;
2010 }
2011 Known2 = KnownUnion;
2012 }
2013 }
2014 }
2015
2016 Known = Known.intersectWith(Known2);
2017 // If all bits have been ruled out, there's no need to check
2018 // more operands.
2019 if (Known.isUnknown())
2020 break;
2021 }
2022 }
2023 break;
2024 }
2025 case Instruction::Call:
2026 case Instruction::Invoke: {
2027 // If range metadata is attached to this call, set known bits from that,
2028 // and then intersect with known bits based on other properties of the
2029 // function.
2030 if (MDNode *MD =
2031 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2033
2034 const auto *CB = cast<CallBase>(I);
2035
2036 if (std::optional<ConstantRange> Range = CB->getRange())
2037 Known = Known.unionWith(Range->toKnownBits());
2038
2039 if (const Value *RV = CB->getReturnedArgOperand()) {
2040 if (RV->getType() == I->getType()) {
2041 computeKnownBits(RV, Known2, Q, Depth + 1);
2042 Known = Known.unionWith(Known2);
2043 // If the function doesn't return properly for all input values
2044 // (e.g. unreachable exits) then there might be conflicts between the
2045 // argument value and the range metadata. Simply discard the known bits
2046 // in case of conflicts.
2047 if (Known.hasConflict())
2048 Known.resetAll();
2049 }
2050 }
2051 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2052 switch (II->getIntrinsicID()) {
2053 default:
2054 break;
2055 case Intrinsic::abs: {
2056 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2057 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2058 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2059 break;
2060 }
2061 case Intrinsic::bitreverse:
2062 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2063 Known = Known.unionWith(Known2.reverseBits());
2064 break;
2065 case Intrinsic::bswap:
2066 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2067 Known = Known.unionWith(Known2.byteSwap());
2068 break;
2069 case Intrinsic::ctlz: {
2070 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2071 // If we have a known 1, its position is our upper bound.
2072 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2073 // If this call is poison for 0 input, the result will be less than 2^n.
2074 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2075 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2076 unsigned LowBits = llvm::bit_width(PossibleLZ);
2077 Known.Zero.setBitsFrom(LowBits);
2078 break;
2079 }
2080 case Intrinsic::cttz: {
2081 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2082 // If we have a known 1, its position is our upper bound.
2083 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2084 // If this call is poison for 0 input, the result will be less than 2^n.
2085 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2086 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2087 unsigned LowBits = llvm::bit_width(PossibleTZ);
2088 Known.Zero.setBitsFrom(LowBits);
2089 break;
2090 }
2091 case Intrinsic::ctpop: {
2092 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2093 // We can bound the space the count needs. Also, bits known to be zero
2094 // can't contribute to the population.
2095 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2096 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2097 Known.Zero.setBitsFrom(LowBits);
2098 // TODO: we could bound KnownOne using the lower bound on the number
2099 // of bits which might be set provided by popcnt KnownOne2.
2100 break;
2101 }
2102 case Intrinsic::fshr:
2103 case Intrinsic::fshl: {
2104 const APInt *SA;
2105 if (!match(I->getOperand(2), m_APInt(SA)))
2106 break;
2107
2108 KnownBits Known3(BitWidth);
2109 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2110 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2111 Known = II->getIntrinsicID() == Intrinsic::fshl
2112 ? KnownBits::fshl(Known2, Known3, *SA)
2113 : KnownBits::fshr(Known2, Known3, *SA);
2114 break;
2115 }
2116 case Intrinsic::clmul:
2117 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2118 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2119 Known = KnownBits::clmul(Known, Known2);
2120 break;
2121 case Intrinsic::pext:
2122 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2123 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2124 Known = KnownBits::pext(Known, Known2);
2125 break;
2126 case Intrinsic::pdep:
2127 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2128 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2129 Known = KnownBits::pdep(Known, Known2);
2130 break;
2131 case Intrinsic::uadd_sat:
2132 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2133 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2134 Known = KnownBits::uadd_sat(Known, Known2);
2135 break;
2136 case Intrinsic::usub_sat:
2137 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2138 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2139 Known = KnownBits::usub_sat(Known, Known2);
2140 break;
2141 case Intrinsic::sadd_sat:
2142 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2143 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2144 Known = KnownBits::sadd_sat(Known, Known2);
2145 break;
2146 case Intrinsic::ssub_sat:
2147 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2148 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2149 Known = KnownBits::ssub_sat(Known, Known2);
2150 break;
2151 // Vec reverse preserves bits from input vec.
2152 case Intrinsic::vector_reverse:
2153 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2154 Depth + 1);
2155 break;
2156 // for min/max/and/or reduce, any bit common to each element in the
2157 // input vec is set in the output.
2158 case Intrinsic::vector_reduce_and:
2159 case Intrinsic::vector_reduce_or:
2160 case Intrinsic::vector_reduce_umax:
2161 case Intrinsic::vector_reduce_umin:
2162 case Intrinsic::vector_reduce_smax:
2163 case Intrinsic::vector_reduce_smin:
2164 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2165 break;
2166 case Intrinsic::vector_reduce_xor: {
2167 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2168 // The zeros common to all vecs are zero in the output.
2169 // If the number of elements is odd, then the common ones remain. If the
2170 // number of elements is even, then the common ones becomes zeros.
2171 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2172 // Even, so the ones become zeros.
2173 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2174 if (EvenCnt)
2175 Known.Zero |= Known.One;
2176 // Maybe even element count so need to clear ones.
2177 if (VecTy->isScalableTy() || EvenCnt)
2178 Known.One.clearAllBits();
2179 break;
2180 }
2181 case Intrinsic::vector_reduce_add: {
2182 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2183 if (!VecTy)
2184 break;
2185 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2186 Known = Known.reduceAdd(VecTy->getNumElements());
2187 break;
2188 }
2189 case Intrinsic::umin:
2190 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2191 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2192 Known = KnownBits::umin(Known, Known2);
2193 break;
2194 case Intrinsic::umax:
2195 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2196 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2197 Known = KnownBits::umax(Known, Known2);
2198 break;
2199 case Intrinsic::smin:
2200 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2201 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2202 Known = KnownBits::smin(Known, Known2);
2204 break;
2205 case Intrinsic::smax:
2206 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2207 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2208 Known = KnownBits::smax(Known, Known2);
2210 break;
2211 case Intrinsic::ptrmask: {
2212 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2213
2214 const Value *Mask = I->getOperand(1);
2215 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2216 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2217 // TODO: 1-extend would be more precise.
2218 Known &= Known2.anyextOrTrunc(BitWidth);
2219 break;
2220 }
2221 case Intrinsic::x86_sse2_pmulh_w:
2222 case Intrinsic::x86_avx2_pmulh_w:
2223 case Intrinsic::x86_avx512_pmulh_w_512:
2224 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2225 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2226 Known = KnownBits::mulhs(Known, Known2);
2227 break;
2228 case Intrinsic::x86_sse2_pmulhu_w:
2229 case Intrinsic::x86_avx2_pmulhu_w:
2230 case Intrinsic::x86_avx512_pmulhu_w_512:
2231 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2232 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2233 Known = KnownBits::mulhu(Known, Known2);
2234 break;
2235 case Intrinsic::x86_sse42_crc32_64_64:
2236 Known.Zero.setBitsFrom(32);
2237 break;
2238 case Intrinsic::x86_ssse3_phadd_d_128:
2239 case Intrinsic::x86_ssse3_phadd_w_128:
2240 case Intrinsic::x86_avx2_phadd_d:
2241 case Intrinsic::x86_avx2_phadd_w: {
2243 I, DemandedElts, Q, Depth,
2244 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2245 return KnownBits::add(KnownLHS, KnownRHS);
2246 });
2247 break;
2248 }
2249 case Intrinsic::x86_ssse3_phadd_sw_128:
2250 case Intrinsic::x86_avx2_phadd_sw: {
2252 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2253 break;
2254 }
2255 case Intrinsic::x86_ssse3_phsub_d_128:
2256 case Intrinsic::x86_ssse3_phsub_w_128:
2257 case Intrinsic::x86_avx2_phsub_d:
2258 case Intrinsic::x86_avx2_phsub_w: {
2260 I, DemandedElts, Q, Depth,
2261 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2262 return KnownBits::sub(KnownLHS, KnownRHS);
2263 });
2264 break;
2265 }
2266 case Intrinsic::x86_ssse3_phsub_sw_128:
2267 case Intrinsic::x86_avx2_phsub_sw: {
2269 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2270 break;
2271 }
2272 case Intrinsic::riscv_vsetvli:
2273 case Intrinsic::riscv_vsetvlimax: {
2274 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2275 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2277 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2278 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2279 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2280 uint64_t MaxVLEN =
2281 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2282 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2283
2284 // Result of vsetvli must be not larger than AVL.
2285 if (HasAVL)
2286 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2287 MaxVL = std::min(MaxVL, CI->getZExtValue());
2288
2289 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2290 if (BitWidth > KnownZeroFirstBit)
2291 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2292 break;
2293 }
2294 case Intrinsic::amdgcn_mbcnt_hi:
2295 case Intrinsic::amdgcn_mbcnt_lo: {
2296 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2297 // most 31 + src1.
2298 Known.Zero.setBitsFrom(
2299 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2300 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2301 Known = KnownBits::add(Known, Known2);
2302 break;
2303 }
2304 case Intrinsic::vscale: {
2305 if (!II->getParent() || !II->getFunction())
2306 break;
2307
2308 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2309 break;
2310 }
2311 }
2312 }
2313 break;
2314 }
2315 case Instruction::ShuffleVector: {
2316 if (auto *Splat = getSplatValue(I)) {
2318 break;
2319 }
2320
2321 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2322 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2323 if (!Shuf) {
2324 Known.resetAll();
2325 return;
2326 }
2327 // For undef elements, we don't know anything about the common state of
2328 // the shuffle result.
2329 APInt DemandedLHS, DemandedRHS;
2330 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2331 Known.resetAll();
2332 return;
2333 }
2334 Known.setAllConflict();
2335 if (!!DemandedLHS) {
2336 const Value *LHS = Shuf->getOperand(0);
2337 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2338 // If we don't know any bits, early out.
2339 if (Known.isUnknown())
2340 break;
2341 }
2342 if (!!DemandedRHS) {
2343 const Value *RHS = Shuf->getOperand(1);
2344 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2345 Known = Known.intersectWith(Known2);
2346 }
2347 break;
2348 }
2349 case Instruction::InsertElement: {
2350 if (isa<ScalableVectorType>(I->getType())) {
2351 Known.resetAll();
2352 return;
2353 }
2354 const Value *Vec = I->getOperand(0);
2355 const Value *Elt = I->getOperand(1);
2356 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2357 unsigned NumElts = DemandedElts.getBitWidth();
2358 APInt DemandedVecElts = DemandedElts;
2359 bool NeedsElt = true;
2360 // If we know the index we are inserting too, clear it from Vec check.
2361 if (CIdx && CIdx->getValue().ult(NumElts)) {
2362 DemandedVecElts.clearBit(CIdx->getZExtValue());
2363 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2364 }
2365
2366 Known.setAllConflict();
2367 if (NeedsElt) {
2368 computeKnownBits(Elt, Known, Q, Depth + 1);
2369 // If we don't know any bits, early out.
2370 if (Known.isUnknown())
2371 break;
2372 }
2373
2374 if (!DemandedVecElts.isZero()) {
2375 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2376 Known = Known.intersectWith(Known2);
2377 }
2378 break;
2379 }
2380 case Instruction::ExtractElement: {
2381 // Look through extract element. If the index is non-constant or
2382 // out-of-range demand all elements, otherwise just the extracted element.
2383 const Value *Vec = I->getOperand(0);
2384 const Value *Idx = I->getOperand(1);
2385 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2386 if (isa<ScalableVectorType>(Vec->getType())) {
2387 // FIXME: there's probably *something* we can do with scalable vectors
2388 Known.resetAll();
2389 break;
2390 }
2391 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2392 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2393 if (CIdx && CIdx->getValue().ult(NumElts))
2394 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2395 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2396 break;
2397 }
2398 case Instruction::ExtractValue:
2399 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2401 if (EVI->getNumIndices() != 1) break;
2402 if (EVI->getIndices()[0] == 0) {
2403 switch (II->getIntrinsicID()) {
2404 default: break;
2405 case Intrinsic::uadd_with_overflow:
2406 case Intrinsic::sadd_with_overflow:
2408 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2409 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2410 break;
2411 case Intrinsic::usub_with_overflow:
2412 case Intrinsic::ssub_with_overflow:
2414 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2415 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2416 break;
2417 case Intrinsic::umul_with_overflow:
2418 case Intrinsic::smul_with_overflow:
2419 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2420 false, DemandedElts, Known, Known2, Q, Depth);
2421 break;
2422 }
2423 }
2424 }
2425 break;
2426 case Instruction::Freeze:
2427 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2428 Depth + 1))
2429 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2430 break;
2431 }
2432}
2433
2434/// Determine which bits of V are known to be either zero or one and return
2435/// them.
2436KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2437 const SimplifyQuery &Q, unsigned Depth) {
2438 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2439 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2440 return Known;
2441}
2442
2443/// Determine which bits of V are known to be either zero or one and return
2444/// them.
2446 unsigned Depth) {
2447 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2449 return Known;
2450}
2451
2452/// Determine which bits of V are known to be either zero or one and return
2453/// them in the Known bit set.
2454///
2455/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2456/// we cannot optimize based on the assumption that it is zero without changing
2457/// it to be an explicit zero. If we don't change it to zero, other code could
2458/// optimized based on the contradictory assumption that it is non-zero.
2459/// Because instcombine aggressively folds operations with undef args anyway,
2460/// this won't lose us code quality.
2461///
2462/// This function is defined on values with integer type, values with pointer
2463/// type, and vectors of integers. In the case
2464/// where V is a vector, known zero, and known one values are the
2465/// same width as the vector element, and the bit is set only if it is true
2466/// for all of the demanded elements in the vector specified by DemandedElts.
2467void computeKnownBits(const Value *V, const APInt &DemandedElts,
2468 KnownBits &Known, const SimplifyQuery &Q,
2469 unsigned Depth) {
2470 if (!DemandedElts) {
2471 // No demanded elts, better to assume we don't know anything.
2472 Known.resetAll();
2473 return;
2474 }
2475
2476 assert(V && "No Value?");
2477 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2478
2479#ifndef NDEBUG
2480 Type *Ty = V->getType();
2481 unsigned BitWidth = Known.getBitWidth();
2482
2483 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2484 "Not integer or pointer type!");
2485
2486 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2487 assert(
2488 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2489 "DemandedElt width should equal the fixed vector number of elements");
2490 } else {
2491 assert(DemandedElts == APInt(1, 1) &&
2492 "DemandedElt width should be 1 for scalars or scalable vectors");
2493 }
2494
2495 Type *ScalarTy = Ty->getScalarType();
2496 if (ScalarTy->isPointerTy()) {
2497 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2498 "V and Known should have same BitWidth");
2499 } else {
2500 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2501 "V and Known should have same BitWidth");
2502 }
2503#endif
2504
2505 const APInt *C;
2506 if (match(V, m_APInt(C))) {
2507 // We know all of the bits for a scalar constant or a splat vector constant!
2509 return;
2510 }
2511 // Null and aggregate-zero are all-zeros.
2513 Known.setAllZero();
2514 return;
2515 }
2516 // Handle a constant vector by taking the intersection of the known bits of
2517 // each element.
2519 assert(!isa<ScalableVectorType>(V->getType()));
2520 // We know that CDV must be a vector of integers. Take the intersection of
2521 // each element.
2522 Known.setAllConflict();
2523 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2524 if (!DemandedElts[i])
2525 continue;
2526 APInt Elt = CDV->getElementAsAPInt(i);
2527 Known.Zero &= ~Elt;
2528 Known.One &= Elt;
2529 }
2530 if (Known.hasConflict())
2531 Known.resetAll();
2532 return;
2533 }
2534
2535 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2536 assert(!isa<ScalableVectorType>(V->getType()));
2537 // We know that CV must be a vector of integers. Take the intersection of
2538 // each element.
2539 Known.setAllConflict();
2540 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2541 if (!DemandedElts[i])
2542 continue;
2543 Constant *Element = CV->getAggregateElement(i);
2544 if (isa<PoisonValue>(Element))
2545 continue;
2546 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2547 if (!ElementCI) {
2548 Known.resetAll();
2549 return;
2550 }
2551 const APInt &Elt = ElementCI->getValue();
2552 Known.Zero &= ~Elt;
2553 Known.One &= Elt;
2554 }
2555 if (Known.hasConflict())
2556 Known.resetAll();
2557 return;
2558 }
2559
2560 // Start out not knowing anything.
2561 Known.resetAll();
2562
2563 // We can't imply anything about undefs.
2564 if (isa<UndefValue>(V))
2565 return;
2566
2567 // There's no point in looking through other users of ConstantData for
2568 // assumptions. Confirm that we've handled them all.
2569 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2570
2571 if (const auto *A = dyn_cast<Argument>(V))
2572 if (std::optional<ConstantRange> Range = A->getRange())
2573 Known = Range->toKnownBits();
2574
2575 // All recursive calls that increase depth must come after this.
2577 return;
2578
2579 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2580 // the bits of its aliasee.
2581 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2582 if (!GA->isInterposable())
2583 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2584 return;
2585 }
2586
2587 if (const Operator *I = dyn_cast<Operator>(V))
2588 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2589 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2590 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2591 Known = CR->toKnownBits();
2592 }
2593
2594 // Aligned pointers have trailing zeros - refine Known.Zero set
2595 if (isa<PointerType>(V->getType())) {
2596 Align Alignment = V->getPointerAlignment(Q.DL);
2597 Known.Zero.setLowBits(Log2(Alignment));
2598 }
2599
2600 // computeKnownBitsFromContext strictly refines Known.
2601 // Therefore, we run them after computeKnownBitsFromOperator.
2602
2603 // Check whether we can determine known bits from context such as assumes.
2605}
2606
2607/// Try to detect a recurrence that the value of the induction variable is
2608/// always a power of two (or zero).
2609static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2610 SimplifyQuery &Q, unsigned Depth) {
2611 BinaryOperator *BO = nullptr;
2612 Value *Start = nullptr, *Step = nullptr;
2613 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2614 return false;
2615
2616 // Initial value must be a power of two.
2617 for (const Use &U : PN->operands()) {
2618 if (U.get() == Start) {
2619 // Initial value comes from a different BB, need to adjust context
2620 // instruction for analysis.
2621 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2622 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2623 return false;
2624 }
2625 }
2626
2627 // Except for Mul, the induction variable must be on the left side of the
2628 // increment expression, otherwise its value can be arbitrary.
2629 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2630 return false;
2631
2632 Q.CxtI = BO->getParent()->getTerminator();
2633 switch (BO->getOpcode()) {
2634 case Instruction::Mul:
2635 // Power of two is closed under multiplication.
2636 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2637 Q.IIQ.hasNoSignedWrap(BO)) &&
2638 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2639 case Instruction::SDiv:
2640 // Start value must not be signmask for signed division, so simply being a
2641 // power of two is not sufficient, and it has to be a constant.
2642 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2643 return false;
2644 [[fallthrough]];
2645 case Instruction::UDiv:
2646 // Divisor must be a power of two.
2647 // If OrZero is false, cannot guarantee induction variable is non-zero after
2648 // division, same for Shr, unless it is exact division.
2649 return (OrZero || Q.IIQ.isExact(BO)) &&
2650 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2651 case Instruction::Shl:
2652 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2653 case Instruction::AShr:
2654 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2655 return false;
2656 [[fallthrough]];
2657 case Instruction::LShr:
2658 return OrZero || Q.IIQ.isExact(BO);
2659 default:
2660 return false;
2661 }
2662}
2663
2664/// Return true if we can infer that \p V is known to be a power of 2 from
2665/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2666static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2667 const Value *Cond,
2668 bool CondIsTrue) {
2669 CmpPredicate Pred;
2670 const APInt *RHSC;
2671 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2672 return false;
2673 if (!CondIsTrue)
2674 Pred = ICmpInst::getInversePredicate(Pred);
2675 // ctpop(V) u< 2
2676 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2677 return true;
2678 // ctpop(V) == 1
2679 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2680}
2681
2682/// Return true if the given value is known to have exactly one
2683/// bit set when defined. For vectors return true if every element is known to
2684/// be a power of two when defined. Supports values with integer or pointer
2685/// types and vectors of integers.
2686bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2687 const SimplifyQuery &Q, unsigned Depth) {
2688 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2689
2690 if (isa<Constant>(V))
2691 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2692
2693 // i1 is by definition a power of 2 or zero.
2694 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2695 return true;
2696
2697 // Try to infer from assumptions.
2698 if (Q.AC && Q.CxtI) {
2699 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2700 if (!AssumeVH)
2701 continue;
2702 CallInst *I = cast<CallInst>(AssumeVH);
2703 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2704 /*CondIsTrue=*/true) &&
2706 return true;
2707 }
2708 }
2709
2710 // Handle dominating conditions.
2711 if (Q.DC && Q.CxtI && Q.DT) {
2712 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2713 Value *Cond = BI->getCondition();
2714
2715 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2717 /*CondIsTrue=*/true) &&
2718 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2719 return true;
2720
2721 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2723 /*CondIsTrue=*/false) &&
2724 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2725 return true;
2726 }
2727 }
2728
2729 auto *I = dyn_cast<Instruction>(V);
2730 if (!I)
2731 return false;
2732
2733 if (Q.CxtI && match(V, m_VScale())) {
2734 const Function *F = Q.CxtI->getFunction();
2735 // The vscale_range indicates vscale is a power-of-two.
2736 return F->hasFnAttribute(Attribute::VScaleRange);
2737 }
2738
2739 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2740 // it is shifted off the end then the result is undefined.
2741 if (match(I, m_Shl(m_One(), m_Value())))
2742 return true;
2743
2744 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2745 // the bottom. If it is shifted off the bottom then the result is undefined.
2746 if (match(I, m_LShr(m_SignMask(), m_Value())))
2747 return true;
2748
2749 // The remaining tests are all recursive, so bail out if we hit the limit.
2751 return false;
2752
2753 switch (I->getOpcode()) {
2754 case Instruction::ZExt:
2755 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2756 case Instruction::Trunc:
2757 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2758 case Instruction::Shl:
2759 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2760 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2761 return false;
2762 case Instruction::LShr:
2763 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2764 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2765 return false;
2766 case Instruction::UDiv:
2768 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2769 return false;
2770 case Instruction::Mul:
2771 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2772 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2773 (OrZero || isKnownNonZero(I, Q, Depth));
2774 case Instruction::And:
2775 // A power of two and'd with anything is a power of two or zero.
2776 if (OrZero &&
2777 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2778 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2779 return true;
2780 // X & (-X) is always a power of two or zero.
2781 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2782 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2783 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2784 return false;
2785 case Instruction::Add: {
2786 // Adding a power-of-two or zero to the same power-of-two or zero yields
2787 // either the original power-of-two, a larger power-of-two or zero.
2789 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2790 Q.IIQ.hasNoSignedWrap(VOBO)) {
2791 if (match(I->getOperand(0),
2792 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2793 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2794 return true;
2795 if (match(I->getOperand(1),
2796 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2797 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2798 return true;
2799
2800 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2801 KnownBits LHSBits(BitWidth);
2802 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2803
2804 KnownBits RHSBits(BitWidth);
2805 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2806 // If i8 V is a power of two or zero:
2807 // ZeroBits: 1 1 1 0 1 1 1 1
2808 // ~ZeroBits: 0 0 0 1 0 0 0 0
2809 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2810 // If OrZero isn't set, we cannot give back a zero result.
2811 // Make sure either the LHS or RHS has a bit set.
2812 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2813 return true;
2814 }
2815
2816 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2817 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2818 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2819 return true;
2820 return false;
2821 }
2822 case Instruction::Select:
2823 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2824 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2825 case Instruction::PHI: {
2826 // A PHI node is power of two if all incoming values are power of two, or if
2827 // it is an induction variable where in each step its value is a power of
2828 // two.
2829 auto *PN = cast<PHINode>(I);
2831
2832 // Check if it is an induction variable and always power of two.
2833 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2834 return true;
2835
2836 // Recursively check all incoming values. Limit recursion to 2 levels, so
2837 // that search complexity is limited to number of operands^2.
2838 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2839 return llvm::all_of(PN->operands(), [&](const Use &U) {
2840 // Value is power of 2 if it is coming from PHI node itself by induction.
2841 if (U.get() == PN)
2842 return true;
2843
2844 // Change the context instruction to the incoming block where it is
2845 // evaluated.
2846 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2847 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2848 });
2849 }
2850 case Instruction::Invoke:
2851 case Instruction::Call: {
2852 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2853 switch (II->getIntrinsicID()) {
2854 case Intrinsic::umax:
2855 case Intrinsic::smax:
2856 case Intrinsic::umin:
2857 case Intrinsic::smin:
2858 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2859 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2860 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2861 // thus dont change pow2/non-pow2 status.
2862 case Intrinsic::bitreverse:
2863 case Intrinsic::bswap:
2864 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2865 case Intrinsic::fshr:
2866 case Intrinsic::fshl:
2867 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2868 if (II->getArgOperand(0) == II->getArgOperand(1))
2869 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2870 break;
2871 default:
2872 break;
2873 }
2874 }
2875 return false;
2876 }
2877 default:
2878 return false;
2879 }
2880}
2881
2882/// Test whether a GEP's result is known to be non-null.
2883///
2884/// Uses properties inherent in a GEP to try to determine whether it is known
2885/// to be non-null.
2886///
2887/// Currently this routine does not support vector GEPs.
2888static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2889 unsigned Depth) {
2890 const Function *F = nullptr;
2891 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2892 F = I->getFunction();
2893
2894 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2895 // may be null iff the base pointer is null and the offset is zero.
2896 if (!GEP->hasNoUnsignedWrap() &&
2897 !(GEP->isInBounds() &&
2898 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2899 return false;
2900
2901 // FIXME: Support vector-GEPs.
2902 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2903
2904 // If the base pointer is non-null, we cannot walk to a null address with an
2905 // inbounds GEP in address space zero.
2906 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2907 return true;
2908
2909 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2910 // If so, then the GEP cannot produce a null pointer, as doing so would
2911 // inherently violate the inbounds contract within address space zero.
2913 GTI != GTE; ++GTI) {
2914 // Struct types are easy -- they must always be indexed by a constant.
2915 if (StructType *STy = GTI.getStructTypeOrNull()) {
2916 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2917 unsigned ElementIdx = OpC->getZExtValue();
2918 const StructLayout *SL = Q.DL.getStructLayout(STy);
2919 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2920 if (ElementOffset > 0)
2921 return true;
2922 continue;
2923 }
2924
2925 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2926 if (GTI.getSequentialElementStride(Q.DL).isZero())
2927 continue;
2928
2929 // Fast path the constant operand case both for efficiency and so we don't
2930 // increment Depth when just zipping down an all-constant GEP.
2931 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2932 if (!OpC->isZero())
2933 return true;
2934 continue;
2935 }
2936
2937 // We post-increment Depth here because while isKnownNonZero increments it
2938 // as well, when we pop back up that increment won't persist. We don't want
2939 // to recurse 10k times just because we have 10k GEP operands. We don't
2940 // bail completely out because we want to handle constant GEPs regardless
2941 // of depth.
2943 continue;
2944
2945 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2946 return true;
2947 }
2948
2949 return false;
2950}
2951
2953 const Instruction *CtxI,
2954 const DominatorTree *DT) {
2955 assert(!isa<Constant>(V) && "Called for constant?");
2956
2957 if (!CtxI || !DT)
2958 return false;
2959
2960 unsigned NumUsesExplored = 0;
2961 for (auto &U : V->uses()) {
2962 // Avoid massive lists
2963 if (NumUsesExplored >= DomConditionsMaxUses)
2964 break;
2965 NumUsesExplored++;
2966
2967 const Instruction *UI = cast<Instruction>(U.getUser());
2968 // If the value is used as an argument to a call or invoke, then argument
2969 // attributes may provide an answer about null-ness.
2970 if (V->getType()->isPointerTy()) {
2971 if (const auto *CB = dyn_cast<CallBase>(UI)) {
2972 if (CB->isArgOperand(&U) &&
2973 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
2974 /*AllowUndefOrPoison=*/false) &&
2975 DT->dominates(CB, CtxI))
2976 return true;
2977 }
2978 }
2979
2980 // If the value is used as a load/store, then the pointer must be non null.
2981 if (V == getLoadStorePointerOperand(UI)) {
2984 DT->dominates(UI, CtxI))
2985 return true;
2986 }
2987
2988 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
2989 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
2990 isValidAssumeForContext(UI, CtxI, DT))
2991 return true;
2992
2993 // Consider only compare instructions uniquely controlling a branch
2994 Value *RHS;
2995 CmpPredicate Pred;
2996 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2997 continue;
2998
2999 bool NonNullIfTrue;
3000 if (cmpExcludesZero(Pred, RHS))
3001 NonNullIfTrue = true;
3003 NonNullIfTrue = false;
3004 else
3005 continue;
3006
3009 for (const auto *CmpU : UI->users()) {
3010 assert(WorkList.empty() && "Should be!");
3011 if (Visited.insert(CmpU).second)
3012 WorkList.push_back(CmpU);
3013
3014 while (!WorkList.empty()) {
3015 auto *Curr = WorkList.pop_back_val();
3016
3017 // If a user is an AND, add all its users to the work list. We only
3018 // propagate "pred != null" condition through AND because it is only
3019 // correct to assume that all conditions of AND are met in true branch.
3020 // TODO: Support similar logic of OR and EQ predicate?
3021 if (NonNullIfTrue)
3022 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3023 for (const auto *CurrU : Curr->users())
3024 if (Visited.insert(CurrU).second)
3025 WorkList.push_back(CurrU);
3026 continue;
3027 }
3028
3029 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3030 BasicBlock *NonNullSuccessor =
3031 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3032 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3033 if (DT->dominates(Edge, CtxI->getParent()))
3034 return true;
3035 } else if (NonNullIfTrue && isGuard(Curr) &&
3036 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3037 return true;
3038 }
3039 }
3040 }
3041 }
3042
3043 return false;
3044}
3045
3046/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3047/// ensure that the value it's attached to is never Value? 'RangeType' is
3048/// is the type of the value described by the range.
3049static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3050 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3051 assert(NumRanges >= 1);
3052 for (unsigned i = 0; i < NumRanges; ++i) {
3054 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3056 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3057 ConstantRange Range(Lower->getValue(), Upper->getValue());
3058 if (Range.contains(Value))
3059 return false;
3060 }
3061 return true;
3062}
3063
3064/// Try to detect a recurrence that monotonically increases/decreases from a
3065/// non-zero starting value. These are common as induction variables.
3066static bool isNonZeroRecurrence(const PHINode *PN) {
3067 BinaryOperator *BO = nullptr;
3068 Value *Start = nullptr, *Step = nullptr;
3069 const APInt *StartC, *StepC;
3070 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3071 !match(Start, m_APInt(StartC)) || StartC->isZero())
3072 return false;
3073
3074 switch (BO->getOpcode()) {
3075 case Instruction::Add:
3076 // Starting from non-zero and stepping away from zero can never wrap back
3077 // to zero.
3078 return BO->hasNoUnsignedWrap() ||
3079 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3080 StartC->isNegative() == StepC->isNegative());
3081 case Instruction::Mul:
3082 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3083 match(Step, m_APInt(StepC)) && !StepC->isZero();
3084 case Instruction::Shl:
3085 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3086 case Instruction::AShr:
3087 case Instruction::LShr:
3088 return BO->isExact();
3089 default:
3090 return false;
3091 }
3092}
3093
3094static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3096 m_Specific(Op1), m_Zero()))) ||
3098 m_Specific(Op0), m_Zero())));
3099}
3100
3101static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3102 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3103 bool NUW, unsigned Depth) {
3104 // (X + (X != 0)) is non zero
3105 if (matchOpWithOpEqZero(X, Y))
3106 return true;
3107
3108 if (NUW)
3109 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3110 isKnownNonZero(X, DemandedElts, Q, Depth);
3111
3112 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3113 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3114
3115 // If X and Y are both non-negative (as signed values) then their sum is not
3116 // zero unless both X and Y are zero.
3117 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3118 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3119 isKnownNonZero(X, DemandedElts, Q, Depth))
3120 return true;
3121
3122 // If X and Y are both negative (as signed values) then their sum is not
3123 // zero unless both X and Y equal INT_MIN.
3124 if (XKnown.isNegative() && YKnown.isNegative()) {
3126 // The sign bit of X is set. If some other bit is set then X is not equal
3127 // to INT_MIN.
3128 if (XKnown.One.intersects(Mask))
3129 return true;
3130 // The sign bit of Y is set. If some other bit is set then Y is not equal
3131 // to INT_MIN.
3132 if (YKnown.One.intersects(Mask))
3133 return true;
3134 }
3135
3136 // The sum of a non-negative number and a power of two is not zero.
3137 if (XKnown.isNonNegative() &&
3138 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3139 return true;
3140 if (YKnown.isNonNegative() &&
3141 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3142 return true;
3143
3144 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3145}
3146
3147static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3148 unsigned BitWidth, Value *X, Value *Y,
3149 unsigned Depth) {
3150 // (X - (X != 0)) is non zero
3151 // ((X != 0) - X) is non zero
3152 if (matchOpWithOpEqZero(X, Y))
3153 return true;
3154
3155 // TODO: Move this case into isKnownNonEqual().
3156 if (auto *C = dyn_cast<Constant>(X))
3157 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3158 return true;
3159
3160 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3161}
3162
3163static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3164 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3165 bool NUW, unsigned Depth) {
3166 // If X and Y are non-zero then so is X * Y as long as the multiplication
3167 // does not overflow.
3168 if (NSW || NUW)
3169 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3170 isKnownNonZero(Y, DemandedElts, Q, Depth);
3171
3172 // If either X or Y is odd, then if the other is non-zero the result can't
3173 // be zero.
3174 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3175 if (XKnown.One[0])
3176 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3177
3178 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3179 if (YKnown.One[0])
3180 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3181
3182 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3183 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3184 // the lowest known One of X and Y. If they are non-zero, the result
3185 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3186 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3187 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3188 BitWidth;
3189}
3190
3191static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3192 const SimplifyQuery &Q, const KnownBits &KnownVal,
3193 unsigned Depth) {
3194 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3195 switch (I->getOpcode()) {
3196 case Instruction::Shl:
3197 return Lhs.shl(Rhs);
3198 case Instruction::LShr:
3199 return Lhs.lshr(Rhs);
3200 case Instruction::AShr:
3201 return Lhs.ashr(Rhs);
3202 default:
3203 llvm_unreachable("Unknown Shift Opcode");
3204 }
3205 };
3206
3207 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3208 switch (I->getOpcode()) {
3209 case Instruction::Shl:
3210 return Lhs.lshr(Rhs);
3211 case Instruction::LShr:
3212 case Instruction::AShr:
3213 return Lhs.shl(Rhs);
3214 default:
3215 llvm_unreachable("Unknown Shift Opcode");
3216 }
3217 };
3218
3219 if (KnownVal.isUnknown())
3220 return false;
3221
3222 KnownBits KnownCnt =
3223 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3224 APInt MaxShift = KnownCnt.getMaxValue();
3225 unsigned NumBits = KnownVal.getBitWidth();
3226 if (MaxShift.uge(NumBits))
3227 return false;
3228
3229 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3230 return true;
3231
3232 // If all of the bits shifted out are known to be zero, and Val is known
3233 // non-zero then at least one non-zero bit must remain.
3234 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3235 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3236 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3237 return true;
3238
3239 return false;
3240}
3241
3243 const APInt &DemandedElts,
3244 const SimplifyQuery &Q, unsigned Depth) {
3245 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3246 switch (I->getOpcode()) {
3247 case Instruction::Alloca:
3248 // Alloca never returns null, malloc might.
3249 return I->getType()->getPointerAddressSpace() == 0;
3250 case Instruction::GetElementPtr:
3251 if (I->getType()->isPointerTy())
3253 break;
3254 case Instruction::BitCast: {
3255 // We need to be a bit careful here. We can only peek through the bitcast
3256 // if the scalar size of elements in the operand are smaller than and a
3257 // multiple of the size they are casting too. Take three cases:
3258 //
3259 // 1) Unsafe:
3260 // bitcast <2 x i16> %NonZero to <4 x i8>
3261 //
3262 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3263 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3264 // guranteed (imagine just sign bit set in the 2 i16 elements).
3265 //
3266 // 2) Unsafe:
3267 // bitcast <4 x i3> %NonZero to <3 x i4>
3268 //
3269 // Even though the scalar size of the src (`i3`) is smaller than the
3270 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3271 // its possible for the `3 x i4` elements to be zero because there are
3272 // some elements in the destination that don't contain any full src
3273 // element.
3274 //
3275 // 3) Safe:
3276 // bitcast <4 x i8> %NonZero to <2 x i16>
3277 //
3278 // This is always safe as non-zero in the 4 i8 elements implies
3279 // non-zero in the combination of any two adjacent ones. Since i8 is a
3280 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3281 // This all implies the 2 i16 elements are non-zero.
3282 Type *FromTy = I->getOperand(0)->getType();
3283 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3284 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3285 return isKnownNonZero(I->getOperand(0), Q, Depth);
3286 } break;
3287 case Instruction::IntToPtr:
3288 // Note that we have to take special care to avoid looking through
3289 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3290 // as casts that can alter the value, e.g., AddrSpaceCasts.
3291 if (!isa<ScalableVectorType>(I->getType()) &&
3292 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3293 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3294 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3295 break;
3296 case Instruction::PtrToAddr:
3297 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3298 // so we can directly forward.
3299 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3300 case Instruction::PtrToInt:
3301 // For inttoptr, make sure the result size is >= the address size. If the
3302 // address is non-zero, any larger value is also non-zero.
3303 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3304 I->getType()->getScalarSizeInBits())
3305 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3306 break;
3307 case Instruction::Trunc:
3308 // nuw/nsw trunc preserves zero/non-zero status of input.
3309 if (auto *TI = dyn_cast<TruncInst>(I))
3310 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3311 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3312 break;
3313
3314 // Iff x - y != 0, then x ^ y != 0
3315 // Therefore we can do the same exact checks
3316 case Instruction::Xor:
3317 case Instruction::Sub:
3318 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3319 I->getOperand(1), Depth);
3320 case Instruction::Or:
3321 // (X | (X != 0)) is non zero
3322 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3323 return true;
3324 // X | Y != 0 if X != Y.
3325 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3326 Depth))
3327 return true;
3328 // X | Y != 0 if X != 0 or Y != 0.
3329 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3330 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3331 case Instruction::SExt:
3332 case Instruction::ZExt:
3333 // ext X != 0 if X != 0.
3334 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3335
3336 case Instruction::Shl: {
3337 // shl nsw/nuw can't remove any non-zero bits.
3339 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3340 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3341
3342 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3343 // if the lowest bit is shifted off the end.
3345 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3346 if (Known.One[0])
3347 return true;
3348
3349 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3350 }
3351 case Instruction::LShr:
3352 case Instruction::AShr: {
3353 // shr exact can only shift out zero bits.
3355 if (BO->isExact())
3356 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3357
3358 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3359 // defined if the sign bit is shifted off the end.
3361 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3362 if (Known.isNegative())
3363 return true;
3364
3365 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3366 // position >= C, because the sum >= max(A, B).
3367 Value *A, *B;
3368 const APInt *C;
3369 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3370 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3371 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3372 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3373 if (!KnownA.One.lshr(*C).isZero())
3374 return true;
3375 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3376 if (!KnownB.One.lshr(*C).isZero())
3377 return true;
3378 }
3379
3380 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3381 }
3382 case Instruction::UDiv:
3383 case Instruction::SDiv: {
3384 // X / Y
3385 // div exact can only produce a zero if the dividend is zero.
3386 if (cast<PossiblyExactOperator>(I)->isExact())
3387 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3388
3389 KnownBits XKnown =
3390 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3391 // If X is fully unknown we won't be able to figure anything out so don't
3392 // both computing knownbits for Y.
3393 if (XKnown.isUnknown())
3394 return false;
3395
3396 KnownBits YKnown =
3397 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3398 if (I->getOpcode() == Instruction::SDiv) {
3399 // For signed division need to compare abs value of the operands.
3400 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3401 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3402 }
3403 // If X u>= Y then div is non zero (0/0 is UB).
3404 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3405 // If X is total unknown or X u< Y we won't be able to prove non-zero
3406 // with compute known bits so just return early.
3407 return XUgeY && *XUgeY;
3408 }
3409 case Instruction::Add: {
3410 // X + Y.
3411
3412 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3413 // non-zero.
3415 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3416 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3417 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3418 }
3419 case Instruction::Mul: {
3421 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3422 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3423 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3424 }
3425 case Instruction::Select: {
3426 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3427
3428 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3429 // then see if the select condition implies the arm is non-zero. For example
3430 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3431 // dominated by `X != 0`.
3432 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3433 Value *Op;
3434 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3435 // Op is trivially non-zero.
3436 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3437 return true;
3438
3439 // The condition of the select dominates the true/false arm. Check if the
3440 // condition implies that a given arm is non-zero.
3441 Value *X;
3442 CmpPredicate Pred;
3443 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3444 return false;
3445
3446 if (!IsTrueArm)
3447 Pred = ICmpInst::getInversePredicate(Pred);
3448
3449 return cmpExcludesZero(Pred, X);
3450 };
3451
3452 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3453 SelectArmIsNonZero(/* IsTrueArm */ false))
3454 return true;
3455 break;
3456 }
3457 case Instruction::PHI: {
3458 auto *PN = cast<PHINode>(I);
3460 return true;
3461
3462 // Check if all incoming values are non-zero using recursion.
3464 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3465 return llvm::all_of(PN->operands(), [&](const Use &U) {
3466 if (U.get() == PN)
3467 return true;
3468 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3469 // Check if the branch on the phi excludes zero.
3470 CmpPredicate Pred;
3471 Value *X;
3472 BasicBlock *TrueSucc, *FalseSucc;
3473 if (match(RecQ.CxtI,
3474 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3475 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3476 // Check for cases of duplicate successors.
3477 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3478 // If we're using the false successor, invert the predicate.
3479 if (FalseSucc == PN->getParent())
3480 Pred = CmpInst::getInversePredicate(Pred);
3481 if (cmpExcludesZero(Pred, X))
3482 return true;
3483 }
3484 }
3485 // Finally recurse on the edge and check it directly.
3486 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3487 });
3488 }
3489 case Instruction::InsertElement: {
3490 if (isa<ScalableVectorType>(I->getType()))
3491 break;
3492
3493 const Value *Vec = I->getOperand(0);
3494 const Value *Elt = I->getOperand(1);
3495 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3496
3497 unsigned NumElts = DemandedElts.getBitWidth();
3498 APInt DemandedVecElts = DemandedElts;
3499 bool SkipElt = false;
3500 // If we know the index we are inserting too, clear it from Vec check.
3501 if (CIdx && CIdx->getValue().ult(NumElts)) {
3502 DemandedVecElts.clearBit(CIdx->getZExtValue());
3503 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3504 }
3505
3506 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3507 // are non-zero.
3508 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3509 (DemandedVecElts.isZero() ||
3510 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3511 }
3512 case Instruction::ExtractElement:
3513 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3514 const Value *Vec = EEI->getVectorOperand();
3515 const Value *Idx = EEI->getIndexOperand();
3516 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3517 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3518 unsigned NumElts = VecTy->getNumElements();
3519 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3520 if (CIdx && CIdx->getValue().ult(NumElts))
3521 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3522 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3523 }
3524 }
3525 break;
3526 case Instruction::ShuffleVector: {
3527 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3528 if (!Shuf)
3529 break;
3530 APInt DemandedLHS, DemandedRHS;
3531 // For undef elements, we don't know anything about the common state of
3532 // the shuffle result.
3533 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3534 break;
3535 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3536 return (DemandedRHS.isZero() ||
3537 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3538 (DemandedLHS.isZero() ||
3539 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3540 }
3541 case Instruction::Freeze:
3542 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3543 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3544 Depth);
3545 case Instruction::Load: {
3546 auto *LI = cast<LoadInst>(I);
3547 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3548 // is never null.
3549 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3550 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3551 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3552 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3553 return true;
3554 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3556 }
3557
3558 // No need to fall through to computeKnownBits as range metadata is already
3559 // handled in isKnownNonZero.
3560 return false;
3561 }
3562 case Instruction::ExtractValue: {
3563 const WithOverflowInst *WO;
3565 switch (WO->getBinaryOp()) {
3566 default:
3567 break;
3568 case Instruction::Add:
3569 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3570 WO->getArgOperand(1),
3571 /*NSW=*/false,
3572 /*NUW=*/false, Depth);
3573 case Instruction::Sub:
3574 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3575 WO->getArgOperand(1), Depth);
3576 case Instruction::Mul:
3577 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3578 WO->getArgOperand(1),
3579 /*NSW=*/false, /*NUW=*/false, Depth);
3580 break;
3581 }
3582 }
3583 break;
3584 }
3585 case Instruction::Call:
3586 case Instruction::Invoke: {
3587 const auto *Call = cast<CallBase>(I);
3588 if (I->getType()->isPointerTy()) {
3589 if (Call->isReturnNonNull())
3590 return true;
3591 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3592 Call, /*MustPreserveOffset=*/true))
3593 return isKnownNonZero(RP, Q, Depth);
3594 } else {
3595 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3597 if (std::optional<ConstantRange> Range = Call->getRange()) {
3598 const APInt ZeroValue(Range->getBitWidth(), 0);
3599 if (!Range->contains(ZeroValue))
3600 return true;
3601 }
3602 if (const Value *RV = Call->getReturnedArgOperand())
3603 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3604 return true;
3605 }
3606
3607 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3608 switch (II->getIntrinsicID()) {
3609 case Intrinsic::sshl_sat:
3610 case Intrinsic::ushl_sat:
3611 case Intrinsic::abs:
3612 case Intrinsic::bitreverse:
3613 case Intrinsic::bswap:
3614 case Intrinsic::ctpop:
3615 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3616 // NB: We don't do usub_sat here as in any case we can prove its
3617 // non-zero, we will fold it to `sub nuw` in InstCombine.
3618 case Intrinsic::ssub_sat:
3619 // For most types, if x != y then ssub.sat x, y != 0. But
3620 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3621 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3622 if (BitWidth == 1)
3623 return false;
3624 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3625 II->getArgOperand(1), Depth);
3626 case Intrinsic::sadd_sat:
3627 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3628 II->getArgOperand(1),
3629 /*NSW=*/true, /* NUW=*/false, Depth);
3630 // Vec reverse preserves zero/non-zero status from input vec.
3631 case Intrinsic::vector_reverse:
3632 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3633 Q, Depth);
3634 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3635 case Intrinsic::vector_reduce_or:
3636 case Intrinsic::vector_reduce_umax:
3637 case Intrinsic::vector_reduce_umin:
3638 case Intrinsic::vector_reduce_smax:
3639 case Intrinsic::vector_reduce_smin:
3640 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3641 case Intrinsic::umax:
3642 case Intrinsic::uadd_sat:
3643 // umax(X, (X != 0)) is non zero
3644 // X +usat (X != 0) is non zero
3645 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3646 return true;
3647
3648 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3649 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3650 case Intrinsic::smax: {
3651 // If either arg is strictly positive the result is non-zero. Otherwise
3652 // the result is non-zero if both ops are non-zero.
3653 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3654 const KnownBits &OpKnown) {
3655 if (!OpNonZero.has_value())
3656 OpNonZero = OpKnown.isNonZero() ||
3657 isKnownNonZero(Op, DemandedElts, Q, Depth);
3658 return *OpNonZero;
3659 };
3660 // Avoid re-computing isKnownNonZero.
3661 std::optional<bool> Op0NonZero, Op1NonZero;
3662 KnownBits Op1Known =
3663 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3664 if (Op1Known.isNonNegative() &&
3665 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3666 return true;
3667 KnownBits Op0Known =
3668 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3669 if (Op0Known.isNonNegative() &&
3670 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3671 return true;
3672 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3673 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3674 }
3675 case Intrinsic::smin: {
3676 // If either arg is negative the result is non-zero. Otherwise
3677 // the result is non-zero if both ops are non-zero.
3678 KnownBits Op1Known =
3679 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3680 if (Op1Known.isNegative())
3681 return true;
3682 KnownBits Op0Known =
3683 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3684 if (Op0Known.isNegative())
3685 return true;
3686
3687 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3688 return true;
3689 }
3690 [[fallthrough]];
3691 case Intrinsic::umin:
3692 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3693 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3694 case Intrinsic::cttz:
3695 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3696 .Zero[0];
3697 case Intrinsic::ctlz:
3698 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3699 .isNonNegative();
3700 case Intrinsic::fshr:
3701 case Intrinsic::fshl:
3702 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3703 if (II->getArgOperand(0) == II->getArgOperand(1))
3704 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3705 break;
3706 case Intrinsic::vscale:
3707 return true;
3708 case Intrinsic::experimental_get_vector_length:
3709 return isKnownNonZero(I->getOperand(0), Q, Depth);
3710 default:
3711 break;
3712 }
3713 break;
3714 }
3715
3716 return false;
3717 }
3718 }
3719
3721 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3722 return Known.One != 0;
3723}
3724
3725/// Return true if the given value is known to be non-zero when defined. For
3726/// vectors, return true if every demanded element is known to be non-zero when
3727/// defined. For pointers, if the context instruction and dominator tree are
3728/// specified, perform context-sensitive analysis and return true if the
3729/// pointer couldn't possibly be null at the specified instruction.
3730/// Supports values with integer or pointer type and vectors of integers.
3731bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3732 const SimplifyQuery &Q, unsigned Depth) {
3733 Type *Ty = V->getType();
3734
3735#ifndef NDEBUG
3736 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3737
3738 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3739 assert(
3740 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3741 "DemandedElt width should equal the fixed vector number of elements");
3742 } else {
3743 assert(DemandedElts == APInt(1, 1) &&
3744 "DemandedElt width should be 1 for scalars");
3745 }
3746#endif
3747
3748 if (auto *C = dyn_cast<Constant>(V)) {
3749 if (C->isNullValue())
3750 return false;
3751 if (isa<ConstantInt>(C))
3752 // Must be non-zero due to null test above.
3753 return true;
3754
3755 // For constant vectors, check that all elements are poison or known
3756 // non-zero to determine that the whole vector is known non-zero.
3757 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3758 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3759 if (!DemandedElts[i])
3760 continue;
3761 Constant *Elt = C->getAggregateElement(i);
3762 if (!Elt || Elt->isNullValue())
3763 return false;
3764 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3765 return false;
3766 }
3767 return true;
3768 }
3769
3770 // Constant ptrauth can be null, iff the base pointer can be.
3771 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3772 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3773
3774 // A global variable in address space 0 is non null unless extern weak
3775 // or an absolute symbol reference. Other address spaces may have null as a
3776 // valid address for a global, so we can't assume anything.
3777 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3778 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3779 GV->getType()->getAddressSpace() == 0)
3780 return true;
3781 }
3782
3783 // For constant expressions, fall through to the Operator code below.
3784 if (!isa<ConstantExpr>(V))
3785 return false;
3786 }
3787
3788 if (const auto *A = dyn_cast<Argument>(V))
3789 if (std::optional<ConstantRange> Range = A->getRange()) {
3790 const APInt ZeroValue(Range->getBitWidth(), 0);
3791 if (!Range->contains(ZeroValue))
3792 return true;
3793 }
3794
3795 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3796 return true;
3797
3798 // Some of the tests below are recursive, so bail out if we hit the limit.
3800 return false;
3801
3802 // Check for pointer simplifications.
3803
3804 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3805 // A byval, inalloca may not be null in a non-default addres space. A
3806 // nonnull argument is assumed never 0.
3807 if (const Argument *A = dyn_cast<Argument>(V)) {
3808 if (((A->hasPassPointeeByValueCopyAttr() &&
3809 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3810 A->hasNonNullAttr()))
3811 return true;
3812 }
3813 }
3814
3815 if (const auto *I = dyn_cast<Operator>(V))
3816 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3817 return true;
3818
3819 if (!isa<Constant>(V) &&
3821 return true;
3822
3823 if (const Value *Stripped = stripNullTest(V))
3824 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3825
3826 return false;
3827}
3828
3830 unsigned Depth) {
3831 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3832 APInt DemandedElts =
3833 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3834 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3835}
3836
3837/// If the pair of operators are the same invertible function, return the
3838/// the operands of the function corresponding to each input. Otherwise,
3839/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3840/// every input value to exactly one output value. This is equivalent to
3841/// saying that Op1 and Op2 are equal exactly when the specified pair of
3842/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3843static std::optional<std::pair<Value*, Value*>>
3845 const Operator *Op2) {
3846 if (Op1->getOpcode() != Op2->getOpcode())
3847 return std::nullopt;
3848
3849 auto getOperands = [&](unsigned OpNum) -> auto {
3850 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3851 };
3852
3853 switch (Op1->getOpcode()) {
3854 default:
3855 break;
3856 case Instruction::Or:
3857 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3858 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3859 break;
3860 [[fallthrough]];
3861 case Instruction::Xor:
3862 case Instruction::Add: {
3863 Value *Other;
3864 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3865 return std::make_pair(Op1->getOperand(1), Other);
3866 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3867 return std::make_pair(Op1->getOperand(0), Other);
3868 break;
3869 }
3870 case Instruction::Sub:
3871 if (Op1->getOperand(0) == Op2->getOperand(0))
3872 return getOperands(1);
3873 if (Op1->getOperand(1) == Op2->getOperand(1))
3874 return getOperands(0);
3875 break;
3876 case Instruction::Mul: {
3877 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3878 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3879 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3880 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3881 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3882 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3883 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3884 break;
3885
3886 // Assume operand order has been canonicalized
3887 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3888 isa<ConstantInt>(Op1->getOperand(1)) &&
3889 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3890 return getOperands(0);
3891 break;
3892 }
3893 case Instruction::Shl: {
3894 // Same as multiplies, with the difference that we don't need to check
3895 // for a non-zero multiply. Shifts always multiply by non-zero.
3896 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3897 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3898 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3899 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3900 break;
3901
3902 if (Op1->getOperand(1) == Op2->getOperand(1))
3903 return getOperands(0);
3904 break;
3905 }
3906 case Instruction::AShr:
3907 case Instruction::LShr: {
3908 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3909 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3910 if (!PEO1->isExact() || !PEO2->isExact())
3911 break;
3912
3913 if (Op1->getOperand(1) == Op2->getOperand(1))
3914 return getOperands(0);
3915 break;
3916 }
3917 case Instruction::SExt:
3918 case Instruction::ZExt:
3919 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3920 return getOperands(0);
3921 break;
3922 case Instruction::PHI: {
3923 const PHINode *PN1 = cast<PHINode>(Op1);
3924 const PHINode *PN2 = cast<PHINode>(Op2);
3925
3926 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3927 // are a single invertible function of the start values? Note that repeated
3928 // application of an invertible function is also invertible
3929 BinaryOperator *BO1 = nullptr;
3930 Value *Start1 = nullptr, *Step1 = nullptr;
3931 BinaryOperator *BO2 = nullptr;
3932 Value *Start2 = nullptr, *Step2 = nullptr;
3933 if (PN1->getParent() != PN2->getParent() ||
3934 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3935 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3936 break;
3937
3939 cast<Operator>(BO2));
3940 if (!Values)
3941 break;
3942
3943 // We have to be careful of mutually defined recurrences here. Ex:
3944 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3945 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3946 // The invertibility of these is complicated, and not worth reasoning
3947 // about (yet?).
3948 if (Values->first != PN1 || Values->second != PN2)
3949 break;
3950
3951 return std::make_pair(Start1, Start2);
3952 }
3953 }
3954 return std::nullopt;
3955}
3956
3957/// Return true if V1 == (binop V2, X), where X is known non-zero.
3958/// Only handle a small subset of binops where (binop V2, X) with non-zero X
3959/// implies V2 != V1.
3960static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
3961 const APInt &DemandedElts,
3962 const SimplifyQuery &Q, unsigned Depth) {
3964 if (!BO)
3965 return false;
3966 switch (BO->getOpcode()) {
3967 default:
3968 break;
3969 case Instruction::Or:
3970 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3971 break;
3972 [[fallthrough]];
3973 case Instruction::Xor:
3974 case Instruction::Add:
3975 Value *Op = nullptr;
3976 if (V2 == BO->getOperand(0))
3977 Op = BO->getOperand(1);
3978 else if (V2 == BO->getOperand(1))
3979 Op = BO->getOperand(0);
3980 else
3981 return false;
3982 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
3983 }
3984 return false;
3985}
3986
3987/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3988/// the multiplication is nuw or nsw.
3989static bool isNonEqualMul(const Value *V1, const Value *V2,
3990 const APInt &DemandedElts, const SimplifyQuery &Q,
3991 unsigned Depth) {
3992 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3993 const APInt *C;
3994 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
3995 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3996 !C->isZero() && !C->isOne() &&
3997 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
3998 }
3999 return false;
4000}
4001
4002/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4003/// the shift is nuw or nsw.
4004static bool isNonEqualShl(const Value *V1, const Value *V2,
4005 const APInt &DemandedElts, const SimplifyQuery &Q,
4006 unsigned Depth) {
4007 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4008 const APInt *C;
4009 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4010 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4011 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4012 }
4013 return false;
4014}
4015
4016static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4017 const APInt &DemandedElts, const SimplifyQuery &Q,
4018 unsigned Depth) {
4019 // Check two PHIs are in same block.
4020 if (PN1->getParent() != PN2->getParent())
4021 return false;
4022
4024 bool UsedFullRecursion = false;
4025 for (const BasicBlock *IncomBB : PN1->blocks()) {
4026 if (!VisitedBBs.insert(IncomBB).second)
4027 continue; // Don't reprocess blocks that we have dealt with already.
4028 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4029 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4030 const APInt *C1, *C2;
4031 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4032 continue;
4033
4034 // Only one pair of phi operands is allowed for full recursion.
4035 if (UsedFullRecursion)
4036 return false;
4037
4039 RecQ.CxtI = IncomBB->getTerminator();
4040 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4041 return false;
4042 UsedFullRecursion = true;
4043 }
4044 return true;
4045}
4046
4047static bool isNonEqualSelect(const Value *V1, const Value *V2,
4048 const APInt &DemandedElts, const SimplifyQuery &Q,
4049 unsigned Depth) {
4050 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4051 if (!SI1)
4052 return false;
4053
4054 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4055 const Value *Cond1 = SI1->getCondition();
4056 const Value *Cond2 = SI2->getCondition();
4057 if (Cond1 == Cond2)
4058 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4059 DemandedElts, Q, Depth + 1) &&
4060 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4061 DemandedElts, Q, Depth + 1);
4062 }
4063 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4064 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4065}
4066
4067// Check to see if A is both a GEP and is the incoming value for a PHI in the
4068// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4069// one of them being the recursive GEP A and the other a ptr at same base and at
4070// the same/higher offset than B we are only incrementing the pointer further in
4071// loop if offset of recursive GEP is greater than 0.
4073 const SimplifyQuery &Q) {
4074 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4075 return false;
4076
4077 auto *GEPA = dyn_cast<GEPOperator>(A);
4078 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4079 return false;
4080
4081 // Handle 2 incoming PHI values with one being a recursive GEP.
4082 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4083 if (!PN || PN->getNumIncomingValues() != 2)
4084 return false;
4085
4086 // Search for the recursive GEP as an incoming operand, and record that as
4087 // Step.
4088 Value *Start = nullptr;
4089 Value *Step = const_cast<Value *>(A);
4090 if (PN->getIncomingValue(0) == Step)
4091 Start = PN->getIncomingValue(1);
4092 else if (PN->getIncomingValue(1) == Step)
4093 Start = PN->getIncomingValue(0);
4094 else
4095 return false;
4096
4097 // Other incoming node base should match the B base.
4098 // StartOffset >= OffsetB && StepOffset > 0?
4099 // StartOffset <= OffsetB && StepOffset < 0?
4100 // Is non-equal if above are true.
4101 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4102 // optimisation to inbounds GEPs only.
4103 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4104 APInt StartOffset(IndexWidth, 0);
4105 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4106 APInt StepOffset(IndexWidth, 0);
4107 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4108
4109 // Check if Base Pointer of Step matches the PHI.
4110 if (Step != PN)
4111 return false;
4112 APInt OffsetB(IndexWidth, 0);
4113 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4114 return Start == B &&
4115 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4116 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4117}
4118
4119static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4120 const SimplifyQuery &Q, unsigned Depth) {
4121 if (!Q.CxtI)
4122 return false;
4123
4124 // Try to infer NonEqual based on information from dominating conditions.
4125 if (Q.DC && Q.DT) {
4126 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4127 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4128 Value *Cond = BI->getCondition();
4129 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4130 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4132 /*LHSIsTrue=*/true, Depth)
4133 .value_or(false))
4134 return true;
4135
4136 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4137 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4139 /*LHSIsTrue=*/false, Depth)
4140 .value_or(false))
4141 return true;
4142 }
4143
4144 return false;
4145 };
4146
4147 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4148 IsKnownNonEqualFromDominatingCondition(V2))
4149 return true;
4150 }
4151
4152 if (!Q.AC)
4153 return false;
4154
4155 // Try to infer NonEqual based on information from assumptions.
4156 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4157 if (!AssumeVH)
4158 continue;
4159 CallInst *I = cast<CallInst>(AssumeVH);
4160
4161 assert(I->getFunction() == Q.CxtI->getFunction() &&
4162 "Got assumption for the wrong function!");
4163 assert(I->getIntrinsicID() == Intrinsic::assume &&
4164 "must be an assume intrinsic");
4165
4166 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4167 /*LHSIsTrue=*/true, Depth)
4168 .value_or(false) &&
4170 return true;
4171 }
4172
4173 return false;
4174}
4175
4176/// Return true if it is known that V1 != V2.
4177static bool isKnownNonEqual(const Value *V1, const Value *V2,
4178 const APInt &DemandedElts, const SimplifyQuery &Q,
4179 unsigned Depth) {
4180 if (V1 == V2)
4181 return false;
4182 if (V1->getType() != V2->getType())
4183 // We can't look through casts yet.
4184 return false;
4185
4187 return false;
4188
4189 // See if we can recurse through (exactly one of) our operands. This
4190 // requires our operation be 1-to-1 and map every input value to exactly
4191 // one output value. Such an operation is invertible.
4192 auto *O1 = dyn_cast<Operator>(V1);
4193 auto *O2 = dyn_cast<Operator>(V2);
4194 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4195 if (auto Values = getInvertibleOperands(O1, O2))
4196 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4197 Depth + 1);
4198
4199 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4200 const PHINode *PN2 = cast<PHINode>(V2);
4201 // FIXME: This is missing a generalization to handle the case where one is
4202 // a PHI and another one isn't.
4203 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4204 return true;
4205 };
4206 }
4207
4208 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4209 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4210 return true;
4211
4212 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4213 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4214 return true;
4215
4216 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4217 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4218 return true;
4219
4220 if (V1->getType()->isIntOrIntVectorTy()) {
4221 // Are any known bits in V1 contradictory to known bits in V2? If V1
4222 // has a known zero where V2 has a known one, they must not be equal.
4223 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4224 if (!Known1.isUnknown()) {
4225 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4226 if (Known1.Zero.intersects(Known2.One) ||
4227 Known2.Zero.intersects(Known1.One))
4228 return true;
4229 }
4230 }
4231
4232 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4233 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4234 return true;
4235
4238 return true;
4239
4240 Value *A, *B;
4241 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4242 // Check PtrToInt type matches the pointer size.
4243 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4245 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4246
4247 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4248 return true;
4249
4250 return false;
4251}
4252
4253/// For vector constants, loop over the elements and find the constant with the
4254/// minimum number of sign bits. Return 0 if the value is not a vector constant
4255/// or if any element was not analyzed; otherwise, return the count for the
4256/// element with the minimum number of sign bits.
4258 const APInt &DemandedElts,
4259 unsigned TyBits) {
4260 const auto *CV = dyn_cast<Constant>(V);
4261 if (!CV || !isa<FixedVectorType>(CV->getType()))
4262 return 0;
4263
4264 unsigned MinSignBits = TyBits;
4265 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4266 for (unsigned i = 0; i != NumElts; ++i) {
4267 if (!DemandedElts[i])
4268 continue;
4269 // If we find a non-ConstantInt, bail out.
4270 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4271 if (!Elt)
4272 return 0;
4273
4274 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4275 }
4276
4277 return MinSignBits;
4278}
4279
4280static unsigned ComputeNumSignBitsImpl(const Value *V,
4281 const APInt &DemandedElts,
4282 const SimplifyQuery &Q, unsigned Depth);
4283
4284static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4285 const SimplifyQuery &Q, unsigned Depth) {
4286 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4287 assert(Result > 0 && "At least one sign bit needs to be present!");
4288 return Result;
4289}
4290
4291/// Return the number of times the sign bit of the register is replicated into
4292/// the other bits. We know that at least 1 bit is always equal to the sign bit
4293/// (itself), but other cases can give us information. For example, immediately
4294/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4295/// other, so we return 3. For vectors, return the number of sign bits for the
4296/// vector element with the minimum number of known sign bits of the demanded
4297/// elements in the vector specified by DemandedElts.
4298static unsigned ComputeNumSignBitsImpl(const Value *V,
4299 const APInt &DemandedElts,
4300 const SimplifyQuery &Q, unsigned Depth) {
4301 Type *Ty = V->getType();
4302#ifndef NDEBUG
4303 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4304
4305 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4306 assert(
4307 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4308 "DemandedElt width should equal the fixed vector number of elements");
4309 } else {
4310 assert(DemandedElts == APInt(1, 1) &&
4311 "DemandedElt width should be 1 for scalars");
4312 }
4313#endif
4314
4315 // We return the minimum number of sign bits that are guaranteed to be present
4316 // in V, so for undef we have to conservatively return 1. We don't have the
4317 // same behavior for poison though -- that's a FIXME today.
4318
4319 Type *ScalarTy = Ty->getScalarType();
4320 unsigned TyBits = ScalarTy->isPointerTy() ?
4321 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4322 Q.DL.getTypeSizeInBits(ScalarTy);
4323
4324 unsigned Tmp, Tmp2;
4325 unsigned FirstAnswer = 1;
4326
4327 // Note that ConstantInt is handled by the general computeKnownBits case
4328 // below.
4329
4331 return 1;
4332
4333 if (auto *U = dyn_cast<Operator>(V)) {
4334 switch (Operator::getOpcode(V)) {
4335 default: break;
4336 case Instruction::BitCast: {
4337 Value *Src = U->getOperand(0);
4338 Type *SrcTy = Src->getType();
4339
4340 // Skip if the source type is not an integer or integer vector type
4341 // This ensures we only process integer-like types
4342 if (!SrcTy->isIntOrIntVectorTy())
4343 break;
4344
4345 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4346
4347 // Bitcast 'large element' scalar/vector to 'small element' vector.
4348 if ((SrcBits % TyBits) != 0)
4349 break;
4350
4351 // Only proceed if the destination type is a fixed-size vector
4352 if (isa<FixedVectorType>(Ty)) {
4353 // Fast case - sign splat can be simply split across the small elements.
4354 // This works for both vector and scalar sources
4355 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4356 if (Tmp == SrcBits)
4357 return TyBits;
4358 }
4359 break;
4360 }
4361 case Instruction::SExt:
4362 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4363 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4364 Tmp;
4365
4366 case Instruction::SDiv: {
4367 const APInt *Denominator;
4368 // sdiv X, C -> adds log(C) sign bits.
4369 if (match(U->getOperand(1), m_APInt(Denominator))) {
4370
4371 // Ignore non-positive denominator.
4372 if (!Denominator->isStrictlyPositive())
4373 break;
4374
4375 // Calculate the incoming numerator bits.
4376 unsigned NumBits =
4377 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4378
4379 // Add floor(log(C)) bits to the numerator bits.
4380 return std::min(TyBits, NumBits + Denominator->logBase2());
4381 }
4382 break;
4383 }
4384
4385 case Instruction::SRem: {
4386 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4387
4388 const APInt *Denominator;
4389 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4390 // positive constant. This let us put a lower bound on the number of sign
4391 // bits.
4392 if (match(U->getOperand(1), m_APInt(Denominator))) {
4393
4394 // Ignore non-positive denominator.
4395 if (Denominator->isStrictlyPositive()) {
4396 // Calculate the leading sign bit constraints by examining the
4397 // denominator. Given that the denominator is positive, there are two
4398 // cases:
4399 //
4400 // 1. The numerator is positive. The result range is [0,C) and
4401 // [0,C) u< (1 << ceilLogBase2(C)).
4402 //
4403 // 2. The numerator is negative. Then the result range is (-C,0] and
4404 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4405 //
4406 // Thus a lower bound on the number of sign bits is `TyBits -
4407 // ceilLogBase2(C)`.
4408
4409 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4410 Tmp = std::max(Tmp, ResBits);
4411 }
4412 }
4413 return Tmp;
4414 }
4415
4416 case Instruction::AShr: {
4417 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4418 // ashr X, C -> adds C sign bits. Vectors too.
4419 const APInt *ShAmt;
4420 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4421 if (ShAmt->uge(TyBits))
4422 break; // Bad shift.
4423 unsigned ShAmtLimited = ShAmt->getZExtValue();
4424 Tmp += ShAmtLimited;
4425 if (Tmp > TyBits) Tmp = TyBits;
4426 }
4427 return Tmp;
4428 }
4429 case Instruction::Shl: {
4430 const APInt *ShAmt;
4431 Value *X = nullptr;
4432 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4433 // shl destroys sign bits.
4434 if (ShAmt->uge(TyBits))
4435 break; // Bad shift.
4436 // We can look through a zext (more or less treating it as a sext) if
4437 // all extended bits are shifted out.
4438 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4439 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4440 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4441 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4442 } else
4443 Tmp =
4444 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4445 if (ShAmt->uge(Tmp))
4446 break; // Shifted all sign bits out.
4447 Tmp2 = ShAmt->getZExtValue();
4448 return Tmp - Tmp2;
4449 }
4450 break;
4451 }
4452 case Instruction::And:
4453 case Instruction::Or:
4454 case Instruction::Xor: // NOT is handled here.
4455 // Logical binary ops preserve the number of sign bits at the worst.
4456 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4457 if (Tmp != 1) {
4458 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4459 FirstAnswer = std::min(Tmp, Tmp2);
4460 // We computed what we know about the sign bits as our first
4461 // answer. Now proceed to the generic code that uses
4462 // computeKnownBits, and pick whichever answer is better.
4463 }
4464 break;
4465
4466 case Instruction::Select: {
4467 // If we have a clamp pattern, we know that the number of sign bits will
4468 // be the minimum of the clamp min/max range.
4469 const Value *X;
4470 const APInt *CLow, *CHigh;
4471 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4472 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4473
4474 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4475 if (Tmp == 1)
4476 break;
4477 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4478 return std::min(Tmp, Tmp2);
4479 }
4480
4481 case Instruction::Add:
4482 // Add can have at most one carry bit. Thus we know that the output
4483 // is, at worst, one more bit than the inputs.
4484 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4485 if (Tmp == 1) break;
4486
4487 // Special case decrementing a value (ADD X, -1):
4488 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4489 if (CRHS->isAllOnesValue()) {
4490 KnownBits Known(TyBits);
4491 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4492
4493 // If the input is known to be 0 or 1, the output is 0/-1, which is
4494 // all sign bits set.
4495 if ((Known.Zero | 1).isAllOnes())
4496 return TyBits;
4497
4498 // If we are subtracting one from a positive number, there is no carry
4499 // out of the result.
4500 if (Known.isNonNegative())
4501 return Tmp;
4502 }
4503
4504 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4505 if (Tmp2 == 1)
4506 break;
4507 return std::min(Tmp, Tmp2) - 1;
4508
4509 case Instruction::Sub:
4510 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4511 if (Tmp2 == 1)
4512 break;
4513
4514 // Handle NEG.
4515 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4516 if (CLHS->isNullValue()) {
4517 KnownBits Known(TyBits);
4518 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4519 // If the input is known to be 0 or 1, the output is 0/-1, which is
4520 // all sign bits set.
4521 if ((Known.Zero | 1).isAllOnes())
4522 return TyBits;
4523
4524 // If the input is known to be positive (the sign bit is known clear),
4525 // the output of the NEG has the same number of sign bits as the
4526 // input.
4527 if (Known.isNonNegative())
4528 return Tmp2;
4529
4530 // Otherwise, we treat this like a SUB.
4531 }
4532
4533 // Sub can have at most one carry bit. Thus we know that the output
4534 // is, at worst, one more bit than the inputs.
4535 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4536 if (Tmp == 1)
4537 break;
4538 return std::min(Tmp, Tmp2) - 1;
4539
4540 case Instruction::Mul: {
4541 // The output of the Mul can be at most twice the valid bits in the
4542 // inputs.
4543 unsigned SignBitsOp0 =
4544 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4545 if (SignBitsOp0 == 1)
4546 break;
4547 unsigned SignBitsOp1 =
4548 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4549 if (SignBitsOp1 == 1)
4550 break;
4551 unsigned OutValidBits =
4552 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4553 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4554 }
4555
4556 case Instruction::PHI: {
4557 const PHINode *PN = cast<PHINode>(U);
4558 unsigned NumIncomingValues = PN->getNumIncomingValues();
4559 // Don't analyze large in-degree PHIs.
4560 if (NumIncomingValues > 4) break;
4561 // Unreachable blocks may have zero-operand PHI nodes.
4562 if (NumIncomingValues == 0) break;
4563
4564 // Take the minimum of all incoming values. This can't infinitely loop
4565 // because of our depth threshold.
4567 Tmp = TyBits;
4568 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4569 if (Tmp == 1) return Tmp;
4570 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4571 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4572 DemandedElts, RecQ, Depth + 1));
4573 }
4574 return Tmp;
4575 }
4576
4577 case Instruction::Trunc: {
4578 // If the input contained enough sign bits that some remain after the
4579 // truncation, then we can make use of that. Otherwise we don't know
4580 // anything.
4581 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4582 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4583 if (Tmp > (OperandTyBits - TyBits))
4584 return Tmp - (OperandTyBits - TyBits);
4585
4586 return 1;
4587 }
4588
4589 case Instruction::ExtractElement:
4590 // Look through extract element. At the moment we keep this simple and
4591 // skip tracking the specific element. But at least we might find
4592 // information valid for all elements of the vector (for example if vector
4593 // is sign extended, shifted, etc).
4594 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4595
4596 case Instruction::ShuffleVector: {
4597 // Collect the minimum number of sign bits that are shared by every vector
4598 // element referenced by the shuffle.
4599 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4600 if (!Shuf) {
4601 // FIXME: Add support for shufflevector constant expressions.
4602 return 1;
4603 }
4604 APInt DemandedLHS, DemandedRHS;
4605 // For undef elements, we don't know anything about the common state of
4606 // the shuffle result.
4607 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4608 return 1;
4609 Tmp = std::numeric_limits<unsigned>::max();
4610 if (!!DemandedLHS) {
4611 const Value *LHS = Shuf->getOperand(0);
4612 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4613 }
4614 // If we don't know anything, early out and try computeKnownBits
4615 // fall-back.
4616 if (Tmp == 1)
4617 break;
4618 if (!!DemandedRHS) {
4619 const Value *RHS = Shuf->getOperand(1);
4620 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4621 Tmp = std::min(Tmp, Tmp2);
4622 }
4623 // If we don't know anything, early out and try computeKnownBits
4624 // fall-back.
4625 if (Tmp == 1)
4626 break;
4627 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4628 return Tmp;
4629 }
4630 case Instruction::Call: {
4631 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4632 switch (II->getIntrinsicID()) {
4633 default:
4634 break;
4635 case Intrinsic::abs:
4636 Tmp =
4637 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4638 if (Tmp == 1)
4639 break;
4640
4641 // Absolute value reduces number of sign bits by at most 1.
4642 return Tmp - 1;
4643 case Intrinsic::smin:
4644 case Intrinsic::smax: {
4645 const APInt *CLow, *CHigh;
4646 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4647 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4648 }
4649 }
4650 }
4651 }
4652 }
4653 }
4654
4655 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4656 // use this information.
4657
4658 // If we can examine all elements of a vector constant successfully, we're
4659 // done (we can't do any better than that). If not, keep trying.
4660 if (unsigned VecSignBits =
4661 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4662 return VecSignBits;
4663
4664 KnownBits Known(TyBits);
4665 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4666
4667 // If we know that the sign bit is either zero or one, determine the number of
4668 // identical bits in the top of the input value.
4669 return std::max(FirstAnswer, Known.countMinSignBits());
4670}
4671
4673 const TargetLibraryInfo *TLI) {
4674 const Function *F = CB.getCalledFunction();
4675 if (!F)
4677
4678 if (F->isIntrinsic())
4679 return F->getIntrinsicID();
4680
4681 // We are going to infer semantics of a library function based on mapping it
4682 // to an LLVM intrinsic. Check that the library function is available from
4683 // this callbase and in this environment.
4684 LibFunc Func;
4685 if (F->hasLocalLinkage() || !TLI || !TLI->getLibFunc(CB, Func) ||
4686 !CB.onlyReadsMemory())
4688
4689 switch (Func) {
4690 default:
4691 break;
4692 case LibFunc_sin:
4693 case LibFunc_sinf:
4694 case LibFunc_sinl:
4695 return Intrinsic::sin;
4696 case LibFunc_cos:
4697 case LibFunc_cosf:
4698 case LibFunc_cosl:
4699 return Intrinsic::cos;
4700 case LibFunc_tan:
4701 case LibFunc_tanf:
4702 case LibFunc_tanl:
4703 return Intrinsic::tan;
4704 case LibFunc_asin:
4705 case LibFunc_asinf:
4706 case LibFunc_asinl:
4707 return Intrinsic::asin;
4708 case LibFunc_acos:
4709 case LibFunc_acosf:
4710 case LibFunc_acosl:
4711 return Intrinsic::acos;
4712 case LibFunc_atan:
4713 case LibFunc_atanf:
4714 case LibFunc_atanl:
4715 return Intrinsic::atan;
4716 case LibFunc_atan2:
4717 case LibFunc_atan2f:
4718 case LibFunc_atan2l:
4719 return Intrinsic::atan2;
4720 case LibFunc_sinh:
4721 case LibFunc_sinhf:
4722 case LibFunc_sinhl:
4723 return Intrinsic::sinh;
4724 case LibFunc_cosh:
4725 case LibFunc_coshf:
4726 case LibFunc_coshl:
4727 return Intrinsic::cosh;
4728 case LibFunc_tanh:
4729 case LibFunc_tanhf:
4730 case LibFunc_tanhl:
4731 return Intrinsic::tanh;
4732 case LibFunc_exp:
4733 case LibFunc_expf:
4734 case LibFunc_expl:
4735 return Intrinsic::exp;
4736 case LibFunc_exp2:
4737 case LibFunc_exp2f:
4738 case LibFunc_exp2l:
4739 return Intrinsic::exp2;
4740 case LibFunc_exp10:
4741 case LibFunc_exp10f:
4742 case LibFunc_exp10l:
4743 return Intrinsic::exp10;
4744 case LibFunc_log:
4745 case LibFunc_logf:
4746 case LibFunc_logl:
4747 return Intrinsic::log;
4748 case LibFunc_log10:
4749 case LibFunc_log10f:
4750 case LibFunc_log10l:
4751 return Intrinsic::log10;
4752 case LibFunc_log2:
4753 case LibFunc_log2f:
4754 case LibFunc_log2l:
4755 return Intrinsic::log2;
4756 case LibFunc_fabs:
4757 case LibFunc_fabsf:
4758 case LibFunc_fabsl:
4759 return Intrinsic::fabs;
4760 case LibFunc_fmin:
4761 case LibFunc_fminf:
4762 case LibFunc_fminl:
4763 return Intrinsic::minnum;
4764 case LibFunc_fmax:
4765 case LibFunc_fmaxf:
4766 case LibFunc_fmaxl:
4767 return Intrinsic::maxnum;
4768 case LibFunc_copysign:
4769 case LibFunc_copysignf:
4770 case LibFunc_copysignl:
4771 return Intrinsic::copysign;
4772 case LibFunc_floor:
4773 case LibFunc_floorf:
4774 case LibFunc_floorl:
4775 return Intrinsic::floor;
4776 case LibFunc_ceil:
4777 case LibFunc_ceilf:
4778 case LibFunc_ceill:
4779 return Intrinsic::ceil;
4780 case LibFunc_trunc:
4781 case LibFunc_truncf:
4782 case LibFunc_truncl:
4783 return Intrinsic::trunc;
4784 case LibFunc_rint:
4785 case LibFunc_rintf:
4786 case LibFunc_rintl:
4787 return Intrinsic::rint;
4788 case LibFunc_nearbyint:
4789 case LibFunc_nearbyintf:
4790 case LibFunc_nearbyintl:
4791 return Intrinsic::nearbyint;
4792 case LibFunc_round:
4793 case LibFunc_roundf:
4794 case LibFunc_roundl:
4795 return Intrinsic::round;
4796 case LibFunc_roundeven:
4797 case LibFunc_roundevenf:
4798 case LibFunc_roundevenl:
4799 return Intrinsic::roundeven;
4800 case LibFunc_pow:
4801 case LibFunc_powf:
4802 case LibFunc_powl:
4803 return Intrinsic::pow;
4804 case LibFunc_sqrt:
4805 case LibFunc_sqrtf:
4806 case LibFunc_sqrtl:
4807 return Intrinsic::sqrt;
4808 }
4809
4811}
4812
4813/// Given an exploded icmp instruction, return true if the comparison only
4814/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4815/// the result of the comparison is true when the input value is signed.
4817 bool &TrueIfSigned) {
4818 switch (Pred) {
4819 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4820 TrueIfSigned = true;
4821 return RHS.isZero();
4822 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4823 TrueIfSigned = true;
4824 return RHS.isAllOnes();
4825 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4826 TrueIfSigned = false;
4827 return RHS.isAllOnes();
4828 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4829 TrueIfSigned = false;
4830 return RHS.isZero();
4831 case ICmpInst::ICMP_UGT:
4832 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4833 TrueIfSigned = true;
4834 return RHS.isMaxSignedValue();
4835 case ICmpInst::ICMP_UGE:
4836 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4837 TrueIfSigned = true;
4838 return RHS.isMinSignedValue();
4839 case ICmpInst::ICMP_ULT:
4840 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4841 TrueIfSigned = false;
4842 return RHS.isMinSignedValue();
4843 case ICmpInst::ICMP_ULE:
4844 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4845 TrueIfSigned = false;
4846 return RHS.isMaxSignedValue();
4847 default:
4848 return false;
4849 }
4850}
4851
4853 bool CondIsTrue,
4854 const Instruction *CxtI,
4855 KnownFPClass &KnownFromContext,
4856 unsigned Depth = 0) {
4857 Value *A, *B;
4859 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4860 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4861 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4862 Depth + 1);
4863 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4864 Depth + 1);
4865 return;
4866 }
4868 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4869 Depth + 1);
4870 return;
4871 }
4872 CmpPredicate Pred;
4873 Value *LHS;
4874 uint64_t ClassVal = 0;
4875 const APFloat *CRHS;
4876 const APInt *RHS;
4877 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4878 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4879 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4880 LHS != V);
4881 if (CmpVal == V)
4882 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4884 m_Specific(V), m_ConstantInt(ClassVal)))) {
4885 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4886 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4887 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4888 m_APInt(RHS)))) {
4889 bool TrueIfSigned;
4890 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4891 return;
4892 if (TrueIfSigned == CondIsTrue)
4893 KnownFromContext.signBitMustBeOne();
4894 else
4895 KnownFromContext.signBitMustBeZero();
4896 }
4897}
4898
4899/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4900/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4901/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4902/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4903/// exponent range is [-149, -2], but the 0 edge case is above this range).
4904static std::tuple<int, int, int>
4906 if (!Q.CxtI || !Q.DC || !Q.DT)
4908
4909 // Intersect the bounds implied by every dominating condition, keeping the
4910 // tightest maximum. A value may participate in multiple compares
4911 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4912 int MaxExp = APFloat::IEK_Inf;
4913 int MaxExpNonZero = APFloat::IEK_Inf;
4914
4915 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4916 CmpPredicate Pred;
4917 const APFloat *LimitC;
4918 if (!match(BI->getCondition(),
4919 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4920 continue;
4921
4922 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4923 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4924 continue;
4925
4926 // If fabs(x) <= K, implies the exponent min exp range.
4927 // if fabs(x) >= K, swap the successor
4928 bool IsLessEqual =
4929 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
4930 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
4931 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
4932
4933 bool KnownStrictlyLess =
4934 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
4935 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
4936
4937 BasicBlockEdge Edge1(BI->getParent(),
4938 BI->getSuccessor(IsLessEqual ? 0 : 1));
4939 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
4940 // frexp returns an exponent one greater than ilogb.
4941 int Exp = ilogb(*LimitC) + 1;
4942
4943 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
4944 // exponent drops by one when K is exact power of two.
4945 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
4946 --Exp;
4947
4948 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
4949 // may exclude.
4950
4951 // TODO: Figure out lower bound to detect no-underflow.
4952 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
4953 MaxExp = std::min(MaxExp, std::max(Exp, 0));
4954 }
4955 }
4956
4957 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
4958}
4959
4961 const SimplifyQuery &Q) {
4962 KnownFPClass KnownFromContext;
4963
4964 if (Q.CC && Q.CC->AffectedValues.contains(V))
4966 KnownFromContext);
4967
4968 if (!Q.CxtI)
4969 return KnownFromContext;
4970
4971 if (Q.DC && Q.DT) {
4972 // Handle dominating conditions.
4973 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4974 Value *Cond = BI->getCondition();
4975
4976 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4977 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
4978 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
4979 KnownFromContext);
4980
4981 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4982 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
4983 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
4984 KnownFromContext);
4985 }
4986 }
4987
4988 if (!Q.AC)
4989 return KnownFromContext;
4990
4991 // Try to restrict the floating-point classes based on information from
4992 // assumptions.
4993 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
4994 if (!AssumeVH)
4995 continue;
4996 CallInst *I = cast<CallInst>(AssumeVH);
4997
4998 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
4999 "Got assumption for the wrong function!");
5000 assert(I->getIntrinsicID() == Intrinsic::assume &&
5001 "must be an assume intrinsic");
5002
5003 if (!isValidAssumeForContext(I, Q))
5004 continue;
5005
5006 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5007 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5008 }
5009
5010 return KnownFromContext;
5011}
5012
5014 Value *Arm, bool Invert,
5015 const SimplifyQuery &SQ,
5016 unsigned Depth) {
5017
5018 KnownFPClass KnownSrc;
5020 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5021 Depth + 1);
5022 KnownSrc = KnownSrc.unionWith(Known);
5023 if (KnownSrc.isUnknown())
5024 return;
5025
5026 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5027 Known = KnownSrc;
5028}
5029
5030void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5031 FPClassTest InterestedClasses, KnownFPClass &Known,
5032 const SimplifyQuery &Q, unsigned Depth);
5033
5035 FPClassTest InterestedClasses,
5036 const SimplifyQuery &Q, unsigned Depth) {
5037 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5038 APInt DemandedElts =
5039 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5040 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5041}
5042
5044 const APInt &DemandedElts,
5045 FPClassTest InterestedClasses,
5047 const SimplifyQuery &Q,
5048 unsigned Depth) {
5049 if ((InterestedClasses &
5051 return;
5052
5053 KnownFPClass KnownSrc;
5054 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5055 KnownSrc, Q, Depth + 1);
5056 Known = KnownFPClass::fptrunc(KnownSrc);
5057}
5058
5060 switch (IID) {
5061 case Intrinsic::minimum:
5063 case Intrinsic::maximum:
5065 case Intrinsic::minimumnum:
5067 case Intrinsic::maximumnum:
5069 case Intrinsic::minnum:
5071 case Intrinsic::maxnum:
5073 default:
5074 llvm_unreachable("not a floating-point min-max intrinsic");
5075 }
5076}
5077
5078/// \return true if this is a floating point value that is known to have a
5079/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5080static bool isAbsoluteValueULEOne(const Value *V) {
5081 // TODO: Handle frexp
5082 // TODO: Other rounding intrinsics?
5083 // TODO: Try computeKnownExponentRangeFromContext
5084
5085 // fabs(x - floor(x)) <= 1
5086 const Value *SubFloorX;
5087 if (match(V, m_FSub(m_Value(SubFloorX),
5089 return true;
5090
5093}
5094
5095void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5096 FPClassTest InterestedClasses, KnownFPClass &Known,
5097 const SimplifyQuery &Q, unsigned Depth) {
5098 assert(Known.isUnknown() && "should not be called with known information");
5099
5100 if (!DemandedElts) {
5101 // No demanded elts, better to assume we don't know anything.
5102 Known.resetAll();
5103 return;
5104 }
5105
5106 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5107
5108 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5109 Known = KnownFPClass(CFP->getValueAPF());
5110 return;
5111 }
5112
5114 Known.KnownFPClasses = fcPosZero;
5115 Known.SignBit = false;
5116 return;
5117 }
5118
5119 if (isa<PoisonValue>(V)) {
5120 Known.KnownFPClasses = fcNone;
5121 Known.SignBit = false;
5122 return;
5123 }
5124
5125 // Try to handle fixed width vector constants
5126 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5127 const Constant *CV = dyn_cast<Constant>(V);
5128 if (VFVTy && CV) {
5129 Known.KnownFPClasses = fcNone;
5130 bool SignBitAllZero = true;
5131 bool SignBitAllOne = true;
5132
5133 // For vectors, verify that each element is not NaN.
5134 unsigned NumElts = VFVTy->getNumElements();
5135 for (unsigned i = 0; i != NumElts; ++i) {
5136 if (!DemandedElts[i])
5137 continue;
5138
5139 Constant *Elt = CV->getAggregateElement(i);
5140 if (!Elt) {
5141 Known = KnownFPClass();
5142 return;
5143 }
5144 if (isa<PoisonValue>(Elt))
5145 continue;
5146 auto *CElt = dyn_cast<ConstantFP>(Elt);
5147 if (!CElt) {
5148 Known = KnownFPClass();
5149 return;
5150 }
5151
5152 const APFloat &C = CElt->getValueAPF();
5153 Known.KnownFPClasses |= C.classify();
5154 if (C.isNegative())
5155 SignBitAllZero = false;
5156 else
5157 SignBitAllOne = false;
5158 }
5159 if (SignBitAllOne != SignBitAllZero)
5160 Known.SignBit = SignBitAllOne;
5161 return;
5162 }
5163
5164 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5165 Known.KnownFPClasses = fcNone;
5166 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5167 Known |= CDS->getElementAsAPFloat(I).classify();
5168 return;
5169 }
5170
5171 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5172 // TODO: Handle complex aggregates
5173 Known.KnownFPClasses = fcNone;
5174 for (const Use &Op : CA->operands()) {
5175 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5176 if (!CFP) {
5177 Known = KnownFPClass();
5178 return;
5179 }
5180
5181 Known |= CFP->getValueAPF().classify();
5182 }
5183
5184 return;
5185 }
5186
5187 FPClassTest KnownNotFromFlags = fcNone;
5188 if (const auto *CB = dyn_cast<CallBase>(V))
5189 KnownNotFromFlags |= CB->getRetNoFPClass();
5190 else if (const auto *Arg = dyn_cast<Argument>(V))
5191 KnownNotFromFlags |= Arg->getNoFPClass();
5192
5193 const Operator *Op = dyn_cast<Operator>(V);
5195 if (FPOp->hasNoNaNs())
5196 KnownNotFromFlags |= fcNan;
5197 if (FPOp->hasNoInfs())
5198 KnownNotFromFlags |= fcInf;
5199 }
5200
5201 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5202 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5203
5204 // We no longer need to find out about these bits from inputs if we can
5205 // assume this from flags/attributes.
5206 InterestedClasses &= ~KnownNotFromFlags;
5207
5208 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5209 Known.knownNot(KnownNotFromFlags);
5210 if (!Known.SignBit && AssumedClasses.SignBit) {
5211 if (*AssumedClasses.SignBit)
5212 Known.signBitMustBeOne();
5213 else
5214 Known.signBitMustBeZero();
5215 }
5216 });
5217
5218 if (!Op)
5219 return;
5220
5221 // All recursive calls that increase depth must come after this.
5223 return;
5224
5225 const unsigned Opc = Op->getOpcode();
5226 switch (Opc) {
5227 case Instruction::FNeg: {
5228 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5229 Known, Q, Depth + 1);
5230 Known.fneg();
5231 break;
5232 }
5233 case Instruction::Select: {
5234 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5235 KnownFPClass Res;
5236 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5237 Depth + 1);
5238 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5239 Depth);
5240 return Res;
5241 };
5242 // Only known if known in both the LHS and RHS.
5243 Known =
5244 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5245 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5246 break;
5247 }
5248 case Instruction::Load: {
5249 const MDNode *NoFPClass =
5250 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5251 if (!NoFPClass)
5252 break;
5253
5254 ConstantInt *MaskVal =
5256 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5257 break;
5258 }
5259 case Instruction::Call: {
5260 const CallInst *II = cast<CallInst>(Op);
5261 const Intrinsic::ID IID = II->getIntrinsicID();
5262 switch (IID) {
5263 case Intrinsic::fabs: {
5264 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5265 // If we only care about the sign bit we don't need to inspect the
5266 // operand.
5267 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5268 InterestedClasses, Known, Q, Depth + 1);
5269 }
5270
5271 Known.fabs();
5272 break;
5273 }
5274 case Intrinsic::copysign: {
5275 KnownFPClass KnownSign;
5276
5277 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5278 Known, Q, Depth + 1);
5279 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5280 KnownSign, Q, Depth + 1);
5281 Known.copysign(KnownSign);
5282 break;
5283 }
5284 case Intrinsic::fma:
5285 case Intrinsic::fmuladd: {
5286 if ((InterestedClasses & fcNegative) == fcNone)
5287 break;
5288
5289 // FIXME: This should check isGuaranteedNotToBeUndef
5290 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5291 KnownFPClass KnownSrc, KnownAddend;
5292 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5293 InterestedClasses, KnownAddend, Q, Depth + 1);
5294 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5295 InterestedClasses, KnownSrc, Q, Depth + 1);
5296
5297 const Function *F = II->getFunction();
5298 const fltSemantics &FltSem =
5299 II->getType()->getScalarType()->getFltSemantics();
5301 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5302
5303 if (KnownNotFromFlags & fcNan) {
5304 KnownSrc.knownNot(fcNan);
5305 KnownAddend.knownNot(fcNan);
5306 }
5307
5308 if (KnownNotFromFlags & fcInf) {
5309 KnownSrc.knownNot(fcInf);
5310 KnownAddend.knownNot(fcInf);
5311 }
5312
5313 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5314 break;
5315 }
5316
5317 KnownFPClass KnownSrc[3];
5318 for (int I = 0; I != 3; ++I) {
5319 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5320 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5321 if (KnownSrc[I].isUnknown())
5322 return;
5323
5324 if (KnownNotFromFlags & fcNan)
5325 KnownSrc[I].knownNot(fcNan);
5326 if (KnownNotFromFlags & fcInf)
5327 KnownSrc[I].knownNot(fcInf);
5328 }
5329
5330 const Function *F = II->getFunction();
5331 const fltSemantics &FltSem =
5332 II->getType()->getScalarType()->getFltSemantics();
5334 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5335 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5336 break;
5337 }
5338 case Intrinsic::sqrt:
5339 case Intrinsic::experimental_constrained_sqrt: {
5340 KnownFPClass KnownSrc;
5341 FPClassTest InterestedSrcs = InterestedClasses;
5342 if (InterestedClasses & fcNan)
5343 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5344
5345 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5346 KnownSrc, Q, Depth + 1);
5347
5349
5350 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5351 if (!HasNSZ) {
5352 const Function *F = II->getFunction();
5353 const fltSemantics &FltSem =
5354 II->getType()->getScalarType()->getFltSemantics();
5355 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5356 }
5357
5358 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5359 if (HasNSZ)
5360 Known.knownNot(fcNegZero);
5361
5362 break;
5363 }
5364 case Intrinsic::sin: {
5365 KnownFPClass KnownSrc;
5366 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5367 KnownSrc, Q, Depth + 1);
5368 Known = KnownFPClass::sin(KnownSrc);
5369 break;
5370 }
5371 case Intrinsic::cos: {
5372 KnownFPClass KnownSrc;
5373 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5374 KnownSrc, Q, Depth + 1);
5375 Known = KnownFPClass::cos(KnownSrc);
5376 break;
5377 }
5378 case Intrinsic::tan: {
5379 KnownFPClass KnownSrc;
5380 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5381 KnownSrc, Q, Depth + 1);
5382 Known = KnownFPClass::tan(KnownSrc);
5383 break;
5384 }
5385 case Intrinsic::sinh: {
5386 KnownFPClass KnownSrc;
5387 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5388 KnownSrc, Q, Depth + 1);
5389 Known = KnownFPClass::sinh(KnownSrc);
5390 break;
5391 }
5392 case Intrinsic::cosh: {
5393 KnownFPClass KnownSrc;
5394 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5395 KnownSrc, Q, Depth + 1);
5396 Known = KnownFPClass::cosh(KnownSrc);
5397 break;
5398 }
5399 case Intrinsic::tanh: {
5400 KnownFPClass KnownSrc;
5401 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5402 KnownSrc, Q, Depth + 1);
5403 Known = KnownFPClass::tanh(KnownSrc);
5404 break;
5405 }
5406 case Intrinsic::asin: {
5407 KnownFPClass KnownSrc;
5408 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5409 KnownSrc, Q, Depth + 1);
5410 Known = KnownFPClass::asin(KnownSrc);
5411 break;
5412 }
5413 case Intrinsic::acos: {
5414 KnownFPClass KnownSrc;
5415 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5416 KnownSrc, Q, Depth + 1);
5417 Known = KnownFPClass::acos(KnownSrc);
5418 break;
5419 }
5420 case Intrinsic::atan: {
5421 KnownFPClass KnownSrc;
5422 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5423 KnownSrc, Q, Depth + 1);
5424 Known = KnownFPClass::atan(KnownSrc);
5425 break;
5426 }
5427 case Intrinsic::atan2: {
5428 KnownFPClass KnownLHS, KnownRHS;
5429 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5430 KnownLHS, Q, Depth + 1);
5431 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5432 KnownRHS, Q, Depth + 1);
5433 Known = KnownFPClass::atan2(KnownLHS, KnownRHS);
5434 break;
5435 }
5436 case Intrinsic::maxnum:
5437 case Intrinsic::minnum:
5438 case Intrinsic::minimum:
5439 case Intrinsic::maximum:
5440 case Intrinsic::minimumnum:
5441 case Intrinsic::maximumnum: {
5442 KnownFPClass KnownLHS, KnownRHS;
5443 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5444 KnownLHS, Q, Depth + 1);
5445 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5446 KnownRHS, Q, Depth + 1);
5447
5448 const Function *F = II->getFunction();
5449
5451 F ? F->getDenormalMode(
5452 II->getType()->getScalarType()->getFltSemantics())
5454
5455 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5456 Mode);
5457 break;
5458 }
5459 case Intrinsic::canonicalize: {
5460 KnownFPClass KnownSrc;
5461 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5462 KnownSrc, Q, Depth + 1);
5463
5464 const Function *F = II->getFunction();
5465 DenormalMode DenormMode =
5466 F ? F->getDenormalMode(
5467 II->getType()->getScalarType()->getFltSemantics())
5469 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5470 break;
5471 }
5472 case Intrinsic::vector_reduce_fmax:
5473 case Intrinsic::vector_reduce_fmin:
5474 case Intrinsic::vector_reduce_fmaximum:
5475 case Intrinsic::vector_reduce_fminimum: {
5476 // reduce min/max will choose an element from one of the vector elements,
5477 // so we can infer and class information that is common to all elements.
5478 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5479 InterestedClasses, Q, Depth + 1);
5480 // Can only propagate sign if output is never NaN.
5481 if (!Known.isKnownNeverNaN())
5482 Known.SignBit.reset();
5483 break;
5484 }
5485 // reverse preserves all characteristics of the input vec's element.
5486 case Intrinsic::vector_reverse:
5488 II->getArgOperand(0), DemandedElts.reverseBits(),
5489 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5490 break;
5491 case Intrinsic::trunc:
5492 case Intrinsic::floor:
5493 case Intrinsic::ceil:
5494 case Intrinsic::rint:
5495 case Intrinsic::nearbyint:
5496 case Intrinsic::round:
5497 case Intrinsic::roundeven: {
5498 KnownFPClass KnownSrc;
5499 FPClassTest InterestedSrcs = InterestedClasses;
5500 if (InterestedSrcs & fcPosFinite)
5501 InterestedSrcs |= fcPosFinite;
5502 if (InterestedSrcs & fcNegFinite)
5503 InterestedSrcs |= fcNegFinite;
5504 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5505 KnownSrc, Q, Depth + 1);
5506
5508 KnownSrc, IID == Intrinsic::trunc,
5509 V->getType()->getScalarType()->isMultiUnitFPType());
5510 break;
5511 }
5512 case Intrinsic::exp:
5513 case Intrinsic::exp2:
5514 case Intrinsic::exp10:
5515 case Intrinsic::amdgcn_exp2: {
5516 KnownFPClass KnownSrc;
5517 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5518 KnownSrc, Q, Depth + 1);
5519
5520 Known = KnownFPClass::exp(KnownSrc);
5521
5522 Type *EltTy = II->getType()->getScalarType();
5523 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5524 Known.knownNot(fcSubnormal);
5525
5526 break;
5527 }
5528 case Intrinsic::fptrunc_round: {
5529 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5530 Q, Depth);
5531 break;
5532 }
5533 case Intrinsic::log:
5534 case Intrinsic::log10:
5535 case Intrinsic::log2:
5536 case Intrinsic::experimental_constrained_log:
5537 case Intrinsic::experimental_constrained_log10:
5538 case Intrinsic::experimental_constrained_log2:
5539 case Intrinsic::amdgcn_log: {
5540 Type *EltTy = II->getType()->getScalarType();
5541
5542 // log(+inf) -> +inf
5543 // log([+-]0.0) -> -inf
5544 // log(-inf) -> nan
5545 // log(-x) -> nan
5546 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5547 FPClassTest InterestedSrcs = InterestedClasses;
5548 if ((InterestedClasses & fcNegInf) != fcNone)
5549 InterestedSrcs |= fcZero | fcSubnormal;
5550 if ((InterestedClasses & fcNan) != fcNone)
5551 InterestedSrcs |= fcNan | fcNegative;
5552
5553 KnownFPClass KnownSrc;
5554 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5555 KnownSrc, Q, Depth + 1);
5556
5557 const Function *F = II->getFunction();
5558 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5560 Known = KnownFPClass::log(KnownSrc, Mode);
5561 }
5562
5563 break;
5564 }
5565 case Intrinsic::powi: {
5566 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5567 break;
5568
5569 // The exponent is always a scalar, even when raising a vector to a power.
5570 const Value *Exp = II->getArgOperand(1);
5571 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5572 KnownBits ExponentKnownBits(BitWidth);
5573 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5574
5575 FPClassTest InterestedSrcs = fcNone;
5576 if (InterestedClasses & fcNan)
5577 InterestedSrcs |= fcNan;
5578 if (!ExponentKnownBits.isZero()) {
5579 if (InterestedClasses & fcInf)
5580 InterestedSrcs |= fcFinite | fcInf;
5581 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5582 InterestedSrcs |= fcNegative;
5583 }
5584
5585 KnownFPClass KnownSrc;
5586 if (InterestedSrcs != fcNone)
5587 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5588 KnownSrc, Q, Depth + 1);
5589
5590 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5591 break;
5592 }
5593 case Intrinsic::ldexp: {
5594 KnownFPClass KnownSrc;
5595 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5596 KnownSrc, Q, Depth + 1);
5597 // Can refine inf/zero handling based on the exponent operand.
5598 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5599
5600 const Value *ExpArg = II->getArgOperand(1);
5601 ConstantRange ExpKnownRange =
5602 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5603 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5604 : ConstantRange::getFull(
5605 ExpArg->getType()->getScalarSizeInBits());
5606
5607 const fltSemantics &Flt =
5608 II->getType()->getScalarType()->getFltSemantics();
5609
5610 const Function *F = II->getFunction();
5612 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5613
5614 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5615 ExpKnownRange.getSignedMax(), Flt, Mode);
5616 break;
5617 }
5618 case Intrinsic::arithmetic_fence: {
5619 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5620 Known, Q, Depth + 1);
5621 break;
5622 }
5623 case Intrinsic::experimental_constrained_sitofp:
5624 case Intrinsic::experimental_constrained_uitofp:
5625 // Cannot produce nan
5626 Known.knownNot(fcNan);
5627
5628 // sitofp and uitofp turn into +0.0 for zero.
5629 Known.knownNot(fcNegZero);
5630
5631 // Integers cannot be subnormal
5632 Known.knownNot(fcSubnormal);
5633
5634 if (IID == Intrinsic::experimental_constrained_uitofp)
5635 Known.signBitMustBeZero();
5636
5637 // TODO: Copy inf handling from instructions
5638 break;
5639
5640 case Intrinsic::amdgcn_fract: {
5641 Known.knownNot(fcInf);
5642
5643 if (InterestedClasses & fcNan) {
5644 KnownFPClass KnownSrc;
5645 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5646 InterestedClasses, KnownSrc, Q, Depth + 1);
5647
5648 if (KnownSrc.isKnownNeverInfOrNaN())
5649 Known.knownNot(fcNan);
5650 else if (KnownSrc.isKnownNever(fcSNan))
5651 Known.knownNot(fcSNan);
5652 }
5653
5654 break;
5655 }
5656 case Intrinsic::amdgcn_rcp: {
5657 KnownFPClass KnownSrc;
5658 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5659 KnownSrc, Q, Depth + 1);
5660
5661 Known.propagateNaN(KnownSrc);
5662
5663 Type *EltTy = II->getType()->getScalarType();
5664
5665 // f32 denormal always flushed.
5666 if (EltTy->isFloatTy()) {
5667 Known.knownNot(fcSubnormal);
5668 KnownSrc.knownNot(fcSubnormal);
5669 }
5670
5671 if (KnownSrc.isKnownNever(fcNegative))
5672 Known.knownNot(fcNegative);
5673 if (KnownSrc.isKnownNever(fcPositive))
5674 Known.knownNot(fcPositive);
5675
5676 if (const Function *F = II->getFunction()) {
5677 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5678 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5679 Known.knownNot(fcPosInf);
5680 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5681 Known.knownNot(fcNegInf);
5682 }
5683
5684 break;
5685 }
5686 case Intrinsic::amdgcn_rsq: {
5687 KnownFPClass KnownSrc;
5688 // The only negative value that can be returned is -inf for -0 inputs.
5690
5691 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5692 KnownSrc, Q, Depth + 1);
5693
5694 // Negative -> nan
5695 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5696 Known.knownNot(fcNan);
5697 else if (KnownSrc.isKnownNever(fcSNan))
5698 Known.knownNot(fcSNan);
5699
5700 // +inf -> +0
5701 if (KnownSrc.isKnownNeverPosInfinity())
5702 Known.knownNot(fcPosZero);
5703
5704 Type *EltTy = II->getType()->getScalarType();
5705
5706 // f32 denormal always flushed.
5707 if (EltTy->isFloatTy())
5708 Known.knownNot(fcPosSubnormal);
5709
5710 if (const Function *F = II->getFunction()) {
5711 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5712
5713 // -0 -> -inf
5714 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5715 Known.knownNot(fcNegInf);
5716
5717 // +0 -> +inf
5718 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5719 Known.knownNot(fcPosInf);
5720 }
5721
5722 break;
5723 }
5724 case Intrinsic::amdgcn_trig_preop: {
5725 // Always returns a value [0, 1)
5726 Known.knownNot(fcNan | fcInf | fcNegative);
5727 break;
5728 }
5729 case Intrinsic::convert_from_arbitrary_fp: {
5730 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5731 StringRef FormatStr = cast<MDString>(MD)->getString();
5732
5733 const fltSemantics *SrcSemantics =
5735 if (!SrcSemantics)
5736 break;
5737
5738 const fltSemantics DstSemantics =
5739 II->getType()->getScalarType()->getFltSemantics();
5740
5741 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5742 Known.knownNot(fcNan);
5743
5744 // fcInf can only be cleared if the source format has no Inf encoding
5745 // and the dst max exp can accommodate src max exp.
5746 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5747 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5748 APFloat::semanticsMaxExponent(DstSemantics))
5749 Known.knownNot(fcInf);
5750
5751 // Check and clear all neg flags for formats that do not have signed
5752 // representation.
5753 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5754 Known.knownNot(fcNegative);
5755
5756 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5757 // zero.
5758 if (!APFloat::semanticsHasZero(*SrcSemantics))
5759 Known.knownNot(fcZero);
5760 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5761 Known.knownNot(fcNegZero);
5762
5763 // If src lands normally in dest, the result can never be subnormal.
5764 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5765 Known.knownNot(fcSubnormal);
5766 break;
5767 }
5768 default:
5769 break;
5770 }
5771
5772 break;
5773 }
5774 case Instruction::FAdd:
5775 case Instruction::FSub: {
5776 KnownFPClass KnownLHS, KnownRHS;
5777 bool WantNegative =
5778 Op->getOpcode() == Instruction::FAdd &&
5779 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5780 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5781 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5782
5783 if (!WantNaN && !WantNegative && !WantNegZero)
5784 break;
5785
5786 FPClassTest InterestedSrcs = InterestedClasses;
5787 if (WantNegative)
5788 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5789 if (InterestedClasses & fcNan)
5790 InterestedSrcs |= fcInf;
5791 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5792 KnownRHS, Q, Depth + 1);
5793
5794 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5795 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5796 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5797 Depth + 1);
5798 if (Self)
5799 KnownLHS = KnownRHS;
5800
5801 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5802 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5803 WantNegZero || Opc == Instruction::FSub) {
5804
5805 // FIXME: Context function should always be passed in separately
5806 const Function *F = cast<Instruction>(Op)->getFunction();
5807 const fltSemantics &FltSem =
5808 Op->getType()->getScalarType()->getFltSemantics();
5810 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5811
5812 if (Self && Opc == Instruction::FAdd) {
5813 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5814 } else {
5815 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5816 // there's no point.
5817
5818 if (!Self) {
5819 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5820 KnownLHS, Q, Depth + 1);
5821 }
5822
5823 Known = Opc == Instruction::FAdd
5824 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5825 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5826 }
5827 }
5828
5829 break;
5830 }
5831 case Instruction::FMul: {
5832 const Function *F = cast<Instruction>(Op)->getFunction();
5834 F ? F->getDenormalMode(
5835 Op->getType()->getScalarType()->getFltSemantics())
5837
5838 Value *LHS = Op->getOperand(0);
5839 Value *RHS = Op->getOperand(1);
5840 // X * X is always non-negative or a NaN.
5841 // FIXME: Should check isGuaranteedNotToBeUndef
5842 if (LHS == RHS) {
5843 KnownFPClass KnownSrc;
5844 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5845 Depth + 1);
5846 Known = KnownFPClass::square(KnownSrc, Mode);
5847 break;
5848 }
5849
5850 KnownFPClass KnownLHS, KnownRHS;
5851
5852 const APFloat *CRHS;
5853 if (match(RHS, m_APFloat(CRHS))) {
5854 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5855 Depth + 1);
5856 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5857 } else {
5858 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5859 Depth + 1);
5860 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5861 // additional not-nan if the addend is known-not negative infinity if the
5862 // multiply is known-not infinity.
5863
5864 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5865 Depth + 1);
5866 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5867 }
5868
5869 /// Propgate no-infs if the other source is known smaller than one, such
5870 /// that this cannot introduce overflow.
5871 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5872 Known.knownNot(fcInf);
5873 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5874 Known.knownNot(fcInf);
5875
5876 break;
5877 }
5878 case Instruction::FDiv:
5879 case Instruction::FRem: {
5880 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5881
5882 if (Op->getOpcode() == Instruction::FRem)
5883 Known.knownNot(fcInf);
5884
5885 if (Op->getOperand(0) == Op->getOperand(1) &&
5886 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5887 if (Op->getOpcode() == Instruction::FDiv) {
5888 // X / X is always exactly 1.0 or a NaN.
5889 Known.KnownFPClasses = fcNan | fcPosNormal;
5890 } else {
5891 // X % X is always exactly [+-]0.0 or a NaN.
5892 Known.KnownFPClasses = fcNan | fcZero;
5893 }
5894
5895 if (!WantNan)
5896 break;
5897
5898 KnownFPClass KnownSrc;
5899 computeKnownFPClass(Op->getOperand(0), DemandedElts,
5900 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
5901 Depth + 1);
5902 const Function *F = cast<Instruction>(Op)->getFunction();
5903 const fltSemantics &FltSem =
5904 Op->getType()->getScalarType()->getFltSemantics();
5905
5907 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5908
5909 Known = Op->getOpcode() == Instruction::FDiv
5910 ? KnownFPClass::fdiv_self(KnownSrc, Mode)
5911 : KnownFPClass::frem_self(KnownSrc, Mode);
5912 break;
5913 }
5914
5915 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5916 const bool WantPositive =
5917 Opc == Instruction::FRem && (InterestedClasses & fcPositive) != fcNone;
5918 if (!WantNan && !WantNegative && !WantPositive)
5919 break;
5920
5921 KnownFPClass KnownLHS, KnownRHS;
5922
5923 computeKnownFPClass(Op->getOperand(1), DemandedElts,
5924 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
5925 Depth + 1);
5926
5927 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
5928 KnownRHS.isKnownNever(fcNegative) ||
5929 KnownRHS.isKnownNever(fcPositive);
5930
5931 if (KnowSomethingUseful || WantPositive) {
5932 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
5933 Q, Depth + 1);
5934 }
5935
5936 const Function *F = cast<Instruction>(Op)->getFunction();
5937 const fltSemantics &FltSem =
5938 Op->getType()->getScalarType()->getFltSemantics();
5939
5940 if (Op->getOpcode() == Instruction::FDiv) {
5942 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5943 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
5944 } else {
5945 // Inf REM x and x REM 0 produce NaN.
5946 if (KnownLHS.isKnownNeverNaN() && KnownRHS.isKnownNeverNaN() &&
5947 KnownLHS.isKnownNeverInfinity() && F &&
5948 KnownRHS.isKnownNeverLogicalZero(F->getDenormalMode(FltSem))) {
5949 Known.knownNot(fcNan);
5950 }
5951
5952 // The sign for frem is the same as the first operand.
5953 if (KnownLHS.cannotBeOrderedLessThanZero())
5955 if (KnownLHS.cannotBeOrderedGreaterThanZero())
5957
5958 // See if we can be more aggressive about the sign of 0.
5959 if (KnownLHS.isKnownNever(fcNegative))
5960 Known.knownNot(fcNegative);
5961 if (KnownLHS.isKnownNever(fcPositive))
5962 Known.knownNot(fcPositive);
5963 }
5964
5965 break;
5966 }
5967 case Instruction::FPExt: {
5968 KnownFPClass KnownSrc;
5969 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5970 KnownSrc, Q, Depth + 1);
5971
5972 const fltSemantics &DstTy =
5973 Op->getType()->getScalarType()->getFltSemantics();
5974 const fltSemantics &SrcTy =
5975 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
5976
5977 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
5978 break;
5979 }
5980 case Instruction::FPTrunc: {
5981 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
5982 Depth);
5983 break;
5984 }
5985 case Instruction::SIToFP:
5986 case Instruction::UIToFP: {
5987 // Cannot produce nan
5988 Known.knownNot(fcNan);
5989
5990 // Integers cannot be subnormal
5991 Known.knownNot(fcSubnormal);
5992
5993 // sitofp and uitofp turn into +0.0 for zero.
5994 Known.knownNot(fcNegZero);
5995
5996 // UIToFP is always non-negative regardless of known bits.
5997 if (Op->getOpcode() == Instruction::UIToFP)
5998 Known.signBitMustBeZero();
5999
6000 // Only compute known bits if we can learn something useful from them.
6001 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6002 break;
6003
6004 KnownBits IntKnown =
6005 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6006
6007 // If the integer is non-zero, the result cannot be +0.0
6008 if (IntKnown.isNonZero())
6009 Known.knownNot(fcPosZero);
6010
6011 if (Op->getOpcode() == Instruction::SIToFP) {
6012 // If the signed integer is known non-negative, the result is
6013 // non-negative. If the signed integer is known negative, the result is
6014 // negative.
6015 if (IntKnown.isNonNegative()) {
6016 Known.signBitMustBeZero();
6017 } else if (IntKnown.isNegative()) {
6018 Known.signBitMustBeOne();
6019 }
6020 }
6021
6022 // Guard kept for ilogb()
6023 if (InterestedClasses & fcInf) {
6024 // Get width of largest magnitude integer known.
6025 // This still works for a signed minimum value because the largest FP
6026 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6027 int IntSize = IntKnown.getBitWidth();
6028 if (Op->getOpcode() == Instruction::UIToFP)
6029 IntSize -= IntKnown.countMinLeadingZeros();
6030 else if (Op->getOpcode() == Instruction::SIToFP)
6031 IntSize -= IntKnown.countMinSignBits();
6032
6033 // If the exponent of the largest finite FP value can hold the largest
6034 // integer, the result of the cast must be finite.
6035 Type *FPTy = Op->getType()->getScalarType();
6036 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6037 Known.knownNot(fcInf);
6038 }
6039
6040 break;
6041 }
6042 case Instruction::ExtractElement: {
6043 // Look through extract element. If the index is non-constant or
6044 // out-of-range demand all elements, otherwise just the extracted element.
6045 const Value *Vec = Op->getOperand(0);
6046
6047 APInt DemandedVecElts;
6048 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6049 unsigned NumElts = VecTy->getNumElements();
6050 DemandedVecElts = APInt::getAllOnes(NumElts);
6051 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6052 if (CIdx && CIdx->getValue().ult(NumElts))
6053 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6054 } else {
6055 DemandedVecElts = APInt(1, 1);
6056 }
6057
6058 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6059 Q, Depth + 1);
6060 }
6061 case Instruction::InsertElement: {
6062 if (isa<ScalableVectorType>(Op->getType()))
6063 return;
6064
6065 const Value *Vec = Op->getOperand(0);
6066 const Value *Elt = Op->getOperand(1);
6067 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6068 unsigned NumElts = DemandedElts.getBitWidth();
6069 APInt DemandedVecElts = DemandedElts;
6070 bool NeedsElt = true;
6071 // If we know the index we are inserting to, clear it from Vec check.
6072 if (CIdx && CIdx->getValue().ult(NumElts)) {
6073 DemandedVecElts.clearBit(CIdx->getZExtValue());
6074 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6075 }
6076
6077 // Do we demand the inserted element?
6078 if (NeedsElt) {
6079 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6080 // If we don't know any bits, early out.
6081 if (Known.isUnknown())
6082 break;
6083 } else {
6084 Known.KnownFPClasses = fcNone;
6085 }
6086
6087 // Do we need anymore elements from Vec?
6088 if (!DemandedVecElts.isZero()) {
6089 KnownFPClass Known2;
6090 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6091 Depth + 1);
6092 Known |= Known2;
6093 }
6094
6095 break;
6096 }
6097 case Instruction::ShuffleVector: {
6098 // Handle vector splat idiom
6099 if (Value *Splat = getSplatValue(V)) {
6100 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6101 break;
6102 }
6103
6104 // For undef elements, we don't know anything about the common state of
6105 // the shuffle result.
6106 APInt DemandedLHS, DemandedRHS;
6107 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6108 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6109 return;
6110
6111 if (!!DemandedLHS) {
6112 const Value *LHS = Shuf->getOperand(0);
6113 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6114 Depth + 1);
6115
6116 // If we don't know any bits, early out.
6117 if (Known.isUnknown())
6118 break;
6119 } else {
6120 Known.KnownFPClasses = fcNone;
6121 }
6122
6123 if (!!DemandedRHS) {
6124 KnownFPClass Known2;
6125 const Value *RHS = Shuf->getOperand(1);
6126 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6127 Depth + 1);
6128 Known |= Known2;
6129 }
6130
6131 break;
6132 }
6133 case Instruction::ExtractValue: {
6134 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6135 ArrayRef<unsigned> Indices = Extract->getIndices();
6136 const Value *Src = Extract->getAggregateOperand();
6137 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6138 Indices[0] == 0) {
6139 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6140 switch (II->getIntrinsicID()) {
6141 case Intrinsic::frexp: {
6142 Known.knownNot(fcSubnormal);
6143
6144 KnownFPClass KnownSrc;
6145 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6146 InterestedClasses, KnownSrc, Q, Depth + 1);
6147
6148 const Function *F = cast<Instruction>(Op)->getFunction();
6149 const fltSemantics &FltSem =
6150 Op->getType()->getScalarType()->getFltSemantics();
6151
6153 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6154 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6155 return;
6156 }
6157 default:
6158 break;
6159 }
6160 }
6161 }
6162
6163 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6164 Depth + 1);
6165 break;
6166 }
6167 case Instruction::PHI: {
6168 const PHINode *P = cast<PHINode>(Op);
6169 // Unreachable blocks may have zero-operand PHI nodes.
6170 if (P->getNumIncomingValues() == 0)
6171 break;
6172
6173 // Otherwise take the unions of the known bit sets of the operands,
6174 // taking conservative care to avoid excessive recursion.
6175 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6176
6177 if (Depth < PhiRecursionLimit) {
6178 // Skip if every incoming value references to ourself.
6179 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6180 break;
6181
6182 bool First = true;
6183
6184 for (const Use &U : P->operands()) {
6185 Value *IncValue;
6186 Instruction *CxtI;
6187 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6188 // Skip direct self references.
6189 if (IncValue == P)
6190 continue;
6191
6192 KnownFPClass KnownSrc;
6193 // Recurse, but cap the recursion to two levels, because we don't want
6194 // to waste time spinning around in loops. We need at least depth 2 to
6195 // detect known sign bits.
6196 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6198 PhiRecursionLimit);
6199
6200 if (First) {
6201 Known = KnownSrc;
6202 First = false;
6203 } else {
6204 Known |= KnownSrc;
6205 }
6206
6207 if (Known.KnownFPClasses == fcAllFlags)
6208 break;
6209 }
6210 }
6211
6212 // Look for the case of a for loop which has a positive
6213 // initial value and is incremented by a squared value.
6214 // This will propagate sign information out of such loops.
6215 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6216 break;
6217 for (unsigned I = 0; I < 2; I++) {
6218 Value *RecurValue = P->getIncomingValue(1 - I);
6220 if (!II)
6221 continue;
6222 Value *R, *L, *Init;
6223 PHINode *PN;
6225 PN == P) {
6226 switch (II->getIntrinsicID()) {
6227 case Intrinsic::fma:
6228 case Intrinsic::fmuladd: {
6229 KnownFPClass KnownStart;
6230 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6231 Q, Depth + 1);
6232 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6233 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6235 break;
6236 }
6237 }
6238 }
6239 }
6240 break;
6241 }
6242 case Instruction::BitCast: {
6243 const Value *Src;
6244 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6245 !Src->getType()->isIntOrIntVectorTy())
6246 break;
6247
6248 const Type *Ty = Op->getType();
6249
6250 Value *CastLHS, *CastRHS;
6251
6252 // Match bitcast(umax(bitcast(a), bitcast(b)))
6253 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6254 m_BitCast(m_Value(CastRHS)))) &&
6255 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6256 KnownFPClass KnownLHS, KnownRHS;
6257 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6258 Depth + 1);
6259 if (!KnownRHS.isUnknown()) {
6260 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6261 Q, Depth + 1);
6262 Known = KnownLHS | KnownRHS;
6263 }
6264
6265 return;
6266 }
6267
6268 const Type *EltTy = Ty->getScalarType();
6269 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6270 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6271
6273 break;
6274 }
6275 default:
6276 break;
6277 }
6278}
6279
6281 const APInt &DemandedElts,
6282 FPClassTest InterestedClasses,
6283 const SimplifyQuery &SQ,
6284 unsigned Depth) {
6285 KnownFPClass KnownClasses;
6286 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6287 Depth);
6288 return KnownClasses;
6289}
6290
6292 FPClassTest InterestedClasses,
6293 const SimplifyQuery &SQ,
6294 unsigned Depth) {
6296 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6297 return Known;
6298}
6299
6301 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6302 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6303 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6304 return computeKnownFPClass(V, InterestedClasses,
6305 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6306 Depth);
6307}
6308
6310llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6311 FastMathFlags FMF, FPClassTest InterestedClasses,
6312 const SimplifyQuery &SQ, unsigned Depth) {
6313 if (FMF.noNaNs())
6314 InterestedClasses &= ~fcNan;
6315 if (FMF.noInfs())
6316 InterestedClasses &= ~fcInf;
6317
6318 KnownFPClass Result =
6319 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6320
6321 if (FMF.noNaNs())
6322 Result.KnownFPClasses &= ~fcNan;
6323 if (FMF.noInfs())
6324 Result.KnownFPClasses &= ~fcInf;
6325 return Result;
6326}
6327
6329 FPClassTest InterestedClasses,
6330 const SimplifyQuery &SQ,
6331 unsigned Depth) {
6332 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6333 APInt DemandedElts =
6334 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6335 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6336 Depth);
6337}
6338
6340 unsigned Depth) {
6342 return Known.isKnownNeverNegZero();
6343}
6344
6346 unsigned Depth) {
6349 return Known.cannotBeOrderedLessThanZero();
6350}
6351
6353 unsigned Depth) {
6355 return Known.isKnownNeverInfinity();
6356}
6357
6358/// Return true if the floating-point value can never contain a NaN or infinity.
6360 unsigned Depth) {
6362 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6363}
6364
6365/// Return true if the floating-point scalar value is not a NaN or if the
6366/// floating-point vector value has no NaN elements. Return false if a value
6367/// could ever be NaN.
6369 unsigned Depth) {
6371 return Known.isKnownNeverNaN();
6372}
6373
6374/// Return false if we can prove that the specified FP value's sign bit is 0.
6375/// Return true if we can prove that the specified FP value's sign bit is 1.
6376/// Otherwise return std::nullopt.
6377std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6378 const SimplifyQuery &SQ,
6379 unsigned Depth) {
6381 return Known.SignBit;
6382}
6383
6385 auto *User = cast<Instruction>(U.getUser());
6386 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6387 if (FPOp->hasNoSignedZeros())
6388 return true;
6389 }
6390
6391 switch (User->getOpcode()) {
6392 case Instruction::FPToSI:
6393 case Instruction::FPToUI:
6394 return true;
6395 case Instruction::FCmp:
6396 // fcmp treats both positive and negative zero as equal.
6397 return true;
6398 case Instruction::Call:
6399 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6400 switch (II->getIntrinsicID()) {
6401 case Intrinsic::fabs:
6402 return true;
6403 case Intrinsic::copysign:
6404 return U.getOperandNo() == 0;
6405 case Intrinsic::is_fpclass:
6406 case Intrinsic::vp_is_fpclass: {
6407 auto Test =
6408 static_cast<FPClassTest>(
6409 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6412 }
6413 default:
6414 return false;
6415 }
6416 }
6417 return false;
6418 default:
6419 return false;
6420 }
6421}
6422
6424 auto *User = cast<Instruction>(U.getUser());
6425 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6426 if (FPOp->hasNoNaNs())
6427 return true;
6428 }
6429
6430 switch (User->getOpcode()) {
6431 case Instruction::FPToSI:
6432 case Instruction::FPToUI:
6433 return true;
6434 // Proper FP math operations ignore the sign bit of NaN.
6435 case Instruction::FAdd:
6436 case Instruction::FSub:
6437 case Instruction::FMul:
6438 case Instruction::FDiv:
6439 case Instruction::FRem:
6440 case Instruction::FPTrunc:
6441 case Instruction::FPExt:
6442 case Instruction::FCmp:
6443 return true;
6444 // Bitwise FP operations should preserve the sign bit of NaN.
6445 case Instruction::FNeg:
6446 case Instruction::Select:
6447 case Instruction::PHI:
6448 return false;
6449 case Instruction::Ret:
6450 return User->getFunction()->getAttributes().getRetNoFPClass() &
6452 case Instruction::Call:
6453 case Instruction::Invoke: {
6454 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6455 switch (II->getIntrinsicID()) {
6456 case Intrinsic::fabs:
6457 return true;
6458 case Intrinsic::copysign:
6459 return U.getOperandNo() == 0;
6460 // Other proper FP math intrinsics ignore the sign bit of NaN.
6461 case Intrinsic::maxnum:
6462 case Intrinsic::minnum:
6463 case Intrinsic::maximum:
6464 case Intrinsic::minimum:
6465 case Intrinsic::maximumnum:
6466 case Intrinsic::minimumnum:
6467 case Intrinsic::canonicalize:
6468 case Intrinsic::fma:
6469 case Intrinsic::fmuladd:
6470 case Intrinsic::sqrt:
6471 case Intrinsic::pow:
6472 case Intrinsic::powi:
6473 case Intrinsic::fptoui_sat:
6474 case Intrinsic::fptosi_sat:
6475 case Intrinsic::is_fpclass:
6476 case Intrinsic::vp_is_fpclass:
6477 return true;
6478 default:
6479 return false;
6480 }
6481 }
6482
6483 FPClassTest NoFPClass =
6484 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6485 return NoFPClass & FPClassTest::fcNan;
6486 }
6487 default:
6488 return false;
6489 }
6490}
6491
6493 FastMathFlags FMF) {
6494 if (isa<PoisonValue>(V))
6495 return true;
6496 if (isa<UndefValue>(V))
6497 return false;
6498
6499 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6500 return true;
6501
6503 if (!I)
6504 return false;
6505
6506 switch (I->getOpcode()) {
6507 case Instruction::SIToFP:
6508 case Instruction::UIToFP:
6509 // TODO: Could check nofpclass(inf) on incoming argument
6510 if (FMF.noInfs())
6511 return true;
6512
6513 // Need to check int size cannot produce infinity, which computeKnownFPClass
6514 // knows how to do already.
6515 return isKnownNeverInfinity(I, SQ);
6516 case Instruction::Call: {
6517 const CallInst *CI = cast<CallInst>(I);
6518 switch (CI->getIntrinsicID()) {
6519 case Intrinsic::trunc:
6520 case Intrinsic::floor:
6521 case Intrinsic::ceil:
6522 case Intrinsic::rint:
6523 case Intrinsic::nearbyint:
6524 case Intrinsic::round:
6525 case Intrinsic::roundeven:
6526 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6527 default:
6528 break;
6529 }
6530
6531 break;
6532 }
6533 default:
6534 break;
6535 }
6536
6537 return false;
6538}
6539
6541
6542 // All byte-wide stores are splatable, even of arbitrary variables.
6543 if (V->getType()->isIntegerTy(8))
6544 return V;
6545
6546 LLVMContext &Ctx = V->getContext();
6547
6548 // Undef don't care.
6549 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6550 if (isa<UndefValue>(V))
6551 return UndefInt8;
6552
6553 // Return poison for zero-sized type.
6554 if (DL.getTypeStoreSize(V->getType()).isZero())
6555 return PoisonValue::get(Type::getInt8Ty(Ctx));
6556
6558 if (!C) {
6559 // Conceptually, we could handle things like:
6560 // %a = zext i8 %X to i16
6561 // %b = shl i16 %a, 8
6562 // %c = or i16 %a, %b
6563 // but until there is an example that actually needs this, it doesn't seem
6564 // worth worrying about.
6565 return nullptr;
6566 }
6567
6568 // Handle 'null' ConstantArrayZero etc.
6569 if (C->isNullValue())
6571
6572 // Constant floating-point values can be handled as integer values if the
6573 // corresponding integer value is "byteable". An important case is 0.0.
6574 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6575 Type *ScalarTy = CFP->getType()->getScalarType();
6576 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6577 return isBytewiseValue(
6578 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6579
6580 // Don't handle long double formats, which have strange constraints.
6581 return nullptr;
6582 }
6583
6584 // We can handle constant integers that are multiple of 8 bits.
6585 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6586 if (CI->getBitWidth() % 8 == 0) {
6587 if (!CI->getValue().isSplat(8))
6588 return nullptr;
6589 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6590 }
6591 }
6592
6593 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6594 if (CE->getOpcode() == Instruction::IntToPtr) {
6595 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6596 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6598 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6599 return isBytewiseValue(Op, DL);
6600 }
6601 }
6602 }
6603
6604 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6605 if (LHS == RHS)
6606 return LHS;
6607 if (!LHS || !RHS)
6608 return nullptr;
6609 if (LHS == UndefInt8)
6610 return RHS;
6611 if (RHS == UndefInt8)
6612 return LHS;
6613 return nullptr;
6614 };
6615
6617 Value *Val = UndefInt8;
6618 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6619 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6620 return nullptr;
6621 return Val;
6622 }
6623
6625 Value *Val = UndefInt8;
6626 for (Value *Op : C->operands())
6627 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6628 return nullptr;
6629 return Val;
6630 }
6631
6632 // Don't try to handle the handful of other constants.
6633 return nullptr;
6634}
6635
6636// This is the recursive version of BuildSubAggregate. It takes a few different
6637// arguments. Idxs is the index within the nested struct From that we are
6638// looking at now (which is of type IndexedType). IdxSkip is the number of
6639// indices from Idxs that should be left out when inserting into the resulting
6640// struct. To is the result struct built so far, new insertvalue instructions
6641// build on that.
6642static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6644 unsigned IdxSkip,
6645 BasicBlock::iterator InsertBefore) {
6646 StructType *STy = dyn_cast<StructType>(IndexedType);
6647 if (STy) {
6648 // Save the original To argument so we can modify it
6649 Value *OrigTo = To;
6650 // General case, the type indexed by Idxs is a struct
6651 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6652 // Process each struct element recursively
6653 Idxs.push_back(i);
6654 Value *PrevTo = To;
6655 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6656 InsertBefore);
6657 Idxs.pop_back();
6658 if (!To) {
6659 // Couldn't find any inserted value for this index? Cleanup
6660 while (PrevTo != OrigTo) {
6662 PrevTo = Del->getAggregateOperand();
6663 Del->eraseFromParent();
6664 }
6665 // Stop processing elements
6666 break;
6667 }
6668 }
6669 // If we successfully found a value for each of our subaggregates
6670 if (To)
6671 return To;
6672 }
6673 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6674 // the struct's elements had a value that was inserted directly. In the latter
6675 // case, perhaps we can't determine each of the subelements individually, but
6676 // we might be able to find the complete struct somewhere.
6677
6678 // Find the value that is at that particular spot
6679 Value *V = FindInsertedValue(From, Idxs);
6680
6681 if (!V)
6682 return nullptr;
6683
6684 // Insert the value in the new (sub) aggregate
6685 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6686 InsertBefore);
6687}
6688
6689// This helper takes a nested struct and extracts a part of it (which is again a
6690// struct) into a new value. For example, given the struct:
6691// { a, { b, { c, d }, e } }
6692// and the indices "1, 1" this returns
6693// { c, d }.
6694//
6695// It does this by inserting an insertvalue for each element in the resulting
6696// struct, as opposed to just inserting a single struct. This will only work if
6697// each of the elements of the substruct are known (ie, inserted into From by an
6698// insertvalue instruction somewhere).
6699//
6700// All inserted insertvalue instructions are inserted before InsertBefore
6702 BasicBlock::iterator InsertBefore) {
6703 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6704 idx_range);
6705 Value *To = PoisonValue::get(IndexedType);
6706 SmallVector<unsigned, 10> Idxs(idx_range);
6707 unsigned IdxSkip = Idxs.size();
6708
6709 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6710}
6711
6712/// Given an aggregate and a sequence of indices, see if the scalar value
6713/// indexed is already around as a register, for example if it was inserted
6714/// directly into the aggregate.
6715///
6716/// If InsertBefore is not null, this function will duplicate (modified)
6717/// insertvalues when a part of a nested struct is extracted.
6718Value *
6720 std::optional<BasicBlock::iterator> InsertBefore) {
6721 // Nothing to index? Just return V then (this is useful at the end of our
6722 // recursion).
6723 if (idx_range.empty())
6724 return V;
6725 // We have indices, so V should have an indexable type.
6726 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6727 "Not looking at a struct or array?");
6728 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6729 "Invalid indices for type?");
6730
6731 if (Constant *C = dyn_cast<Constant>(V)) {
6732 C = C->getAggregateElement(idx_range[0]);
6733 if (!C) return nullptr;
6734 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6735 }
6736
6738 // Loop the indices for the insertvalue instruction in parallel with the
6739 // requested indices
6740 const unsigned *req_idx = idx_range.begin();
6741 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6742 i != e; ++i, ++req_idx) {
6743 if (req_idx == idx_range.end()) {
6744 // We can't handle this without inserting insertvalues
6745 if (!InsertBefore)
6746 return nullptr;
6747
6748 // The requested index identifies a part of a nested aggregate. Handle
6749 // this specially. For example,
6750 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6751 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6752 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6753 // This can be changed into
6754 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6755 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6756 // which allows the unused 0,0 element from the nested struct to be
6757 // removed.
6758 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6759 *InsertBefore);
6760 }
6761
6762 // This insert value inserts something else than what we are looking for.
6763 // See if the (aggregate) value inserted into has the value we are
6764 // looking for, then.
6765 if (*req_idx != *i)
6766 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6767 InsertBefore);
6768 }
6769 // If we end up here, the indices of the insertvalue match with those
6770 // requested (though possibly only partially). Now we recursively look at
6771 // the inserted value, passing any remaining indices.
6772 return FindInsertedValue(I->getInsertedValueOperand(),
6773 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6774 }
6775
6777 // If we're extracting a value from an aggregate that was extracted from
6778 // something else, we can extract from that something else directly instead.
6779 // However, we will need to chain I's indices with the requested indices.
6780
6781 // Calculate the number of indices required
6782 unsigned size = I->getNumIndices() + idx_range.size();
6783 // Allocate some space to put the new indices in
6785 Idxs.reserve(size);
6786 // Add indices from the extract value instruction
6787 Idxs.append(I->idx_begin(), I->idx_end());
6788
6789 // Add requested indices
6790 Idxs.append(idx_range.begin(), idx_range.end());
6791
6792 assert(Idxs.size() == size
6793 && "Number of indices added not correct?");
6794
6795 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6796 }
6797 // Otherwise, we don't know (such as, extracting from a function return value
6798 // or load instruction)
6799 return nullptr;
6800}
6801
6802// If V refers to an initialized global constant, set Slice either to
6803// its initializer if the size of its elements equals ElementSize, or,
6804// for ElementSize == 8, to its representation as an array of unsiged
6805// char. Return true on success.
6806// Offset is in the unit "nr of ElementSize sized elements".
6809 unsigned ElementSize, uint64_t Offset) {
6810 assert(V && "V should not be null.");
6811 assert((ElementSize % 8) == 0 &&
6812 "ElementSize expected to be a multiple of the size of a byte.");
6813 unsigned ElementSizeInBytes = ElementSize / 8;
6814
6815 // Drill down into the pointer expression V, ignoring any intervening
6816 // casts, and determine the identity of the object it references along
6817 // with the cumulative byte offset into it.
6818 const GlobalVariable *GV =
6820 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6821 // Fail if V is not based on constant global object.
6822 return false;
6823
6824 const DataLayout &DL = GV->getDataLayout();
6825 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6826
6827 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6828 /*AllowNonInbounds*/ true))
6829 // Fail if a constant offset could not be determined.
6830 return false;
6831
6832 uint64_t StartIdx = Off.getLimitedValue();
6833 if (StartIdx == UINT64_MAX)
6834 // Fail if the constant offset is excessive.
6835 return false;
6836
6837 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6838 // elements. Simply bail out if that isn't possible.
6839 if ((StartIdx % ElementSizeInBytes) != 0)
6840 return false;
6841
6842 Offset += StartIdx / ElementSizeInBytes;
6843 ConstantDataArray *Array = nullptr;
6844 ArrayType *ArrayTy = nullptr;
6845
6846 if (GV->getInitializer()->isNullValue()) {
6847 Type *GVTy = GV->getValueType();
6848 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6849 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6850
6851 Slice.Array = nullptr;
6852 Slice.Offset = 0;
6853 // Return an empty Slice for undersized constants to let callers
6854 // transform even undefined library calls into simpler, well-defined
6855 // expressions. This is preferable to making the calls although it
6856 // prevents sanitizers from detecting such calls.
6857 Slice.Length = Length < Offset ? 0 : Length - Offset;
6858 return true;
6859 }
6860
6861 auto *Init = const_cast<Constant *>(GV->getInitializer());
6862 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6863 Type *InitElTy = ArrayInit->getElementType();
6864 if (InitElTy->isIntegerTy(ElementSize)) {
6865 // If Init is an initializer for an array of the expected type
6866 // and size, use it as is.
6867 Array = ArrayInit;
6868 ArrayTy = ArrayInit->getType();
6869 }
6870 }
6871
6872 if (!Array) {
6873 if (ElementSize != 8)
6874 // TODO: Handle conversions to larger integral types.
6875 return false;
6876
6877 // Otherwise extract the portion of the initializer starting
6878 // at Offset as an array of bytes, and reset Offset.
6880 if (!Init)
6881 return false;
6882
6883 Offset = 0;
6885 ArrayTy = dyn_cast<ArrayType>(Init->getType());
6886 }
6887
6888 uint64_t NumElts = ArrayTy->getArrayNumElements();
6889 if (Offset > NumElts)
6890 return false;
6891
6892 Slice.Array = Array;
6893 Slice.Offset = Offset;
6894 Slice.Length = NumElts - Offset;
6895 return true;
6896}
6897
6898/// Extract bytes from the initializer of the constant array V, which need
6899/// not be a nul-terminated string. On success, store the bytes in Str and
6900/// return true. When TrimAtNul is set, Str will contain only the bytes up
6901/// to but not including the first nul. Return false on failure.
6903 bool TrimAtNul) {
6905 if (!getConstantDataArrayInfo(V, Slice, 8))
6906 return false;
6907
6908 if (Slice.Array == nullptr) {
6909 if (TrimAtNul) {
6910 // Return a nul-terminated string even for an empty Slice. This is
6911 // safe because all existing SimplifyLibcalls callers require string
6912 // arguments and the behavior of the functions they fold is undefined
6913 // otherwise. Folding the calls this way is preferable to making
6914 // the undefined library calls, even though it prevents sanitizers
6915 // from reporting such calls.
6916 Str = StringRef();
6917 return true;
6918 }
6919 if (Slice.Length == 1) {
6920 Str = StringRef("", 1);
6921 return true;
6922 }
6923 // We cannot instantiate a StringRef as we do not have an appropriate string
6924 // of 0s at hand.
6925 return false;
6926 }
6927
6928 // Start out with the entire array in the StringRef.
6929 Str = Slice.Array->getAsString();
6930 // Skip over 'offset' bytes.
6931 Str = Str.substr(Slice.Offset);
6932
6933 if (TrimAtNul) {
6934 // Trim off the \0 and anything after it. If the array is not nul
6935 // terminated, we just return the whole end of string. The client may know
6936 // some other way that the string is length-bound.
6937 Str = Str.substr(0, Str.find('\0'));
6938 }
6939 return true;
6940}
6941
6942// These next two are very similar to the above, but also look through PHI
6943// nodes.
6944// TODO: See if we can integrate these two together.
6945
6946/// If we can compute the length of the string pointed to by
6947/// the specified pointer, return 'len+1'. If we can't, return 0.
6950 unsigned CharSize) {
6951 // Look through noop bitcast instructions.
6952 V = V->stripPointerCasts();
6953
6954 // If this is a PHI node, there are two cases: either we have already seen it
6955 // or we haven't.
6956 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
6957 if (!PHIs.insert(PN).second)
6958 return ~0ULL; // already in the set.
6959
6960 // If it was new, see if all the input strings are the same length.
6961 uint64_t LenSoFar = ~0ULL;
6962 for (Value *IncValue : PN->incoming_values()) {
6963 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
6964 if (Len == 0) return 0; // Unknown length -> unknown.
6965
6966 if (Len == ~0ULL) continue;
6967
6968 if (Len != LenSoFar && LenSoFar != ~0ULL)
6969 return 0; // Disagree -> unknown.
6970 LenSoFar = Len;
6971 }
6972
6973 // Success, all agree.
6974 return LenSoFar;
6975 }
6976
6977 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
6978 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
6979 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
6980 if (Len1 == 0) return 0;
6981 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
6982 if (Len2 == 0) return 0;
6983 if (Len1 == ~0ULL) return Len2;
6984 if (Len2 == ~0ULL) return Len1;
6985 if (Len1 != Len2) return 0;
6986 return Len1;
6987 }
6988
6989 // Otherwise, see if we can read the string.
6991 if (!getConstantDataArrayInfo(V, Slice, CharSize))
6992 return 0;
6993
6994 if (Slice.Array == nullptr)
6995 // Zeroinitializer (including an empty one).
6996 return 1;
6997
6998 // Search for the first nul character. Return a conservative result even
6999 // when there is no nul. This is safe since otherwise the string function
7000 // being folded such as strlen is undefined, and can be preferable to
7001 // making the undefined library call.
7002 unsigned NullIndex = 0;
7003 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7004 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7005 break;
7006 }
7007
7008 return NullIndex + 1;
7009}
7010
7011/// If we can compute the length of the string pointed to by
7012/// the specified pointer, return 'len+1'. If we can't, return 0.
7013uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7014 if (!V->getType()->isPointerTy())
7015 return 0;
7016
7018 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7019 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7020 // an empty string as a length.
7021 return Len == ~0ULL ? 1 : Len;
7022}
7023
7024const Value *
7026 bool MustPreserveOffset) {
7027 assert(Call &&
7028 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7029 if (const Value *RV = Call->getReturnedArgOperand())
7030 return RV;
7031 // This can be used only as a aliasing property.
7033 Call, MustPreserveOffset))
7034 return Call->getArgOperand(0);
7035 return nullptr;
7036}
7037
7039 const CallBase *Call, bool MustPreserveOffset) {
7040 switch (Call->getIntrinsicID()) {
7041 case Intrinsic::launder_invariant_group:
7042 case Intrinsic::strip_invariant_group:
7043 case Intrinsic::aarch64_irg:
7044 case Intrinsic::aarch64_tagp:
7045 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7046 // input pointer (and thus preserves the byte offset, which is the property
7047 // the MustPreserveOffset flag selects). However, it will not necessarily
7048 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7049 // descriptor", which has "all loads return 0, all stores are dropped"
7050 // semantics. Given the context of this intrinsic list, no one should be
7051 // relying on such a strict bit-exact null mapping (and, at time of
7052 // writing, they are not), but we document this fact out of an abundance
7053 // of caution.
7054 case Intrinsic::amdgcn_make_buffer_rsrc:
7055 return true;
7056 case Intrinsic::ptrmask:
7057 return !MustPreserveOffset;
7058 case Intrinsic::threadlocal_address:
7059 // The underlying variable changes with thread ID. The Thread ID may change
7060 // at coroutine suspend points.
7061 return !Call->getParent()->getParent()->isPresplitCoroutine();
7062 default:
7063 return false;
7064 }
7065}
7066
7067/// \p PN defines a loop-variant pointer to an object. Check if the
7068/// previous iteration of the loop was referring to the same object as \p PN.
7070 const LoopInfo *LI) {
7071 // Find the loop-defined value.
7072 Loop *L = LI->getLoopFor(PN->getParent());
7073 if (PN->getNumIncomingValues() != 2)
7074 return true;
7075
7076 // Find the value from previous iteration.
7077 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7078 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7079 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7080 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7081 return true;
7082
7083 // If a new pointer is loaded in the loop, the pointer references a different
7084 // object in every iteration. E.g.:
7085 // for (i)
7086 // int *p = a[i];
7087 // ...
7088 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7089 if (!L->isLoopInvariant(Load->getPointerOperand()))
7090 return false;
7091 return true;
7092}
7093
7094const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7095 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7096 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7097 const Value *PtrOp = GEP->getPointerOperand();
7098 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7099 return V;
7100 V = PtrOp;
7101 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7102 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7103 Value *NewV = cast<Operator>(V)->getOperand(0);
7104 if (!NewV->getType()->isPointerTy())
7105 return V;
7106 V = NewV;
7107 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7108 if (GA->isInterposable())
7109 return V;
7110 V = GA->getAliasee();
7111 } else {
7112 if (auto *PHI = dyn_cast<PHINode>(V)) {
7113 // Look through single-arg phi nodes created by LCSSA.
7114 if (PHI->getNumIncomingValues() == 1) {
7115 V = PHI->getIncomingValue(0);
7116 continue;
7117 }
7118 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7119 // CaptureTracking can know about special capturing properties of some
7120 // intrinsics like launder.invariant.group, that can't be expressed with
7121 // the attributes, but have properties like returning aliasing pointer.
7122 // Because some analysis may assume that nocaptured pointer is not
7123 // returned from some special intrinsic (because function would have to
7124 // be marked with returns attribute), it is crucial to use this function
7125 // because it should be in sync with CaptureTracking. Not using it may
7126 // cause weird miscompilations where 2 aliasing pointers are assumed to
7127 // noalias.
7129 Call, /*MustPreserveOffset=*/false)) {
7130 V = RP;
7131 continue;
7132 }
7133 }
7134
7135 return V;
7136 }
7137 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7138 }
7139 return V;
7140}
7141
7144 const LoopInfo *LI, unsigned MaxLookup) {
7147 Worklist.push_back(V);
7148 do {
7149 const Value *P = Worklist.pop_back_val();
7150 P = getUnderlyingObject(P, MaxLookup);
7151
7152 if (!Visited.insert(P).second)
7153 continue;
7154
7155 if (auto *SI = dyn_cast<SelectInst>(P)) {
7156 Worklist.push_back(SI->getTrueValue());
7157 Worklist.push_back(SI->getFalseValue());
7158 continue;
7159 }
7160
7161 if (auto *PN = dyn_cast<PHINode>(P)) {
7162 // If this PHI changes the underlying object in every iteration of the
7163 // loop, don't look through it. Consider:
7164 // int **A;
7165 // for (i) {
7166 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7167 // Curr = A[i];
7168 // *Prev, *Curr;
7169 //
7170 // Prev is tracking Curr one iteration behind so they refer to different
7171 // underlying objects.
7172 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7174 append_range(Worklist, PN->incoming_values());
7175 else
7176 Objects.push_back(P);
7177 continue;
7178 }
7179
7180 Objects.push_back(P);
7181 } while (!Worklist.empty());
7182}
7183
7185 const unsigned MaxVisited = 8;
7186
7189 Worklist.push_back(V);
7190 const Value *Object = nullptr;
7191 // Used as fallback if we can't find a common underlying object through
7192 // recursion.
7193 bool First = true;
7194 const Value *FirstObject = getUnderlyingObject(V);
7195 do {
7196 const Value *P = Worklist.pop_back_val();
7197 P = First ? FirstObject : getUnderlyingObject(P);
7198 First = false;
7199
7200 if (!Visited.insert(P).second)
7201 continue;
7202
7203 if (Visited.size() == MaxVisited)
7204 return FirstObject;
7205
7206 if (auto *SI = dyn_cast<SelectInst>(P)) {
7207 Worklist.push_back(SI->getTrueValue());
7208 Worklist.push_back(SI->getFalseValue());
7209 continue;
7210 }
7211
7212 if (auto *PN = dyn_cast<PHINode>(P)) {
7213 append_range(Worklist, PN->incoming_values());
7214 continue;
7215 }
7216
7217 if (!Object)
7218 Object = P;
7219 else if (Object != P)
7220 return FirstObject;
7221 } while (!Worklist.empty());
7222
7223 return Object ? Object : FirstObject;
7224}
7225
7226/// This is the function that does the work of looking through basic
7227/// ptrtoint+arithmetic+inttoptr sequences.
7228static const Value *getUnderlyingObjectFromInt(const Value *V) {
7229 do {
7230 if (const Operator *U = dyn_cast<Operator>(V)) {
7231 // If we find a ptrtoint, we can transfer control back to the
7232 // regular getUnderlyingObjectFromInt.
7233 if (U->getOpcode() == Instruction::PtrToInt)
7234 return U->getOperand(0);
7235 // If we find an add of a constant, a multiplied value, or a phi, it's
7236 // likely that the other operand will lead us to the base
7237 // object. We don't have to worry about the case where the
7238 // object address is somehow being computed by the multiply,
7239 // because our callers only care when the result is an
7240 // identifiable object.
7241 if (U->getOpcode() != Instruction::Add ||
7242 (!isa<ConstantInt>(U->getOperand(1)) &&
7243 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7244 !isa<PHINode>(U->getOperand(1))))
7245 return V;
7246 V = U->getOperand(0);
7247 } else {
7248 return V;
7249 }
7250 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7251 } while (true);
7252}
7253
7254/// This is a wrapper around getUnderlyingObjects and adds support for basic
7255/// ptrtoint+arithmetic+inttoptr sequences.
7256/// It returns false if unidentified object is found in getUnderlyingObjects.
7258 SmallVectorImpl<Value *> &Objects) {
7260 SmallVector<const Value *, 4> Working(1, V);
7261 do {
7262 V = Working.pop_back_val();
7263
7265 getUnderlyingObjects(V, Objs);
7266
7267 for (const Value *V : Objs) {
7268 if (!Visited.insert(V).second)
7269 continue;
7270 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7271 const Value *O =
7272 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7273 if (O->getType()->isPointerTy()) {
7274 Working.push_back(O);
7275 continue;
7276 }
7277 }
7278 // If getUnderlyingObjects fails to find an identifiable object,
7279 // getUnderlyingObjectsForCodeGen also fails for safety.
7280 if (!isIdentifiedObject(V)) {
7281 Objects.clear();
7282 return false;
7283 }
7284 Objects.push_back(const_cast<Value *>(V));
7285 }
7286 } while (!Working.empty());
7287 return true;
7288}
7289
7291 AllocaInst *Result = nullptr;
7293 SmallVector<Value *, 4> Worklist;
7294
7295 auto AddWork = [&](Value *V) {
7296 if (Visited.insert(V).second)
7297 Worklist.push_back(V);
7298 };
7299
7300 AddWork(V);
7301 do {
7302 V = Worklist.pop_back_val();
7303 assert(Visited.count(V));
7304
7305 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7306 if (Result && Result != AI)
7307 return nullptr;
7308 Result = AI;
7309 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7310 AddWork(CI->getOperand(0));
7311 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7312 for (Value *IncValue : PN->incoming_values())
7313 AddWork(IncValue);
7314 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7315 AddWork(SI->getTrueValue());
7316 AddWork(SI->getFalseValue());
7318 if (OffsetZero && !GEP->hasAllZeroIndices())
7319 return nullptr;
7320 AddWork(GEP->getPointerOperand());
7321 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7322 Value *Returned = CB->getReturnedArgOperand();
7323 if (Returned)
7324 AddWork(Returned);
7325 else
7326 return nullptr;
7327 } else {
7328 return nullptr;
7329 }
7330 } while (!Worklist.empty());
7331
7332 return Result;
7333}
7334
7336 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7337 for (const User *U : V->users()) {
7339 if (!II)
7340 return false;
7341
7342 if (AllowLifetime && II->isLifetimeStartOrEnd())
7343 continue;
7344
7345 if (AllowDroppable && II->isDroppable())
7346 continue;
7347
7348 return false;
7349 }
7350 return true;
7351}
7352
7355 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7356}
7359 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7360}
7361
7363 if (auto *II = dyn_cast<IntrinsicInst>(I))
7364 return isTriviallyVectorizable(II->getIntrinsicID());
7365 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7366 return (!Shuffle || Shuffle->isSelect()) &&
7368}
7369
7371 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7372 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7373 bool IgnoreUBImplyingAttrs) {
7374 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7375 AC, DT, TLI, UseVariableInfo,
7376 IgnoreUBImplyingAttrs);
7377}
7378
7380 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7381 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7382 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7383#ifndef NDEBUG
7384 if (Inst->getOpcode() != Opcode) {
7385 // Check that the operands are actually compatible with the Opcode override.
7386 auto hasEqualReturnAndLeadingOperandTypes =
7387 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7388 if (Inst->getNumOperands() < NumLeadingOperands)
7389 return false;
7390 const Type *ExpectedType = Inst->getType();
7391 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7392 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7393 return false;
7394 return true;
7395 };
7397 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7398 assert(!Instruction::isUnaryOp(Opcode) ||
7399 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7400 }
7401#endif
7402
7403 switch (Opcode) {
7404 default:
7405 return true;
7406 case Instruction::UDiv:
7407 case Instruction::URem: {
7408 // x / y is undefined if y == 0.
7409 const APInt *V;
7410 if (match(Inst->getOperand(1), m_APInt(V)))
7411 return *V != 0;
7412 return false;
7413 }
7414 case Instruction::SDiv:
7415 case Instruction::SRem: {
7416 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7417 const APInt *Numerator, *Denominator;
7418 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7419 return false;
7420 // We cannot hoist this division if the denominator is 0.
7421 if (*Denominator == 0)
7422 return false;
7423 // It's safe to hoist if the denominator is not 0 or -1.
7424 if (!Denominator->isAllOnes())
7425 return true;
7426 // At this point we know that the denominator is -1. It is safe to hoist as
7427 // long we know that the numerator is not INT_MIN.
7428 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7429 return !Numerator->isMinSignedValue();
7430 // The numerator *might* be MinSignedValue.
7431 return false;
7432 }
7433 case Instruction::Load: {
7434 if (!UseVariableInfo)
7435 return false;
7436
7437 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7438 if (!LI)
7439 return false;
7440 if (mustSuppressSpeculation(*LI))
7441 return false;
7442 const DataLayout &DL = LI->getDataLayout();
7444 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7445 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7446 }
7447 case Instruction::Call: {
7448 auto *CI = dyn_cast<const CallInst>(Inst);
7449 if (!CI)
7450 return false;
7451 const Function *Callee = CI->getCalledFunction();
7452
7453 // The called function could have undefined behavior or side-effects, even
7454 // if marked readnone nounwind.
7455 if (!Callee || !Callee->isSpeculatable())
7456 return false;
7457 // Since the operands may be changed after hoisting, undefined behavior may
7458 // be triggered by some UB-implying attributes.
7459 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7460 }
7461 case Instruction::VAArg:
7462 case Instruction::Alloca:
7463 case Instruction::Invoke:
7464 case Instruction::CallBr:
7465 case Instruction::PHI:
7466 case Instruction::Store:
7467 case Instruction::Ret:
7468 case Instruction::UncondBr:
7469 case Instruction::CondBr:
7470 case Instruction::IndirectBr:
7471 case Instruction::Switch:
7472 case Instruction::Unreachable:
7473 case Instruction::Fence:
7474 case Instruction::AtomicRMW:
7475 case Instruction::AtomicCmpXchg:
7476 case Instruction::LandingPad:
7477 case Instruction::Resume:
7478 case Instruction::CatchSwitch:
7479 case Instruction::CatchPad:
7480 case Instruction::CatchRet:
7481 case Instruction::CleanupPad:
7482 case Instruction::CleanupRet:
7483 return false; // Misc instructions which have effects
7484 }
7485}
7486
7488 if (I.mayReadOrWriteMemory())
7489 // Memory dependency possible
7490 return true;
7492 // Can't move above a maythrow call or infinite loop. Or if an
7493 // inalloca alloca, above a stacksave call.
7494 return true;
7496 // 1) Can't reorder two inf-loop calls, even if readonly
7497 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7498 // safe to speculative execute. (Inverse of above)
7499 return true;
7500 return false;
7501}
7502
7503/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7517
7518/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7521 bool ForSigned,
7522 const SimplifyQuery &SQ) {
7523 ConstantRange CR1 =
7524 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7525 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7528 return CR1.intersectWith(CR2, RangeType);
7529}
7530
7532 const Value *RHS,
7533 const SimplifyQuery &SQ,
7534 bool IsNSW) {
7535 ConstantRange LHSRange =
7536 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7537 ConstantRange RHSRange =
7538 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7539
7540 // mul nsw of two non-negative numbers is also nuw.
7541 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7543
7544 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7545}
7546
7548 const Value *RHS,
7549 const SimplifyQuery &SQ) {
7550 // Multiplying n * m significant bits yields a result of n + m significant
7551 // bits. If the total number of significant bits does not exceed the
7552 // result bit width (minus 1), there is no overflow.
7553 // This means if we have enough leading sign bits in the operands
7554 // we can guarantee that the result does not overflow.
7555 // Ref: "Hacker's Delight" by Henry Warren
7556 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7557
7558 // Note that underestimating the number of sign bits gives a more
7559 // conservative answer.
7560 unsigned SignBits =
7561 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7562
7563 // First handle the easy case: if we have enough sign bits there's
7564 // definitely no overflow.
7565 if (SignBits > BitWidth + 1)
7567
7568 // There are two ambiguous cases where there can be no overflow:
7569 // SignBits == BitWidth + 1 and
7570 // SignBits == BitWidth
7571 // The second case is difficult to check, therefore we only handle the
7572 // first case.
7573 if (SignBits == BitWidth + 1) {
7574 // It overflows only when both arguments are negative and the true
7575 // product is exactly the minimum negative number.
7576 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7577 // For simplicity we just check if at least one side is not negative.
7578 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7579 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7580 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7582 }
7584}
7585
7588 const WithCache<const Value *> &RHS,
7589 const SimplifyQuery &SQ) {
7590 ConstantRange LHSRange =
7591 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7592 ConstantRange RHSRange =
7593 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7594 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7595}
7596
7597static OverflowResult
7600 const AddOperator *Add, const SimplifyQuery &SQ) {
7601 if (Add && Add->hasNoSignedWrap()) {
7603 }
7604
7605 // If LHS and RHS each have at least two sign bits, the addition will look
7606 // like
7607 //
7608 // XX..... +
7609 // YY.....
7610 //
7611 // If the carry into the most significant position is 0, X and Y can't both
7612 // be 1 and therefore the carry out of the addition is also 0.
7613 //
7614 // If the carry into the most significant position is 1, X and Y can't both
7615 // be 0 and therefore the carry out of the addition is also 1.
7616 //
7617 // Since the carry into the most significant position is always equal to
7618 // the carry out of the addition, there is no signed overflow.
7619 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7621
7622 ConstantRange LHSRange =
7623 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7624 ConstantRange RHSRange =
7625 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7626 OverflowResult OR =
7627 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7629 return OR;
7630
7631 // The remaining code needs Add to be available. Early returns if not so.
7632 if (!Add)
7634
7635 // If the sign of Add is the same as at least one of the operands, this add
7636 // CANNOT overflow. If this can be determined from the known bits of the
7637 // operands the above signedAddMayOverflow() check will have already done so.
7638 // The only other way to improve on the known bits is from an assumption, so
7639 // call computeKnownBitsFromContext() directly.
7640 bool LHSOrRHSKnownNonNegative =
7641 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7642 bool LHSOrRHSKnownNegative =
7643 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7644 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7645 KnownBits AddKnown(LHSRange.getBitWidth());
7646 computeKnownBitsFromContext(Add, AddKnown, SQ);
7647 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7648 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7650 }
7651
7653}
7654
7656 const Value *RHS,
7657 const SimplifyQuery &SQ) {
7658 // X - (X % ?)
7659 // The remainder of a value can't have greater magnitude than itself,
7660 // so the subtraction can't overflow.
7661
7662 // X - (X -nuw ?)
7663 // In the minimal case, this would simplify to "?", so there's no subtract
7664 // at all. But if this analysis is used to peek through casts, for example,
7665 // then determining no-overflow may allow other transforms.
7666
7667 // TODO: There are other patterns like this.
7668 // See simplifyICmpWithBinOpOnLHS() for candidates.
7669 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7670 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7671 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7673
7674 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7675 SQ.DL)) {
7676 if (*C)
7679 }
7680
7681 ConstantRange LHSRange =
7682 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7683 ConstantRange RHSRange =
7684 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7685 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7686}
7687
7689 const Value *RHS,
7690 const SimplifyQuery &SQ) {
7691 // X - (X % ?)
7692 // The remainder of a value can't have greater magnitude than itself,
7693 // so the subtraction can't overflow.
7694
7695 // X - (X -nsw ?)
7696 // In the minimal case, this would simplify to "?", so there's no subtract
7697 // at all. But if this analysis is used to peek through casts, for example,
7698 // then determining no-overflow may allow other transforms.
7699 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7700 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7701 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7703
7704 // If LHS and RHS each have at least two sign bits, the subtraction
7705 // cannot overflow.
7706 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7708
7709 ConstantRange LHSRange =
7710 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7711 ConstantRange RHSRange =
7712 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7713 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7714}
7715
7717 const DominatorTree &DT) {
7718 SmallVector<const CondBrInst *, 2> GuardingBranches;
7720
7721 for (const User *U : WO->users()) {
7722 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7723 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7724
7725 if (EVI->getIndices()[0] == 0)
7726 Results.push_back(EVI);
7727 else {
7728 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7729
7730 for (const auto *U : EVI->users())
7731 if (const auto *B = dyn_cast<CondBrInst>(U))
7732 GuardingBranches.push_back(B);
7733 }
7734 } else {
7735 // We are using the aggregate directly in a way we don't want to analyze
7736 // here (storing it to a global, say).
7737 return false;
7738 }
7739 }
7740
7741 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7742 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7743
7744 // Check if all users of the add are provably no-wrap.
7745 for (const auto *Result : Results) {
7746 // If the extractvalue itself is not executed on overflow, the we don't
7747 // need to check each use separately, since domination is transitive.
7748 if (DT.dominates(NoWrapEdge, Result->getParent()))
7749 continue;
7750
7751 for (const auto &RU : Result->uses())
7752 if (!DT.dominates(NoWrapEdge, RU))
7753 return false;
7754 }
7755
7756 return true;
7757 };
7758
7759 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7760}
7761
7762/// Shifts return poison if shiftwidth is larger than the bitwidth.
7763static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7764 auto *C = dyn_cast<Constant>(ShiftAmount);
7765 if (!C)
7766 return false;
7767
7768 // Shifts return poison if shiftwidth is larger than the bitwidth.
7770 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7771 unsigned NumElts = FVTy->getNumElements();
7772 for (unsigned i = 0; i < NumElts; ++i)
7773 ShiftAmounts.push_back(C->getAggregateElement(i));
7774 } else if (isa<ScalableVectorType>(C->getType()))
7775 return false; // Can't tell, just return false to be safe
7776 else
7777 ShiftAmounts.push_back(C);
7778
7779 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7780 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7781 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7782 });
7783
7784 return Safe;
7785}
7786
7788 bool ConsiderFlagsAndMetadata) {
7789
7790 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7791 Op->hasPoisonGeneratingAnnotations())
7792 return true;
7793
7794 unsigned Opcode = Op->getOpcode();
7795
7796 // Check whether opcode is a poison/undef-generating operation
7797 switch (Opcode) {
7798 case Instruction::Shl:
7799 case Instruction::AShr:
7800 case Instruction::LShr:
7801 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7802 case Instruction::FPToSI:
7803 case Instruction::FPToUI:
7804 // fptosi/ui yields poison if the resulting value does not fit in the
7805 // destination type.
7806 return true;
7807 case Instruction::Call:
7808 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7809 switch (II->getIntrinsicID()) {
7810 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7811 case Intrinsic::ctlz:
7812 case Intrinsic::cttz:
7813 case Intrinsic::abs:
7814 // We're not considering flags so it is safe to just return false.
7815 return false;
7816 case Intrinsic::sshl_sat:
7817 case Intrinsic::ushl_sat:
7818 if (!includesPoison(Kind) ||
7819 shiftAmountKnownInRange(II->getArgOperand(1)))
7820 return false;
7821 break;
7822 }
7823 }
7824 [[fallthrough]];
7825 case Instruction::CallBr:
7826 case Instruction::Invoke: {
7827 const auto *CB = cast<CallBase>(Op);
7828 return !CB->hasRetAttr(Attribute::NoUndef) &&
7829 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7830 }
7831 case Instruction::InsertElement:
7832 case Instruction::ExtractElement: {
7833 // If index exceeds the length of the vector, it returns poison
7834 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7835 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7836 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7837 if (includesPoison(Kind))
7838 return !Idx ||
7839 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7840 return false;
7841 }
7842 case Instruction::ShuffleVector: {
7844 ? cast<ConstantExpr>(Op)->getShuffleMask()
7845 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7846 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7847 }
7848 case Instruction::FNeg:
7849 case Instruction::PHI:
7850 case Instruction::Select:
7851 case Instruction::ExtractValue:
7852 case Instruction::InsertValue:
7853 case Instruction::Freeze:
7854 case Instruction::ICmp:
7855 case Instruction::FCmp:
7856 case Instruction::GetElementPtr:
7857 return false;
7858 case Instruction::AddrSpaceCast:
7859 return true;
7860 default: {
7861 const auto *CE = dyn_cast<ConstantExpr>(Op);
7862 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7863 return false;
7864 else if (Instruction::isBinaryOp(Opcode))
7865 return false;
7866 // Be conservative and return true.
7867 return true;
7868 }
7869 }
7870}
7871
7873 bool ConsiderFlagsAndMetadata) {
7874 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
7875 ConsiderFlagsAndMetadata);
7876}
7877
7878bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
7879 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
7880 ConsiderFlagsAndMetadata);
7881}
7882
7883static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
7884 unsigned Depth) {
7885 if (ValAssumedPoison == V)
7886 return true;
7887
7888 const unsigned MaxDepth = 2;
7889 if (Depth >= MaxDepth)
7890 return false;
7891
7892 if (const auto *I = dyn_cast<Instruction>(V)) {
7893 if (any_of(I->operands(), [=](const Use &Op) {
7894 return propagatesPoison(Op) &&
7895 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7896 }))
7897 return true;
7898
7899 // V = extractvalue V0, idx
7900 // V2 = extractvalue V0, idx2
7901 // V0's elements are all poison or not. (e.g., add_with_overflow)
7902 const WithOverflowInst *II;
7904 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
7905 llvm::is_contained(II->args(), ValAssumedPoison)))
7906 return true;
7907 }
7908 return false;
7909}
7910
7911static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
7912 unsigned Depth) {
7913 if (isGuaranteedNotToBePoison(ValAssumedPoison))
7914 return true;
7915
7916 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
7917 return true;
7918
7919 const unsigned MaxDepth = 2;
7920 if (Depth >= MaxDepth)
7921 return false;
7922
7923 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
7924 if (I && !canCreatePoison(cast<Operator>(I))) {
7925 return all_of(I->operands(), [=](const Value *Op) {
7926 return impliesPoison(Op, V, Depth + 1);
7927 });
7928 }
7929 return false;
7930}
7931
7932bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
7933 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
7934}
7935
7936static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
7937
7939 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
7940 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
7942 return false;
7943
7944 if (isa<MetadataAsValue>(V))
7945 return false;
7946
7947 if (const auto *A = dyn_cast<Argument>(V)) {
7948 if (A->hasAttribute(Attribute::NoUndef) ||
7949 A->hasAttribute(Attribute::Dereferenceable) ||
7950 A->hasAttribute(Attribute::DereferenceableOrNull))
7951 return true;
7952 }
7953
7954 if (auto *C = dyn_cast<Constant>(V)) {
7955 if (isa<PoisonValue>(C))
7956 return !includesPoison(Kind);
7957
7958 if (isa<UndefValue>(C))
7959 return !includesUndef(Kind);
7960
7963 return true;
7964
7965 if (C->getType()->isVectorTy()) {
7966 if (isa<ConstantExpr>(C)) {
7967 // Scalable vectors can use a ConstantExpr to build a splat.
7968 if (Constant *SplatC = C->getSplatValue())
7969 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
7970 return true;
7971 } else {
7972 if (includesUndef(Kind) && C->containsUndefElement())
7973 return false;
7974 if (includesPoison(Kind) && C->containsPoisonElement())
7975 return false;
7976 return !C->containsConstantExpression();
7977 }
7978 }
7979 }
7980
7981 // Strip cast operations from a pointer value.
7982 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
7983 // inbounds with zero offset. To guarantee that the result isn't poison, the
7984 // stripped pointer is checked as it has to be pointing into an allocated
7985 // object or be null `null` to ensure `inbounds` getelement pointers with a
7986 // zero offset could not produce poison.
7987 // It can strip off addrspacecast that do not change bit representation as
7988 // well. We believe that such addrspacecast is equivalent to no-op.
7989 auto *StrippedV = V->stripPointerCastsSameRepresentation();
7990 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
7991 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
7992 return true;
7993
7994 auto OpCheck = [&](const Value *V) {
7995 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
7996 };
7997
7998 if (auto *Opr = dyn_cast<Operator>(V)) {
7999 // If the value is a freeze instruction, then it can never
8000 // be undef or poison.
8001 if (isa<FreezeInst>(V))
8002 return true;
8003
8004 if (const auto *CB = dyn_cast<CallBase>(V)) {
8005 if (CB->hasRetAttr(Attribute::NoUndef) ||
8006 CB->hasRetAttr(Attribute::Dereferenceable) ||
8007 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8008 return true;
8009 }
8010
8011 if (!::canCreateUndefOrPoison(Opr, Kind,
8012 /*ConsiderFlagsAndMetadata=*/true)) {
8013 if (const auto *PN = dyn_cast<PHINode>(V)) {
8014 unsigned Num = PN->getNumIncomingValues();
8015 bool IsWellDefined = true;
8016 for (unsigned i = 0; i < Num; ++i) {
8017 if (PN == PN->getIncomingValue(i))
8018 continue;
8019 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8020 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8021 DT, Depth + 1, Kind)) {
8022 IsWellDefined = false;
8023 break;
8024 }
8025 }
8026 if (IsWellDefined)
8027 return true;
8028 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8029 : nullptr) {
8030 // For splats we only need to check the value being splatted.
8031 if (OpCheck(Splat))
8032 return true;
8033 } else if (all_of(Opr->operands(), OpCheck))
8034 return true;
8035 }
8036 }
8037
8038 if (auto *I = dyn_cast<LoadInst>(V))
8039 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8040 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8041 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8042 return true;
8043
8045 return true;
8046
8047 // CxtI may be null or a cloned instruction.
8048 if (!CtxI || !CtxI->getParent() || !DT)
8049 return false;
8050
8051 auto *DNode = DT->getNode(CtxI->getParent());
8052 if (!DNode)
8053 // Unreachable block
8054 return false;
8055
8056 // If V is used as a branch condition before reaching CtxI, V cannot be
8057 // undef or poison.
8058 // br V, BB1, BB2
8059 // BB1:
8060 // CtxI ; V cannot be undef or poison here
8061 auto *Dominator = DNode->getIDom();
8062 // This check is purely for compile time reasons: we can skip the IDom walk
8063 // if what we are checking for includes undef and the value is not an integer.
8064 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8065 while (Dominator) {
8066 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8067
8068 Value *Cond = nullptr;
8069 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8070 Cond = BI->getCondition();
8071 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8072 Cond = SI->getCondition();
8073 }
8074
8075 if (Cond) {
8076 if (Cond == V)
8077 return true;
8078 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8079 // For poison, we can analyze further
8080 auto *Opr = cast<Operator>(Cond);
8081 if (any_of(Opr->operands(), [V](const Use &U) {
8082 return V == U && propagatesPoison(U);
8083 }))
8084 return true;
8085 }
8086 }
8087
8088 Dominator = Dominator->getIDom();
8089 }
8090
8091 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8092 return true;
8093
8094 return false;
8095}
8096
8098 const Instruction *CtxI,
8099 const DominatorTree *DT,
8100 unsigned Depth) {
8101 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8103}
8104
8106 const Instruction *CtxI,
8107 const DominatorTree *DT, unsigned Depth) {
8108 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8110}
8111
8113 const Instruction *CtxI,
8114 const DominatorTree *DT, unsigned Depth) {
8115 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8117}
8118
8119/// Return true if undefined behavior would provably be executed on the path to
8120/// OnPathTo if Root produced a posion result. Note that this doesn't say
8121/// anything about whether OnPathTo is actually executed or whether Root is
8122/// actually poison. This can be used to assess whether a new use of Root can
8123/// be added at a location which is control equivalent with OnPathTo (such as
8124/// immediately before it) without introducing UB which didn't previously
8125/// exist. Note that a false result conveys no information.
8127 Instruction *OnPathTo,
8128 DominatorTree *DT) {
8129 // Basic approach is to assume Root is poison, propagate poison forward
8130 // through all users we can easily track, and then check whether any of those
8131 // users are provable UB and must execute before out exiting block might
8132 // exit.
8133
8134 // The set of all recursive users we've visited (which are assumed to all be
8135 // poison because of said visit)
8138 Worklist.push_back(Root);
8139 while (!Worklist.empty()) {
8140 const Instruction *I = Worklist.pop_back_val();
8141
8142 // If we know this must trigger UB on a path leading our target.
8143 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8144 return true;
8145
8146 // If we can't analyze propagation through this instruction, just skip it
8147 // and transitive users. Safe as false is a conservative result.
8148 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8149 return KnownPoison.contains(U) && propagatesPoison(U);
8150 }))
8151 continue;
8152
8153 if (KnownPoison.insert(I).second)
8154 for (const User *User : I->users())
8155 Worklist.push_back(cast<Instruction>(User));
8156 }
8157
8158 // Might be non-UB, or might have a path we couldn't prove must execute on
8159 // way to exiting bb.
8160 return false;
8161}
8162
8164 const SimplifyQuery &SQ) {
8165 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8166 Add, SQ);
8167}
8168
8171 const WithCache<const Value *> &RHS,
8172 const SimplifyQuery &SQ) {
8173 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8174}
8175
8177 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8178 // of time because it's possible for another thread to interfere with it for an
8179 // arbitrary length of time, but programs aren't allowed to rely on that.
8180
8181 // If there is no successor, then execution can't transfer to it.
8182 if (isa<ReturnInst>(I))
8183 return false;
8185 return false;
8186
8187 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8188 // Instruction::willReturn.
8189 //
8190 // FIXME: Move this check into Instruction::willReturn.
8191 if (isa<CatchPadInst>(I)) {
8192 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8193 default:
8194 // A catchpad may invoke exception object constructors and such, which
8195 // in some languages can be arbitrary code, so be conservative by default.
8196 return false;
8198 // For CoreCLR, it just involves a type test.
8199 return true;
8200 }
8201 }
8202
8203 // An instruction that returns without throwing must transfer control flow
8204 // to a successor.
8205 return !I->mayThrow() && I->willReturn();
8206}
8207
8209 // TODO: This is slightly conservative for invoke instruction since exiting
8210 // via an exception *is* normal control for them.
8211 for (const Instruction &I : *BB)
8213 return false;
8214 return true;
8215}
8216
8223
8226 assert(ScanLimit && "scan limit must be non-zero");
8227 for (const Instruction &I : Range) {
8228 if (--ScanLimit == 0)
8229 return false;
8231 return false;
8232 }
8233 return true;
8234}
8235
8237 const Loop *L) {
8238 // The loop header is guaranteed to be executed for every iteration.
8239 //
8240 // FIXME: Relax this constraint to cover all basic blocks that are
8241 // guaranteed to be executed at every iteration.
8242 if (I->getParent() != L->getHeader()) return false;
8243
8244 for (const Instruction &LI : *L->getHeader()) {
8245 if (&LI == I) return true;
8246 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8247 }
8248 llvm_unreachable("Instruction not contained in its own parent basic block.");
8249}
8250
8252 switch (IID) {
8253 // TODO: Add more intrinsics.
8254 case Intrinsic::sadd_with_overflow:
8255 case Intrinsic::ssub_with_overflow:
8256 case Intrinsic::smul_with_overflow:
8257 case Intrinsic::uadd_with_overflow:
8258 case Intrinsic::usub_with_overflow:
8259 case Intrinsic::umul_with_overflow:
8260 // If an input is a vector containing a poison element, the
8261 // two output vectors (calculated results, overflow bits)'
8262 // corresponding lanes are poison.
8263 return true;
8264 case Intrinsic::ctpop:
8265 case Intrinsic::ctlz:
8266 case Intrinsic::cttz:
8267 case Intrinsic::abs:
8268 case Intrinsic::smax:
8269 case Intrinsic::smin:
8270 case Intrinsic::umax:
8271 case Intrinsic::umin:
8272 case Intrinsic::scmp:
8273 case Intrinsic::is_fpclass:
8274 case Intrinsic::ptrmask:
8275 case Intrinsic::ucmp:
8276 case Intrinsic::bitreverse:
8277 case Intrinsic::bswap:
8278 case Intrinsic::sadd_sat:
8279 case Intrinsic::ssub_sat:
8280 case Intrinsic::sshl_sat:
8281 case Intrinsic::uadd_sat:
8282 case Intrinsic::usub_sat:
8283 case Intrinsic::ushl_sat:
8284 case Intrinsic::smul_fix:
8285 case Intrinsic::smul_fix_sat:
8286 case Intrinsic::umul_fix:
8287 case Intrinsic::umul_fix_sat:
8288 case Intrinsic::pow:
8289 case Intrinsic::powi:
8290 case Intrinsic::sin:
8291 case Intrinsic::sinh:
8292 case Intrinsic::cos:
8293 case Intrinsic::cosh:
8294 case Intrinsic::sincos:
8295 case Intrinsic::sincospi:
8296 case Intrinsic::tan:
8297 case Intrinsic::tanh:
8298 case Intrinsic::asin:
8299 case Intrinsic::acos:
8300 case Intrinsic::atan:
8301 case Intrinsic::atan2:
8302 case Intrinsic::canonicalize:
8303 case Intrinsic::sqrt:
8304 case Intrinsic::exp:
8305 case Intrinsic::exp2:
8306 case Intrinsic::exp10:
8307 case Intrinsic::log:
8308 case Intrinsic::log2:
8309 case Intrinsic::log10:
8310 case Intrinsic::modf:
8311 case Intrinsic::floor:
8312 case Intrinsic::ceil:
8313 case Intrinsic::trunc:
8314 case Intrinsic::rint:
8315 case Intrinsic::nearbyint:
8316 case Intrinsic::round:
8317 case Intrinsic::roundeven:
8318 case Intrinsic::lrint:
8319 case Intrinsic::llrint:
8320 case Intrinsic::fshl:
8321 case Intrinsic::fshr:
8322 case Intrinsic::frexp:
8323 case Intrinsic::get_active_lane_mask:
8324 return true;
8325 default:
8326 return false;
8327 }
8328}
8329
8330bool llvm::propagatesPoison(const Use &PoisonOp) {
8331 const Operator *I = cast<Operator>(PoisonOp.getUser());
8332 switch (I->getOpcode()) {
8333 case Instruction::Freeze:
8334 case Instruction::PHI:
8335 case Instruction::Invoke:
8336 return false;
8337 case Instruction::Select:
8338 return PoisonOp.getOperandNo() == 0;
8339 case Instruction::Call:
8340 if (auto *II = dyn_cast<IntrinsicInst>(I))
8341 return intrinsicPropagatesPoison(II->getIntrinsicID());
8342 return false;
8343 case Instruction::ICmp:
8344 case Instruction::FCmp:
8345 case Instruction::GetElementPtr:
8346 return true;
8347 default:
8349 return true;
8350
8351 // Be conservative and return false.
8352 return false;
8353 }
8354}
8355
8356/// Enumerates all operands of \p I that are guaranteed to not be undef or
8357/// poison. If the callback \p Handle returns true, stop processing and return
8358/// true. Otherwise, return false.
8359template <typename CallableT>
8361 const CallableT &Handle) {
8362 switch (I->getOpcode()) {
8363 case Instruction::Store:
8364 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8365 return true;
8366 break;
8367
8368 case Instruction::Load:
8369 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8370 return true;
8371 break;
8372
8373 // Since dereferenceable attribute imply noundef, atomic operations
8374 // also implicitly have noundef pointers too
8375 case Instruction::AtomicCmpXchg:
8377 return true;
8378 break;
8379
8380 case Instruction::AtomicRMW:
8381 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8382 return true;
8383 break;
8384
8385 case Instruction::Call:
8386 case Instruction::Invoke: {
8387 const CallBase *CB = cast<CallBase>(I);
8388 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8389 return true;
8390 for (unsigned i = 0; i < CB->arg_size(); ++i)
8391 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8392 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8393 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8394 Handle(CB->getArgOperand(i)))
8395 return true;
8396 break;
8397 }
8398 case Instruction::Ret:
8399 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8400 Handle(I->getOperand(0)))
8401 return true;
8402 break;
8403 case Instruction::Switch:
8404 if (Handle(cast<SwitchInst>(I)->getCondition()))
8405 return true;
8406 break;
8407 case Instruction::CondBr:
8408 if (Handle(cast<CondBrInst>(I)->getCondition()))
8409 return true;
8410 break;
8411 default:
8412 break;
8413 }
8414
8415 return false;
8416}
8417
8418/// Enumerates all operands of \p I that are guaranteed to not be poison.
8419template <typename CallableT>
8421 const CallableT &Handle) {
8422 if (handleGuaranteedWellDefinedOps(I, Handle))
8423 return true;
8424 switch (I->getOpcode()) {
8425 // Divisors of these operations are allowed to be partially undef.
8426 case Instruction::UDiv:
8427 case Instruction::SDiv:
8428 case Instruction::URem:
8429 case Instruction::SRem:
8430 return Handle(I->getOperand(1));
8431 default:
8432 return false;
8433 }
8434}
8435
8437 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8439 I, [&](const Value *V) { return KnownPoison.count(V); });
8440}
8441
8443 bool PoisonOnly) {
8444 // We currently only look for uses of values within the same basic
8445 // block, as that makes it easier to guarantee that the uses will be
8446 // executed given that Inst is executed.
8447 //
8448 // FIXME: Expand this to consider uses beyond the same basic block. To do
8449 // this, look out for the distinction between post-dominance and strong
8450 // post-dominance.
8451 const BasicBlock *BB = nullptr;
8453 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8454 BB = Inst->getParent();
8455 Begin = Inst->getIterator();
8456 Begin++;
8457 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8458 if (Arg->getParent()->isDeclaration())
8459 return false;
8460 BB = &Arg->getParent()->getEntryBlock();
8461 Begin = BB->begin();
8462 } else {
8463 return false;
8464 }
8465
8466 // Limit number of instructions we look at, to avoid scanning through large
8467 // blocks. The current limit is chosen arbitrarily.
8468 unsigned ScanLimit = 32;
8469 BasicBlock::const_iterator End = BB->end();
8470
8471 if (!PoisonOnly) {
8472 // Since undef does not propagate eagerly, be conservative & just check
8473 // whether a value is directly passed to an instruction that must take
8474 // well-defined operands.
8475
8476 for (const auto &I : make_range(Begin, End)) {
8477 if (--ScanLimit == 0)
8478 break;
8479
8480 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8481 return WellDefinedOp == V;
8482 }))
8483 return true;
8484
8486 break;
8487 }
8488 return false;
8489 }
8490
8491 // Set of instructions that we have proved will yield poison if Inst
8492 // does.
8493 SmallPtrSet<const Value *, 16> YieldsPoison;
8495
8496 YieldsPoison.insert(V);
8497 Visited.insert(BB);
8498
8499 while (true) {
8500 for (const auto &I : make_range(Begin, End)) {
8501 if (--ScanLimit == 0)
8502 return false;
8503 if (mustTriggerUB(&I, YieldsPoison))
8504 return true;
8506 return false;
8507
8508 // If an operand is poison and propagates it, mark I as yielding poison.
8509 for (const Use &Op : I.operands()) {
8510 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8511 YieldsPoison.insert(&I);
8512 break;
8513 }
8514 }
8515
8516 // Special handling for select, which returns poison if its operand 0 is
8517 // poison (handled in the loop above) *or* if both its true/false operands
8518 // are poison (handled here).
8519 if (I.getOpcode() == Instruction::Select &&
8520 YieldsPoison.count(I.getOperand(1)) &&
8521 YieldsPoison.count(I.getOperand(2))) {
8522 YieldsPoison.insert(&I);
8523 }
8524 }
8525
8526 BB = BB->getSingleSuccessor();
8527 if (!BB || !Visited.insert(BB).second)
8528 break;
8529
8530 Begin = BB->getFirstNonPHIIt();
8531 End = BB->end();
8532 }
8533 return false;
8534}
8535
8537 return ::programUndefinedIfUndefOrPoison(Inst, false);
8538}
8539
8541 return ::programUndefinedIfUndefOrPoison(Inst, true);
8542}
8543
8544static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8545 if (FMF.noNaNs())
8546 return true;
8547
8548 if (auto *C = dyn_cast<ConstantFP>(V))
8549 return !C->isNaN();
8550
8551 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8552 if (!C->getElementType()->isFloatingPointTy())
8553 return false;
8554 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8555 if (C->getElementAsAPFloat(I).isNaN())
8556 return false;
8557 }
8558 return true;
8559 }
8560
8562 return true;
8563
8564 return false;
8565}
8566
8567static bool isKnownNonZero(const Value *V) {
8568 if (auto *C = dyn_cast<ConstantFP>(V))
8569 return !C->isZero();
8570
8571 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8572 if (!C->getElementType()->isFloatingPointTy())
8573 return false;
8574 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8575 if (C->getElementAsAPFloat(I).isZero())
8576 return false;
8577 }
8578 return true;
8579 }
8580
8581 return false;
8582}
8583
8584/// Match clamp pattern for float types without care about NaNs or signed zeros.
8585/// Given non-min/max outer cmp/select from the clamp pattern this
8586/// function recognizes if it can be substitued by a "canonical" min/max
8587/// pattern.
8589 Value *CmpLHS, Value *CmpRHS,
8590 Value *TrueVal, Value *FalseVal,
8591 Value *&LHS, Value *&RHS) {
8592 // Try to match
8593 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8594 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8595 // and return description of the outer Max/Min.
8596
8597 // First, check if select has inverse order:
8598 if (CmpRHS == FalseVal) {
8599 std::swap(TrueVal, FalseVal);
8600 Pred = CmpInst::getInversePredicate(Pred);
8601 }
8602
8603 // Assume success now. If there's no match, callers should not use these anyway.
8604 LHS = TrueVal;
8605 RHS = FalseVal;
8606
8607 const APFloat *FC1;
8608 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8609 return {SPF_UNKNOWN, SPNB_NA, false};
8610
8611 const APFloat *FC2;
8612 switch (Pred) {
8613 case CmpInst::FCMP_OLT:
8614 case CmpInst::FCMP_OLE:
8615 case CmpInst::FCMP_ULT:
8616 case CmpInst::FCMP_ULE:
8617 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8618 *FC1 < *FC2)
8619 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8620 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8621 *FC1 < *FC2)
8622 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8623 break;
8624 case CmpInst::FCMP_OGT:
8625 case CmpInst::FCMP_OGE:
8626 case CmpInst::FCMP_UGT:
8627 case CmpInst::FCMP_UGE:
8628 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8629 *FC1 > *FC2)
8630 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8631 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8632 *FC1 > *FC2)
8633 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8634 break;
8635 default:
8636 break;
8637 }
8638
8639 return {SPF_UNKNOWN, SPNB_NA, false};
8640}
8641
8642/// Recognize variations of:
8643/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8645 Value *CmpLHS, Value *CmpRHS,
8646 Value *TrueVal, Value *FalseVal) {
8647 // Swap the select operands and predicate to match the patterns below.
8648 if (CmpRHS != TrueVal) {
8649 Pred = ICmpInst::getSwappedPredicate(Pred);
8650 std::swap(TrueVal, FalseVal);
8651 }
8652 const APInt *C1;
8653 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8654 const APInt *C2;
8655 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8656 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8657 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8658 return {SPF_SMAX, SPNB_NA, false};
8659
8660 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8661 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8662 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8663 return {SPF_SMIN, SPNB_NA, false};
8664
8665 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8666 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8667 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8668 return {SPF_UMAX, SPNB_NA, false};
8669
8670 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8671 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8672 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8673 return {SPF_UMIN, SPNB_NA, false};
8674 }
8675 return {SPF_UNKNOWN, SPNB_NA, false};
8676}
8677
8678/// Recognize variations of:
8679/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8681 Value *CmpLHS, Value *CmpRHS,
8682 Value *TVal, Value *FVal,
8683 unsigned Depth) {
8684 // TODO: Allow FP min/max with nnan/nsz.
8685 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8686
8687 Value *A = nullptr, *B = nullptr;
8688 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8689 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8690 return {SPF_UNKNOWN, SPNB_NA, false};
8691
8692 Value *C = nullptr, *D = nullptr;
8693 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8694 if (L.Flavor != R.Flavor)
8695 return {SPF_UNKNOWN, SPNB_NA, false};
8696
8697 // We have something like: x Pred y ? min(a, b) : min(c, d).
8698 // Try to match the compare to the min/max operations of the select operands.
8699 // First, make sure we have the right compare predicate.
8700 switch (L.Flavor) {
8701 case SPF_SMIN:
8702 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8703 Pred = ICmpInst::getSwappedPredicate(Pred);
8704 std::swap(CmpLHS, CmpRHS);
8705 }
8706 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8707 break;
8708 return {SPF_UNKNOWN, SPNB_NA, false};
8709 case SPF_SMAX:
8710 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8711 Pred = ICmpInst::getSwappedPredicate(Pred);
8712 std::swap(CmpLHS, CmpRHS);
8713 }
8714 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8715 break;
8716 return {SPF_UNKNOWN, SPNB_NA, false};
8717 case SPF_UMIN:
8718 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8719 Pred = ICmpInst::getSwappedPredicate(Pred);
8720 std::swap(CmpLHS, CmpRHS);
8721 }
8722 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8723 break;
8724 return {SPF_UNKNOWN, SPNB_NA, false};
8725 case SPF_UMAX:
8726 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8727 Pred = ICmpInst::getSwappedPredicate(Pred);
8728 std::swap(CmpLHS, CmpRHS);
8729 }
8730 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8731 break;
8732 return {SPF_UNKNOWN, SPNB_NA, false};
8733 default:
8734 return {SPF_UNKNOWN, SPNB_NA, false};
8735 }
8736
8737 // If there is a common operand in the already matched min/max and the other
8738 // min/max operands match the compare operands (either directly or inverted),
8739 // then this is min/max of the same flavor.
8740
8741 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8742 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8743 if (D == B) {
8744 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8745 match(A, m_Not(m_Specific(CmpRHS)))))
8746 return {L.Flavor, SPNB_NA, false};
8747 }
8748 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8749 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8750 if (C == B) {
8751 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8752 match(A, m_Not(m_Specific(CmpRHS)))))
8753 return {L.Flavor, SPNB_NA, false};
8754 }
8755 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8756 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8757 if (D == A) {
8758 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8759 match(B, m_Not(m_Specific(CmpRHS)))))
8760 return {L.Flavor, SPNB_NA, false};
8761 }
8762 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8763 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8764 if (C == A) {
8765 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8766 match(B, m_Not(m_Specific(CmpRHS)))))
8767 return {L.Flavor, SPNB_NA, false};
8768 }
8769
8770 return {SPF_UNKNOWN, SPNB_NA, false};
8771}
8772
8773/// If the input value is the result of a 'not' op, constant integer, or vector
8774/// splat of a constant integer, return the bitwise-not source value.
8775/// TODO: This could be extended to handle non-splat vector integer constants.
8777 Value *NotV;
8778 if (match(V, m_Not(m_Value(NotV))))
8779 return NotV;
8780
8781 const APInt *C;
8782 if (match(V, m_APInt(C)))
8783 return ConstantInt::get(V->getType(), ~(*C));
8784
8785 return nullptr;
8786}
8787
8788/// Match non-obvious integer minimum and maximum sequences.
8790 Value *CmpLHS, Value *CmpRHS,
8791 Value *TrueVal, Value *FalseVal,
8792 Value *&LHS, Value *&RHS,
8793 unsigned Depth) {
8794 // Assume success. If there's no match, callers should not use these anyway.
8795 LHS = TrueVal;
8796 RHS = FalseVal;
8797
8798 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8800 return SPR;
8801
8802 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8804 return SPR;
8805
8806 // Look through 'not' ops to find disguised min/max.
8807 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8808 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8809 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8810 switch (Pred) {
8811 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8812 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8813 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8814 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8815 default: break;
8816 }
8817 }
8818
8819 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8820 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8821 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8822 switch (Pred) {
8823 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8824 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8825 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8826 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8827 default: break;
8828 }
8829 }
8830
8831 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
8832 return {SPF_UNKNOWN, SPNB_NA, false};
8833
8834 const APInt *C1;
8835 if (!match(CmpRHS, m_APInt(C1)))
8836 return {SPF_UNKNOWN, SPNB_NA, false};
8837
8838 // An unsigned min/max can be written with a signed compare.
8839 const APInt *C2;
8840 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
8841 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
8842 // Is the sign bit set?
8843 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
8844 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
8845 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
8846 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8847
8848 // Is the sign bit clear?
8849 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
8850 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
8851 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
8852 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8853 }
8854
8855 return {SPF_UNKNOWN, SPNB_NA, false};
8856}
8857
8858bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
8859 bool AllowPoison) {
8860 assert(X && Y && "Invalid operand");
8861
8862 auto IsNegationOf = [&](const Value *X, const Value *Y) {
8863 if (!match(X, m_Neg(m_Specific(Y))))
8864 return false;
8865
8866 auto *BO = cast<BinaryOperator>(X);
8867 if (NeedNSW && !BO->hasNoSignedWrap())
8868 return false;
8869
8870 auto *Zero = cast<Constant>(BO->getOperand(0));
8871 if (!AllowPoison && !Zero->isNullValue())
8872 return false;
8873
8874 return true;
8875 };
8876
8877 // X = -Y or Y = -X
8878 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
8879 return true;
8880
8881 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
8882 Value *A, *B;
8883 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
8884 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
8885 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
8887}
8888
8889bool llvm::isKnownInversion(const Value *X, const Value *Y) {
8890 // Handle X = icmp pred A, B, Y = icmp pred A, C.
8891 Value *A, *B, *C;
8892 CmpPredicate Pred1, Pred2;
8893 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
8894 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
8895 return false;
8896
8897 // They must both have samesign flag or not.
8898 if (Pred1.hasSameSign() != Pred2.hasSameSign())
8899 return false;
8900
8901 if (B == C)
8902 return Pred1 == ICmpInst::getInversePredicate(Pred2);
8903
8904 // Try to infer the relationship from constant ranges.
8905 const APInt *RHSC1, *RHSC2;
8906 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
8907 return false;
8908
8909 // Sign bits of two RHSCs should match.
8910 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
8911 return false;
8912
8913 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
8914 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
8915
8916 return CR1.inverse() == CR2;
8917}
8918
8920 SelectPatternNaNBehavior NaNBehavior,
8921 bool Ordered) {
8922 switch (Pred) {
8923 default:
8924 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
8925 case ICmpInst::ICMP_UGT:
8926 case ICmpInst::ICMP_UGE:
8927 return {SPF_UMAX, SPNB_NA, false};
8928 case ICmpInst::ICMP_SGT:
8929 case ICmpInst::ICMP_SGE:
8930 return {SPF_SMAX, SPNB_NA, false};
8931 case ICmpInst::ICMP_ULT:
8932 case ICmpInst::ICMP_ULE:
8933 return {SPF_UMIN, SPNB_NA, false};
8934 case ICmpInst::ICMP_SLT:
8935 case ICmpInst::ICMP_SLE:
8936 return {SPF_SMIN, SPNB_NA, false};
8937 case FCmpInst::FCMP_UGT:
8938 case FCmpInst::FCMP_UGE:
8939 case FCmpInst::FCMP_OGT:
8940 case FCmpInst::FCMP_OGE:
8941 return {SPF_FMAXNUM, NaNBehavior, Ordered};
8942 case FCmpInst::FCMP_ULT:
8943 case FCmpInst::FCMP_ULE:
8944 case FCmpInst::FCMP_OLT:
8945 case FCmpInst::FCMP_OLE:
8946 return {SPF_FMINNUM, NaNBehavior, Ordered};
8947 }
8948}
8949
8950std::optional<std::pair<CmpPredicate, Constant *>>
8953 "Only for relational integer predicates.");
8954 if (isa<UndefValue>(C))
8955 return std::nullopt;
8956
8957 Type *Type = C->getType();
8958 bool IsSigned = ICmpInst::isSigned(Pred);
8959
8961 bool WillIncrement =
8962 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
8963
8964 // Check if the constant operand can be safely incremented/decremented
8965 // without overflowing/underflowing.
8966 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
8967 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
8968 return false;
8969
8970 if (!Pred.hasSameSign())
8971 return true;
8972
8973 // Crossing the corresponding boundary in the other ordering changes the
8974 // sign bit, and therefore changes the poison domain.
8975 return WillIncrement ? !C->isMaxValue(!IsSigned)
8976 : !C->isMinValue(!IsSigned);
8977 };
8978
8979 Constant *SafeReplacementConstant = nullptr;
8980 if (auto *CI = dyn_cast<ConstantInt>(C)) {
8981 // Bail out if the constant can't be safely incremented/decremented.
8982 if (!ConstantIsOk(CI))
8983 return std::nullopt;
8984 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
8985 unsigned NumElts = FVTy->getNumElements();
8986 for (unsigned i = 0; i != NumElts; ++i) {
8987 Constant *Elt = C->getAggregateElement(i);
8988 if (!Elt)
8989 return std::nullopt;
8990
8991 if (isa<UndefValue>(Elt))
8992 continue;
8993
8994 // Bail out if we can't determine if this constant is min/max or if we
8995 // know that this constant is min/max.
8996 auto *CI = dyn_cast<ConstantInt>(Elt);
8997 if (!CI || !ConstantIsOk(CI))
8998 return std::nullopt;
8999
9000 if (!SafeReplacementConstant)
9001 SafeReplacementConstant = CI;
9002 }
9003 } else if (isa<VectorType>(C->getType())) {
9004 // Handle scalable splat
9005 Value *SplatC = C->getSplatValue();
9006 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9007 // Bail out if the constant can't be safely incremented/decremented.
9008 if (!CI || !ConstantIsOk(CI))
9009 return std::nullopt;
9010 } else {
9011 // ConstantExpr?
9012 return std::nullopt;
9013 }
9014
9015 // It may not be safe to change a compare predicate in the presence of
9016 // undefined elements, so replace those elements with the first safe constant
9017 // that we found.
9018 // TODO: in case of poison, it is safe; let's replace undefs only.
9019 if (C->containsUndefOrPoisonElement()) {
9020 assert(SafeReplacementConstant && "Replacement constant not set");
9021 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9022 }
9023
9025 Pred.hasSameSign());
9026
9027 // Increment or decrement the constant.
9028 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9029 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9030
9031 return std::make_pair(NewPred, NewC);
9032}
9033
9035 FastMathFlags FMF,
9036 Value *CmpLHS, Value *CmpRHS,
9037 Value *TrueVal, Value *FalseVal,
9038 Value *&LHS, Value *&RHS,
9039 unsigned Depth) {
9040 if (CmpInst::isFPPredicate(Pred)) {
9041 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9042 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9043 // purpose of identifying min/max. Disregard vector constants with undefined
9044 // elements because those can not be back-propagated for analysis.
9045 Value *OutputZeroVal = nullptr;
9046 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9047 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9048 OutputZeroVal = TrueVal;
9049 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9050 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9051 OutputZeroVal = FalseVal;
9052
9053 if (OutputZeroVal) {
9054 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9055 CmpLHS = OutputZeroVal;
9056 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9057 CmpRHS = OutputZeroVal;
9058 }
9059 }
9060
9061 LHS = CmpLHS;
9062 RHS = CmpRHS;
9063
9064 // Signed zero may return inconsistent results between implementations.
9065 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9066 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9067 // Therefore, we behave conservatively and only proceed if at least one of the
9068 // operands is known to not be zero or if we don't care about signed zero.
9069 if (CmpInst::isFPPredicate(Pred)) {
9070 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9071 !isKnownNonZero(CmpRHS))
9072 return {SPF_UNKNOWN, SPNB_NA, false};
9073 }
9074
9075 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9076 bool Ordered = false;
9077
9078 // When given one NaN and one non-NaN input:
9079 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9080 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9081 // ordered comparison fails), which could be NaN or non-NaN.
9082 // so here we discover exactly what NaN behavior is required/accepted.
9083 if (CmpInst::isFPPredicate(Pred)) {
9084 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9085 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9086
9087 if (LHSSafe && RHSSafe) {
9088 // Both operands are known non-NaN.
9089 NaNBehavior = SPNB_RETURNS_ANY;
9090 Ordered = CmpInst::isOrdered(Pred);
9091 } else if (CmpInst::isOrdered(Pred)) {
9092 // An ordered comparison will return false when given a NaN, so it
9093 // returns the RHS.
9094 Ordered = true;
9095 if (LHSSafe)
9096 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9097 NaNBehavior = SPNB_RETURNS_NAN;
9098 else if (RHSSafe)
9099 NaNBehavior = SPNB_RETURNS_OTHER;
9100 else
9101 // Completely unsafe.
9102 return {SPF_UNKNOWN, SPNB_NA, false};
9103 } else {
9104 Ordered = false;
9105 // An unordered comparison will return true when given a NaN, so it
9106 // returns the LHS.
9107 if (LHSSafe)
9108 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9109 NaNBehavior = SPNB_RETURNS_OTHER;
9110 else if (RHSSafe)
9111 NaNBehavior = SPNB_RETURNS_NAN;
9112 else
9113 // Completely unsafe.
9114 return {SPF_UNKNOWN, SPNB_NA, false};
9115 }
9116 }
9117
9118 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9119 std::swap(CmpLHS, CmpRHS);
9120 Pred = CmpInst::getSwappedPredicate(Pred);
9121 if (NaNBehavior == SPNB_RETURNS_NAN)
9122 NaNBehavior = SPNB_RETURNS_OTHER;
9123 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9124 NaNBehavior = SPNB_RETURNS_NAN;
9125 Ordered = !Ordered;
9126 }
9127
9128 // ([if]cmp X, Y) ? X : Y
9129 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9130 return getSelectPattern(Pred, NaNBehavior, Ordered);
9131
9132 if (isKnownNegation(TrueVal, FalseVal)) {
9133 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9134 // match against either LHS or sign-preserving operations on LHS, like
9135 // sext(LHS), or binary ops that do not wrap in signed sense.
9136 auto CmpLHSOrSExt =
9137 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9138 auto MaybeSExtOrMulCmpLHS =
9139 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9140 m_NSWShl(CmpLHSOrSExt, m_Value()));
9141 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9142 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9143 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9144 // Set the return values. If the compare uses the negated value (-X >s 0),
9145 // swap the return values because the negated value is always 'RHS'.
9146 LHS = TrueVal;
9147 RHS = FalseVal;
9148 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9149 std::swap(LHS, RHS);
9150
9151 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9152 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9153 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9154 return {SPF_ABS, SPNB_NA, false};
9155
9156 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9157 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9158 return {SPF_ABS, SPNB_NA, false};
9159
9160 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9161 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9162 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9163 return {SPF_NABS, SPNB_NA, false};
9164 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9165 // Set the return values. If the compare uses the negated value (-X >s 0),
9166 // swap the return values because the negated value is always 'RHS'.
9167 LHS = FalseVal;
9168 RHS = TrueVal;
9169 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9170 std::swap(LHS, RHS);
9171
9172 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9173 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9174 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9175 return {SPF_NABS, SPNB_NA, false};
9176
9177 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9178 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9179 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9180 return {SPF_ABS, SPNB_NA, false};
9181 }
9182 }
9183
9184 if (CmpInst::isIntPredicate(Pred))
9185 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9186
9187 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9188 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9189 // semantics than minNum. Be conservative in such case.
9190 if (NaNBehavior != SPNB_RETURNS_ANY ||
9191 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9192 !isKnownNonZero(CmpRHS)))
9193 return {SPF_UNKNOWN, SPNB_NA, false};
9194
9195 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9196}
9197
9199 Instruction::CastOps *CastOp) {
9200 const DataLayout &DL = CmpI->getDataLayout();
9201
9202 Constant *CastedTo = nullptr;
9203 switch (*CastOp) {
9204 case Instruction::ZExt:
9205 if (CmpI->isUnsigned())
9206 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9207 break;
9208 case Instruction::SExt:
9209 if (CmpI->isSigned())
9210 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9211 break;
9212 case Instruction::Trunc:
9213 Constant *CmpConst;
9214 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9215 CmpConst->getType() == SrcTy) {
9216 // Here we have the following case:
9217 //
9218 // %cond = cmp iN %x, CmpConst
9219 // %tr = trunc iN %x to iK
9220 // %narrowsel = select i1 %cond, iK %t, iK C
9221 //
9222 // We can always move trunc after select operation:
9223 //
9224 // %cond = cmp iN %x, CmpConst
9225 // %widesel = select i1 %cond, iN %x, iN CmpConst
9226 // %tr = trunc iN %widesel to iK
9227 //
9228 // Note that C could be extended in any way because we don't care about
9229 // upper bits after truncation. It can't be abs pattern, because it would
9230 // look like:
9231 //
9232 // select i1 %cond, x, -x.
9233 //
9234 // So only min/max pattern could be matched. Such match requires widened C
9235 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9236 // CmpConst == C is checked below.
9237 CastedTo = CmpConst;
9238 } else {
9239 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9240 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9241 }
9242 break;
9243 case Instruction::FPTrunc:
9244 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9245 break;
9246 case Instruction::FPExt:
9247 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9248 break;
9249 case Instruction::FPToUI:
9250 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9251 break;
9252 case Instruction::FPToSI:
9253 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9254 break;
9255 case Instruction::UIToFP:
9256 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9257 break;
9258 case Instruction::SIToFP:
9259 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9260 break;
9261 default:
9262 break;
9263 }
9264
9265 if (!CastedTo)
9266 return nullptr;
9267
9268 // Make sure the cast doesn't lose any information.
9269 Constant *CastedBack =
9270 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9271 if (CastedBack && CastedBack != C)
9272 return nullptr;
9273
9274 return CastedTo;
9275}
9276
9277/// Helps to match a select pattern in case of a type mismatch.
9278///
9279/// The function processes the case when type of true and false values of a
9280/// select instruction differs from type of the cmp instruction operands because
9281/// of a cast instruction. The function checks if it is legal to move the cast
9282/// operation after "select". If yes, it returns the new second value of
9283/// "select" (with the assumption that cast is moved):
9284/// 1. As operand of cast instruction when both values of "select" are same cast
9285/// instructions.
9286/// 2. As restored constant (by applying reverse cast operation) when the first
9287/// value of the "select" is a cast operation and the second value is a
9288/// constant. It is implemented in lookThroughCastConst().
9289/// 3. As one operand is cast instruction and the other is not. The operands in
9290/// sel(cmp) are in different type integer.
9291/// NOTE: We return only the new second value because the first value could be
9292/// accessed as operand of cast instruction.
9294 Instruction::CastOps *CastOp) {
9295 auto *Cast1 = dyn_cast<CastInst>(V1);
9296 if (!Cast1)
9297 return nullptr;
9298
9299 *CastOp = Cast1->getOpcode();
9300 Type *SrcTy = Cast1->getSrcTy();
9301 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9302 // If V1 and V2 are both the same cast from the same type, look through V1.
9303 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9304 return Cast2->getOperand(0);
9305 return nullptr;
9306 }
9307
9308 auto *C = dyn_cast<Constant>(V2);
9309 if (C)
9310 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9311
9312 Value *CastedTo = nullptr;
9313 if (*CastOp == Instruction::Trunc) {
9314 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9315 // Here we have the following case:
9316 // %y_ext = sext iK %y to iN
9317 // %cond = cmp iN %x, %y_ext
9318 // %tr = trunc iN %x to iK
9319 // %narrowsel = select i1 %cond, iK %tr, iK %y
9320 //
9321 // We can always move trunc after select operation:
9322 // %y_ext = sext iK %y to iN
9323 // %cond = cmp iN %x, %y_ext
9324 // %widesel = select i1 %cond, iN %x, iN %y_ext
9325 // %tr = trunc iN %widesel to iK
9326 assert(V2->getType() == Cast1->getType() &&
9327 "V2 and Cast1 should be the same type.");
9328 CastedTo = CmpI->getOperand(1);
9329 }
9330 }
9331
9332 return CastedTo;
9333}
9335 Instruction::CastOps *CastOp,
9336 unsigned Depth) {
9338 return {SPF_UNKNOWN, SPNB_NA, false};
9339
9341 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9342
9343 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9344 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9345
9346 Value *TrueVal = SI->getTrueValue();
9347 Value *FalseVal = SI->getFalseValue();
9348
9349 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9350 SI->getFastMathFlagsOrNone(),
9351 CastOp, Depth);
9352}
9353
9355 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9356 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9357 CmpInst::Predicate Pred = CmpI->getPredicate();
9358 Value *CmpLHS = CmpI->getOperand(0);
9359 Value *CmpRHS = CmpI->getOperand(1);
9360 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9361 FMF.setNoNaNs();
9362
9363 // Bail out early.
9364 if (CmpI->isEquality())
9365 return {SPF_UNKNOWN, SPNB_NA, false};
9366
9367 // Deal with type mismatches.
9368 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9369 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9370 // If this is a potential fmin/fmax with a cast to integer, then ignore
9371 // -0.0 because there is no corresponding integer value.
9372 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9373 FMF.setNoSignedZeros();
9374 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9375 cast<CastInst>(TrueVal)->getOperand(0), C,
9376 LHS, RHS, Depth);
9377 }
9378 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9379 // If this is a potential fmin/fmax with a cast to integer, then ignore
9380 // -0.0 because there is no corresponding integer value.
9381 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9382 FMF.setNoSignedZeros();
9383 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9384 C, cast<CastInst>(FalseVal)->getOperand(0),
9385 LHS, RHS, Depth);
9386 }
9387 }
9388 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9389 LHS, RHS, Depth);
9390}
9391
9393 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9394 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9395 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9396 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9397 if (SPF == SPF_FMINNUM)
9398 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9399 if (SPF == SPF_FMAXNUM)
9400 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9401 llvm_unreachable("unhandled!");
9402}
9403
9405 switch (SPF) {
9407 return Intrinsic::umin;
9409 return Intrinsic::umax;
9411 return Intrinsic::smin;
9413 return Intrinsic::smax;
9414 default:
9415 llvm_unreachable("Unexpected SPF");
9416 }
9417}
9418
9420 if (SPF == SPF_SMIN) return SPF_SMAX;
9421 if (SPF == SPF_UMIN) return SPF_UMAX;
9422 if (SPF == SPF_SMAX) return SPF_SMIN;
9423 if (SPF == SPF_UMAX) return SPF_UMIN;
9424 llvm_unreachable("unhandled!");
9425}
9426
9428 switch (MinMaxID) {
9429 case Intrinsic::smax: return Intrinsic::smin;
9430 case Intrinsic::smin: return Intrinsic::smax;
9431 case Intrinsic::umax: return Intrinsic::umin;
9432 case Intrinsic::umin: return Intrinsic::umax;
9433 // Please note that next four intrinsics may produce the same result for
9434 // original and inverted case even if X != Y due to NaN is handled specially.
9435 case Intrinsic::maximum: return Intrinsic::minimum;
9436 case Intrinsic::minimum: return Intrinsic::maximum;
9437 case Intrinsic::maxnum: return Intrinsic::minnum;
9438 case Intrinsic::minnum: return Intrinsic::maxnum;
9439 case Intrinsic::maximumnum:
9440 return Intrinsic::minimumnum;
9441 case Intrinsic::minimumnum:
9442 return Intrinsic::maximumnum;
9443 default: llvm_unreachable("Unexpected intrinsic");
9444 }
9445}
9446
9448 switch (SPF) {
9451 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9452 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9453 default: llvm_unreachable("Unexpected flavor");
9454 }
9455}
9456
9457std::pair<Intrinsic::ID, bool>
9459 // Check if VL contains select instructions that can be folded into a min/max
9460 // vector intrinsic and return the intrinsic if it is possible.
9461 // TODO: Support floating point min/max.
9462 bool AllCmpSingleUse = true;
9463 SelectPatternResult SelectPattern;
9464 SelectPattern.Flavor = SPF_UNKNOWN;
9465 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9466 Value *LHS, *RHS;
9467 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9468 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9469 return false;
9470 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9471 SelectPattern.Flavor != CurrentPattern.Flavor)
9472 return false;
9473 SelectPattern = CurrentPattern;
9474 AllCmpSingleUse &=
9476 return true;
9477 })) {
9478 switch (SelectPattern.Flavor) {
9479 case SPF_SMIN:
9480 return {Intrinsic::smin, AllCmpSingleUse};
9481 case SPF_UMIN:
9482 return {Intrinsic::umin, AllCmpSingleUse};
9483 case SPF_SMAX:
9484 return {Intrinsic::smax, AllCmpSingleUse};
9485 case SPF_UMAX:
9486 return {Intrinsic::umax, AllCmpSingleUse};
9487 case SPF_FMAXNUM:
9488 return {Intrinsic::maxnum, AllCmpSingleUse};
9489 case SPF_FMINNUM:
9490 return {Intrinsic::minnum, AllCmpSingleUse};
9491 default:
9492 llvm_unreachable("unexpected select pattern flavor");
9493 }
9494 }
9495 return {Intrinsic::not_intrinsic, false};
9496}
9497
9498template <typename InstTy>
9499static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9500 Value *&Init, Value *&OtherOp) {
9501 // Handle the case of a simple two-predecessor recurrence PHI.
9502 // There's a lot more that could theoretically be done here, but
9503 // this is sufficient to catch some interesting cases.
9504 // TODO: Expand list -- gep, uadd.sat etc.
9505 if (PN->getNumIncomingValues() != 2)
9506 return false;
9507
9508 for (unsigned I = 0; I != 2; ++I) {
9509 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9510 Operation && Operation->getNumOperands() >= 2) {
9511 Value *LHS = Operation->getOperand(0);
9512 Value *RHS = Operation->getOperand(1);
9513 if (LHS != PN && RHS != PN)
9514 continue;
9515
9516 Inst = Operation;
9517 Init = PN->getIncomingValue(!I);
9518 OtherOp = (LHS == PN) ? RHS : LHS;
9519 return true;
9520 }
9521 }
9522 return false;
9523}
9524
9525template <typename InstTy>
9526static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9527 Value *&Init, Value *&OtherOp0,
9528 Value *&OtherOp1) {
9529 if (PN->getNumIncomingValues() != 2)
9530 return false;
9531
9532 for (unsigned I = 0; I != 2; ++I) {
9533 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9534 Operation && Operation->getNumOperands() >= 3) {
9535 Value *Op0 = Operation->getOperand(0);
9536 Value *Op1 = Operation->getOperand(1);
9537 Value *Op2 = Operation->getOperand(2);
9538
9539 if (Op0 != PN && Op1 != PN && Op2 != PN)
9540 continue;
9541
9542 Inst = Operation;
9543 Init = PN->getIncomingValue(!I);
9544 if (Op0 == PN) {
9545 OtherOp0 = Op1;
9546 OtherOp1 = Op2;
9547 } else if (Op1 == PN) {
9548 OtherOp0 = Op0;
9549 OtherOp1 = Op2;
9550 } else {
9551 OtherOp0 = Op0;
9552 OtherOp1 = Op1;
9553 }
9554 return true;
9555 }
9556 }
9557 return false;
9558}
9560 Value *&Start, Value *&Step) {
9561 // We try to match a recurrence of the form:
9562 // %iv = [Start, %entry], [%iv.next, %backedge]
9563 // %iv.next = binop %iv, Step
9564 // Or:
9565 // %iv = [Start, %entry], [%iv.next, %backedge]
9566 // %iv.next = binop Step, %iv
9567 return matchTwoInputRecurrence(P, BO, Start, Step);
9568}
9569
9571 Value *&Start, Value *&Step) {
9572 BinaryOperator *BO = nullptr;
9573 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9574 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9575}
9576
9578 PHINode *&P, Value *&Init,
9579 Value *&OtherOp) {
9580 // Binary intrinsics only supported for now.
9581 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9582 I->getType() != I->getArgOperand(1)->getType())
9583 return false;
9584
9585 IntrinsicInst *II = nullptr;
9586 P = dyn_cast<PHINode>(I->getArgOperand(0));
9587 if (!P)
9588 P = dyn_cast<PHINode>(I->getArgOperand(1));
9589
9590 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9591}
9592
9594 PHINode *&P, Value *&Init,
9595 Value *&OtherOp0,
9596 Value *&OtherOp1) {
9597 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9598 I->getType() != I->getArgOperand(1)->getType() ||
9599 I->getType() != I->getArgOperand(2)->getType())
9600 return false;
9601 IntrinsicInst *II = nullptr;
9602 P = dyn_cast<PHINode>(I->getArgOperand(0));
9603 if (!P) {
9604 P = dyn_cast<PHINode>(I->getArgOperand(1));
9605 if (!P)
9606 P = dyn_cast<PHINode>(I->getArgOperand(2));
9607 }
9608 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9609 II == I;
9610}
9611
9612/// Return true if "icmp Pred LHS RHS" is always true.
9614 const Value *RHS) {
9615 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9616 return true;
9617
9618 switch (Pred) {
9619 default:
9620 return false;
9621
9622 case CmpInst::ICMP_SLE: {
9623 const APInt *C;
9624
9625 // LHS s<= LHS +_{nsw} C if C >= 0
9626 // LHS s<= LHS | C if C >= 0
9627 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9629 return !C->isNegative();
9630
9631 // LHS s<= smax(LHS, V) for any V
9633 return true;
9634
9635 // smin(RHS, V) s<= RHS for any V
9637 return true;
9638
9639 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9640 const Value *X;
9641 const APInt *CLHS, *CRHS;
9642 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9644 return CLHS->sle(*CRHS);
9645
9646 return false;
9647 }
9648
9649 case CmpInst::ICMP_ULE: {
9650 // LHS u<= LHS +_{nuw} V for any V
9651 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9653 return true;
9654
9655 // LHS u<= LHS | V for any V
9656 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9657 return true;
9658
9659 // LHS u<= umax(LHS, V) for any V
9661 return true;
9662
9663 // RHS >> V u<= RHS for any V
9664 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9665 return true;
9666
9667 // RHS u/ C_ugt_1 u<= RHS
9668 const APInt *C;
9669 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9670 return true;
9671
9672 // RHS & V u<= RHS for any V
9674 return true;
9675
9676 // umin(RHS, V) u<= RHS for any V
9678 return true;
9679
9680 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9681 const Value *X;
9682 const APInt *CLHS, *CRHS;
9683 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9685 return CLHS->ule(*CRHS);
9686
9687 return false;
9688 }
9689 }
9690}
9691
9692/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9693/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9694static std::optional<bool>
9696 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9697 switch (Pred) {
9698 default:
9699 return std::nullopt;
9700
9701 case CmpInst::ICMP_SLT:
9702 case CmpInst::ICMP_SLE:
9703 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9705 return true;
9706 return std::nullopt;
9707
9708 case CmpInst::ICMP_SGT:
9709 case CmpInst::ICMP_SGE:
9710 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9712 return true;
9713 return std::nullopt;
9714
9715 case CmpInst::ICMP_ULT:
9716 case CmpInst::ICMP_ULE:
9717 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9719 return true;
9720 return std::nullopt;
9721
9722 case CmpInst::ICMP_UGT:
9723 case CmpInst::ICMP_UGE:
9724 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9726 return true;
9727 return std::nullopt;
9728 }
9729}
9730
9731/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9732/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9733/// Otherwise, return std::nullopt if we can't infer anything.
9734static std::optional<bool>
9736 CmpPredicate RPred, const ConstantRange &RCR) {
9737 auto CRImpliesPred = [&](ConstantRange CR,
9738 CmpInst::Predicate Pred) -> std::optional<bool> {
9739 // If all true values for lhs and true for rhs, lhs implies rhs
9740 if (CR.icmp(Pred, RCR))
9741 return true;
9742
9743 // If there is no overlap, lhs implies not rhs
9744 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9745 return false;
9746
9747 return std::nullopt;
9748 };
9749 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9750 RPred))
9751 return Res;
9752 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9754 : LPred.dropSameSign();
9756 : RPred.dropSameSign();
9757 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9758 RPred);
9759 }
9760 return std::nullopt;
9761}
9762
9763/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9764/// is true. Return false if LHS implies RHS is false. Otherwise, return
9765/// std::nullopt if we can't infer anything.
9766static std::optional<bool>
9767isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9768 CmpPredicate RPred, const Value *R0, const Value *R1,
9769 const DataLayout &DL, bool LHSIsTrue) {
9770 // The rest of the logic assumes the LHS condition is true. If that's not the
9771 // case, invert the predicate to make it so.
9772 if (!LHSIsTrue)
9773 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9774
9775 // We can have non-canonical operands, so try to normalize any common operand
9776 // to L0/R0.
9777 if (L0 == R1) {
9778 std::swap(R0, R1);
9779 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9780 }
9781 if (R0 == L1) {
9782 std::swap(L0, L1);
9783 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9784 }
9785 if (L1 == R1) {
9786 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9787 if (L0 != R0 || match(L0, m_ImmConstant())) {
9788 std::swap(L0, L1);
9789 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9790 std::swap(R0, R1);
9791 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9792 }
9793 }
9794
9795 // See if we can infer anything if operand-0 matches and we have at least one
9796 // constant.
9797 const APInt *Unused;
9798 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9799 // Potential TODO: We could also further use the constant range of L0/R0 to
9800 // further constraint the constant ranges. At the moment this leads to
9801 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9802 // C1` (see discussion: D58633).
9803 SimplifyQuery SQ(DL);
9808
9809 // Even if L1/R1 are not both constant, we can still sometimes deduce
9810 // relationship from a single constant. For example X u> Y implies X != 0.
9811 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9812 return R;
9813 // If both L1/R1 were exact constant ranges and we didn't get anything
9814 // here, we won't be able to deduce this.
9815 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9816 return std::nullopt;
9817 }
9818
9819 // Can we infer anything when the two compares have matching operands?
9820 if (L0 == R0 && L1 == R1)
9821 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9822
9823 // It only really makes sense in the context of signed comparison for "X - Y
9824 // must be positive if X >= Y and no overflow".
9825 // Take SGT as an example: L0:x > L1:y and C >= 0
9826 // ==> R0:(x -nsw y) < R1:(-C) is false
9827 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
9828 if ((SignedLPred == ICmpInst::ICMP_SGT ||
9829 SignedLPred == ICmpInst::ICMP_SGE) &&
9830 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9831 if (match(R1, m_NonPositive()) &&
9832 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
9833 return false;
9834 }
9835
9836 // Take SLT as an example: L0:x < L1:y and C <= 0
9837 // ==> R0:(x -nsw y) < R1:(-C) is true
9838 if ((SignedLPred == ICmpInst::ICMP_SLT ||
9839 SignedLPred == ICmpInst::ICMP_SLE) &&
9840 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9841 if (match(R1, m_NonNegative()) &&
9842 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
9843 return true;
9844 }
9845
9846 // a - b == NonZero -> a != b
9847 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
9848 const APInt *L1C;
9849 Value *A, *B;
9850 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
9851 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
9852 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
9853 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
9858 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
9859 }
9860
9861 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
9862 if (L0 == R0 &&
9863 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
9864 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
9865 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
9866 return CmpPredicate::getMatching(LPred, RPred).has_value();
9867
9868 if (auto P = CmpPredicate::getMatching(LPred, RPred))
9869 return isImpliedCondOperands(*P, L0, L1, R0, R1);
9870
9871 return std::nullopt;
9872}
9873
9874/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9875/// is true. Return false if LHS implies RHS is false. Otherwise, return
9876/// std::nullopt if we can't infer anything.
9877static std::optional<bool>
9879 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
9880 const DataLayout &DL, bool LHSIsTrue) {
9881 // The rest of the logic assumes the LHS condition is true. If that's not the
9882 // case, invert the predicate to make it so.
9883 if (!LHSIsTrue)
9884 LPred = FCmpInst::getInversePredicate(LPred);
9885
9886 // We can have non-canonical operands, so try to normalize any common operand
9887 // to L0/R0.
9888 if (L0 == R1) {
9889 std::swap(R0, R1);
9890 RPred = FCmpInst::getSwappedPredicate(RPred);
9891 }
9892 if (R0 == L1) {
9893 std::swap(L0, L1);
9894 LPred = FCmpInst::getSwappedPredicate(LPred);
9895 }
9896 if (L1 == R1) {
9897 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9898 if (L0 != R0 || match(L0, m_ImmConstant())) {
9899 std::swap(L0, L1);
9900 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9901 std::swap(R0, R1);
9902 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9903 }
9904 }
9905
9906 // Can we infer anything when the two compares have matching operands?
9907 if (L0 == R0 && L1 == R1) {
9908 if ((LPred & RPred) == LPred)
9909 return true;
9910 if ((LPred & ~RPred) == LPred)
9911 return false;
9912 }
9913
9914 // See if we can infer anything if operand-0 matches and we have at least one
9915 // constant.
9916 const APFloat *L1C, *R1C;
9917 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
9918 if (std::optional<ConstantFPRange> DomCR =
9920 if (std::optional<ConstantFPRange> ImpliedCR =
9922 if (ImpliedCR->contains(*DomCR))
9923 return true;
9924 }
9925 if (std::optional<ConstantFPRange> ImpliedCR =
9927 FCmpInst::getInversePredicate(RPred), *R1C)) {
9928 if (ImpliedCR->contains(*DomCR))
9929 return false;
9930 }
9931 }
9932 }
9933
9934 return std::nullopt;
9935}
9936
9937/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
9938/// false. Otherwise, return std::nullopt if we can't infer anything. We
9939/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
9940/// instruction.
9941static std::optional<bool>
9943 const Value *RHSOp0, const Value *RHSOp1,
9944 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
9945 // The LHS must be an 'or', 'and', or a 'select' instruction.
9946 assert((LHS->getOpcode() == Instruction::And ||
9947 LHS->getOpcode() == Instruction::Or ||
9948 LHS->getOpcode() == Instruction::Select) &&
9949 "Expected LHS to be 'and', 'or', or 'select'.");
9950
9951 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
9952
9953 // If the result of an 'or' is false, then we know both legs of the 'or' are
9954 // false. Similarly, if the result of an 'and' is true, then we know both
9955 // legs of the 'and' are true.
9956 const Value *ALHS, *ARHS;
9957 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
9958 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
9959 // FIXME: Make this non-recursion.
9960 if (std::optional<bool> Implication = isImpliedCondition(
9961 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
9962 return Implication;
9963 if (std::optional<bool> Implication = isImpliedCondition(
9964 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
9965 return Implication;
9966 return std::nullopt;
9967 }
9968 return std::nullopt;
9969}
9970
9971std::optional<bool>
9973 const Value *RHSOp0, const Value *RHSOp1,
9974 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
9975 // Bail out when we hit the limit.
9977 return std::nullopt;
9978
9979 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
9980 // example.
9981 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
9982 return std::nullopt;
9983
9984 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
9985 "Expected integer type only!");
9986
9987 // Match not
9988 if (match(LHS, m_Not(m_Value(LHS))))
9989 LHSIsTrue = !LHSIsTrue;
9990
9991 // Both LHS and RHS are icmps.
9992 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
9993 CmpPredicate LHSPred;
9994 Value *LHSOp0, *LHSOp1;
9995 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
9996 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
9997 RHSOp1, DL, LHSIsTrue);
9998 } else {
9999 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10000 "Expected floating point type only!");
10001 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10002 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10003 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10004 DL, LHSIsTrue);
10005 }
10006
10007 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10008 /// the RHS to be an icmp.
10009 /// FIXME: Add support for and/or/select on the RHS.
10010 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10011 if ((LHSI->getOpcode() == Instruction::And ||
10012 LHSI->getOpcode() == Instruction::Or ||
10013 LHSI->getOpcode() == Instruction::Select))
10014 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10015 Depth);
10016 }
10017 return std::nullopt;
10018}
10019
10020std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10021 const DataLayout &DL,
10022 bool LHSIsTrue, unsigned Depth) {
10023 // LHS ==> RHS by definition
10024 if (LHS == RHS)
10025 return LHSIsTrue;
10026
10027 // Match not
10028 bool InvertRHS = false;
10029 if (match(RHS, m_Not(m_Value(RHS)))) {
10030 if (LHS == RHS)
10031 return !LHSIsTrue;
10032 InvertRHS = true;
10033 }
10034
10035 CmpPredicate RHSPred;
10036 Value *RHSOp0, *RHSOp1;
10037 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10038 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10039 LHSIsTrue, Depth))
10040 return InvertRHS ? !*Implied : *Implied;
10041 return std::nullopt;
10042 }
10043 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10044 if (auto Implied = isImpliedCondition(
10045 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10046 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10047 return InvertRHS ? !*Implied : *Implied;
10048 return std::nullopt;
10049 }
10050
10052 return std::nullopt;
10053
10054 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10055 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10056 const Value *RHS1, *RHS2;
10057 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10058 if (std::optional<bool> Imp =
10059 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10060 if (*Imp == true)
10061 return !InvertRHS;
10062 if (std::optional<bool> Imp =
10063 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10064 if (*Imp == true)
10065 return !InvertRHS;
10066 }
10067 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10068 if (std::optional<bool> Imp =
10069 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10070 if (*Imp == false)
10071 return InvertRHS;
10072 if (std::optional<bool> Imp =
10073 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10074 if (*Imp == false)
10075 return InvertRHS;
10076 }
10077
10078 return std::nullopt;
10079}
10080
10081// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10082// condition dominating ContextI or nullptr, if no condition is found.
10083static std::pair<Value *, bool>
10085 if (!ContextI || !ContextI->getParent())
10086 return {nullptr, false};
10087
10088 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10089 // dominator tree (eg, from a SimplifyQuery) instead?
10090 const BasicBlock *ContextBB = ContextI->getParent();
10091 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10092 if (!PredBB)
10093 return {nullptr, false};
10094
10095 // We need a conditional branch in the predecessor.
10096 Value *PredCond;
10097 BasicBlock *TrueBB, *FalseBB;
10098 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10099 return {nullptr, false};
10100
10101 // The branch should get simplified. Don't bother simplifying this condition.
10102 if (TrueBB == FalseBB)
10103 return {nullptr, false};
10104
10105 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10106 "Predecessor block does not point to successor?");
10107
10108 // Is this condition implied by the predecessor condition?
10109 return {PredCond, TrueBB == ContextBB};
10110}
10111
10112std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10113 const Instruction *ContextI,
10114 const DataLayout &DL) {
10115 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10116 auto PredCond = getDomPredecessorCondition(ContextI);
10117 if (PredCond.first)
10118 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10119 return std::nullopt;
10120}
10121
10123 const Value *LHS,
10124 const Value *RHS,
10125 const Instruction *ContextI,
10126 const DataLayout &DL) {
10127 auto PredCond = getDomPredecessorCondition(ContextI);
10128 if (PredCond.first)
10129 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10130 PredCond.second);
10131 return std::nullopt;
10132}
10133
10135 APInt &Upper, const InstrInfoQuery &IIQ,
10136 bool PreferSignedRange) {
10137 unsigned Width = Lower.getBitWidth();
10138 const APInt *C;
10139 switch (BO.getOpcode()) {
10140 case Instruction::Sub:
10141 if (match(BO.getOperand(0), m_APInt(C))) {
10142 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10143 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10144
10145 // If the caller expects a signed compare, then try to use a signed range.
10146 // Otherwise if both no-wraps are set, use the unsigned range because it
10147 // is never larger than the signed range. Example:
10148 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10149 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10150 if (PreferSignedRange && HasNSW && HasNUW)
10151 HasNUW = false;
10152
10153 if (HasNUW) {
10154 // 'sub nuw c, x' produces [0, C].
10155 Upper = *C + 1;
10156 } else if (HasNSW) {
10157 if (C->isNegative()) {
10158 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10160 Upper = *C - APInt::getSignedMaxValue(Width);
10161 } else {
10162 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10163 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10164 Lower = *C - APInt::getSignedMaxValue(Width);
10166 }
10167 }
10168 }
10169 break;
10170 case Instruction::Add:
10171 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10172 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10173 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10174
10175 // If the caller expects a signed compare, then try to use a signed
10176 // range. Otherwise if both no-wraps are set, use the unsigned range
10177 // because it is never larger than the signed range. Example: "add nuw
10178 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10179 if (PreferSignedRange && HasNSW && HasNUW)
10180 HasNUW = false;
10181
10182 if (HasNUW) {
10183 // 'add nuw x, C' produces [C, UINT_MAX].
10184 Lower = *C;
10185 } else if (HasNSW) {
10186 if (C->isNegative()) {
10187 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10189 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10190 } else {
10191 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10192 Lower = APInt::getSignedMinValue(Width) + *C;
10193 Upper = APInt::getSignedMaxValue(Width) + 1;
10194 }
10195 }
10196 }
10197 break;
10198
10199 case Instruction::And:
10200 if (match(BO.getOperand(1), m_APInt(C)))
10201 // 'and x, C' produces [0, C].
10202 Upper = *C + 1;
10203 // X & -X is a power of two or zero. So we can cap the value at max power of
10204 // two.
10205 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10206 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10207 Upper = APInt::getSignedMinValue(Width) + 1;
10208 break;
10209
10210 case Instruction::Or:
10211 if (match(BO.getOperand(1), m_APInt(C)))
10212 // 'or x, C' produces [C, UINT_MAX].
10213 Lower = *C;
10214 break;
10215
10216 case Instruction::AShr:
10217 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10218 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10220 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10221 } else if (match(BO.getOperand(0), m_APInt(C))) {
10222 unsigned ShiftAmount = Width - 1;
10223 if (!C->isZero() && IIQ.isExact(&BO))
10224 ShiftAmount = C->countr_zero();
10225 if (C->isNegative()) {
10226 // 'ashr C, x' produces [C, C >> (Width-1)]
10227 Lower = *C;
10228 Upper = C->ashr(ShiftAmount) + 1;
10229 } else {
10230 // 'ashr C, x' produces [C >> (Width-1), C]
10231 Lower = C->ashr(ShiftAmount);
10232 Upper = *C + 1;
10233 }
10234 }
10235 break;
10236
10237 case Instruction::LShr:
10238 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10239 // 'lshr x, C' produces [0, UINT_MAX >> C].
10240 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10241 } else if (match(BO.getOperand(0), m_APInt(C))) {
10242 // 'lshr C, x' produces [C >> (Width-1), C].
10243 unsigned ShiftAmount = Width - 1;
10244 if (!C->isZero() && IIQ.isExact(&BO))
10245 ShiftAmount = C->countr_zero();
10246 Lower = C->lshr(ShiftAmount);
10247 Upper = *C + 1;
10248 }
10249 break;
10250
10251 case Instruction::Shl:
10252 if (match(BO.getOperand(0), m_APInt(C))) {
10253 if (IIQ.hasNoUnsignedWrap(&BO)) {
10254 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10255 Lower = *C;
10256 Upper = Lower.shl(Lower.countl_zero()) + 1;
10257 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10258 if (C->isNegative()) {
10259 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10260 unsigned ShiftAmount = C->countl_one() - 1;
10261 Lower = C->shl(ShiftAmount);
10262 Upper = *C + 1;
10263 } else {
10264 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10265 unsigned ShiftAmount = C->countl_zero() - 1;
10266 Lower = *C;
10267 Upper = C->shl(ShiftAmount) + 1;
10268 }
10269 } else {
10270 // If lowbit is set, value can never be zero.
10271 if ((*C)[0])
10272 Lower = APInt::getOneBitSet(Width, 0);
10273 // If we are shifting a constant the largest it can be is if the longest
10274 // sequence of consecutive ones is shifted to the highbits (breaking
10275 // ties for which sequence is higher). At the moment we take a liberal
10276 // upper bound on this by just popcounting the constant.
10277 // TODO: There may be a bitwise trick for it longest/highest
10278 // consecutative sequence of ones (naive method is O(Width) loop).
10279 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10280 }
10281 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10282 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10283 }
10284 break;
10285
10286 case Instruction::SDiv:
10287 if (match(BO.getOperand(1), m_APInt(C))) {
10288 APInt IntMin = APInt::getSignedMinValue(Width);
10289 APInt IntMax = APInt::getSignedMaxValue(Width);
10290 if (C->isAllOnes()) {
10291 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10292 // where C != -1 and C != 0 and C != 1
10293 Lower = IntMin + 1;
10294 Upper = IntMax + 1;
10295 } else if (C->countl_zero() < Width - 1) {
10296 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10297 // where C != -1 and C != 0 and C != 1
10298 Lower = IntMin.sdiv(*C);
10299 Upper = IntMax.sdiv(*C);
10300 if (Lower.sgt(Upper))
10302 Upper = Upper + 1;
10303 assert(Upper != Lower && "Upper part of range has wrapped!");
10304 }
10305 } else if (match(BO.getOperand(0), m_APInt(C))) {
10306 if (C->isMinSignedValue()) {
10307 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10308 Lower = *C;
10309 Upper = Lower.lshr(1) + 1;
10310 } else {
10311 // 'sdiv C, x' produces [-|C|, |C|].
10312 Upper = C->abs() + 1;
10313 Lower = (-Upper) + 1;
10314 }
10315 }
10316 break;
10317
10318 case Instruction::UDiv:
10319 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10320 // 'udiv x, C' produces [0, UINT_MAX / C].
10321 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10322 } else if (match(BO.getOperand(0), m_APInt(C))) {
10323 // 'udiv C, x' produces [0, C].
10324 Upper = *C + 1;
10325 }
10326 break;
10327
10328 case Instruction::SRem:
10329 if (match(BO.getOperand(1), m_APInt(C))) {
10330 // 'srem x, C' produces (-|C|, |C|).
10331 Upper = C->abs();
10332 Lower = (-Upper) + 1;
10333 } else if (match(BO.getOperand(0), m_APInt(C))) {
10334 if (C->isNegative()) {
10335 // 'srem -|C|, x' produces [-|C|, 0].
10336 Upper = 1;
10337 Lower = *C;
10338 } else {
10339 // 'srem |C|, x' produces [0, |C|].
10340 Upper = *C + 1;
10341 }
10342 }
10343 break;
10344
10345 case Instruction::URem:
10346 if (match(BO.getOperand(1), m_APInt(C)))
10347 // 'urem x, C' produces [0, C).
10348 Upper = *C;
10349 else if (match(BO.getOperand(0), m_APInt(C)))
10350 // 'urem C, x' produces [0, C].
10351 Upper = *C + 1;
10352 break;
10353
10354 default:
10355 break;
10356 }
10357}
10358
10360 bool UseInstrInfo) {
10361 unsigned Width = II.getType()->getScalarSizeInBits();
10362 const APInt *C;
10363 switch (II.getIntrinsicID()) {
10364 case Intrinsic::ctlz:
10365 case Intrinsic::cttz: {
10366 APInt Upper(Width, Width);
10367 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10368 Upper += 1;
10369 // Maximum of set/clear bits is the bit width.
10371 }
10372 case Intrinsic::ctpop:
10373 // Maximum of set/clear bits is the bit width.
10375 APInt(Width, Width) + 1);
10376 case Intrinsic::uadd_sat:
10377 // uadd.sat(x, C) produces [C, UINT_MAX].
10378 if (match(II.getOperand(0), m_APInt(C)) ||
10379 match(II.getOperand(1), m_APInt(C)))
10381 break;
10382 case Intrinsic::sadd_sat:
10383 if (match(II.getOperand(0), m_APInt(C)) ||
10384 match(II.getOperand(1), m_APInt(C))) {
10385 if (C->isNegative())
10386 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10388 APInt::getSignedMaxValue(Width) + *C +
10389 1);
10390
10391 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10393 APInt::getSignedMaxValue(Width) + 1);
10394 }
10395 break;
10396 case Intrinsic::usub_sat:
10397 // usub.sat(C, x) produces [0, C].
10398 if (match(II.getOperand(0), m_APInt(C)))
10399 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10400
10401 // usub.sat(x, C) produces [0, UINT_MAX - C].
10402 if (match(II.getOperand(1), m_APInt(C)))
10404 APInt::getMaxValue(Width) - *C + 1);
10405 break;
10406 case Intrinsic::ssub_sat:
10407 if (match(II.getOperand(0), m_APInt(C))) {
10408 if (C->isNegative())
10409 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10411 *C - APInt::getSignedMinValue(Width) +
10412 1);
10413
10414 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10416 APInt::getSignedMaxValue(Width) + 1);
10417 } else if (match(II.getOperand(1), m_APInt(C))) {
10418 if (C->isNegative())
10419 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10421 APInt::getSignedMaxValue(Width) + 1);
10422
10423 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10425 APInt::getSignedMaxValue(Width) - *C +
10426 1);
10427 }
10428 break;
10429 case Intrinsic::umin:
10430 case Intrinsic::umax:
10431 case Intrinsic::smin:
10432 case Intrinsic::smax:
10433 if (!match(II.getOperand(0), m_APInt(C)) &&
10434 !match(II.getOperand(1), m_APInt(C)))
10435 break;
10436
10437 switch (II.getIntrinsicID()) {
10438 case Intrinsic::umin:
10439 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10440 case Intrinsic::umax:
10442 case Intrinsic::smin:
10444 *C + 1);
10445 case Intrinsic::smax:
10447 APInt::getSignedMaxValue(Width) + 1);
10448 default:
10449 llvm_unreachable("Must be min/max intrinsic");
10450 }
10451 break;
10452 case Intrinsic::abs:
10453 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10454 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10455 if (match(II.getOperand(1), m_One()))
10457 APInt::getSignedMaxValue(Width) + 1);
10458
10460 APInt::getSignedMinValue(Width) + 1);
10461 case Intrinsic::vscale:
10462 if (!II.getParent() || !II.getFunction())
10463 break;
10464 return getVScaleRange(II.getFunction(), Width);
10465 default:
10466 break;
10467 }
10468
10469 return ConstantRange::getFull(Width);
10470}
10471
10473 const InstrInfoQuery &IIQ) {
10474 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10475 const Value *LHS = nullptr, *RHS = nullptr;
10477 if (R.Flavor == SPF_UNKNOWN)
10478 return ConstantRange::getFull(BitWidth);
10479
10480 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10481 // If the negation part of the abs (in RHS) has the NSW flag,
10482 // then the result of abs(X) is [0..SIGNED_MAX],
10483 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10484 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10488
10491 }
10492
10493 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10494 // The result of -abs(X) is <= 0.
10496 APInt(BitWidth, 1));
10497 }
10498
10499 const APInt *C;
10500 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10501 return ConstantRange::getFull(BitWidth);
10502
10503 switch (R.Flavor) {
10504 case SPF_UMIN:
10506 case SPF_UMAX:
10508 case SPF_SMIN:
10510 *C + 1);
10511 case SPF_SMAX:
10514 default:
10515 return ConstantRange::getFull(BitWidth);
10516 }
10517}
10518
10520 // The maximum representable value of a half is 65504. For floats the maximum
10521 // value is 3.4e38 which requires roughly 129 bits.
10522 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10523 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10524 return;
10525 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10526 Lower = APInt(BitWidth, -65504, true);
10527 Upper = APInt(BitWidth, 65505);
10528 }
10529
10530 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10531 // For a fptoui the lower limit is left as 0.
10532 Upper = APInt(BitWidth, 65505);
10533 }
10534}
10535
10537 const SimplifyQuery &SQ,
10538 unsigned Depth) {
10539 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10540
10542 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10543
10544 if (auto *C = dyn_cast<Constant>(V))
10545 return C->toConstantRange();
10546
10547 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10548 ConstantRange CR = ConstantRange::getFull(BitWidth);
10549 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10550 APInt Lower = APInt(BitWidth, 0);
10551 APInt Upper = APInt(BitWidth, 0);
10552 // TODO: Return ConstantRange.
10553 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10555 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10557 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10558 ConstantRange CRTrue =
10559 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10560 ConstantRange CRFalse =
10561 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10562 CR = CRTrue.unionWith(CRFalse);
10564 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10565 ConstantRange SrcCR =
10566 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10567 CR = SrcCR.truncate(BitWidth);
10568 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10569 APInt Lower = APInt(BitWidth, 0);
10570 APInt Upper = APInt(BitWidth, 0);
10571 // TODO: Return ConstantRange.
10574 } else if (const auto *A = dyn_cast<Argument>(V))
10575 if (std::optional<ConstantRange> Range = A->getRange())
10576 CR = *Range;
10577
10578 if (auto *I = dyn_cast<Instruction>(V)) {
10579 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10581
10582 Value *FrexpSrc;
10583 if (const auto *CB = dyn_cast<CallBase>(V)) {
10584 if (std::optional<ConstantRange> Range = CB->getRange())
10585 CR = CR.intersectWith(*Range);
10587 m_Value(FrexpSrc))))) {
10588 const fltSemantics &FltSem =
10589 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10590 // It should be possible to implement this for any type, but this logic
10591 // only computes the range assuming standard subnormal handling.
10592 if (APFloat::isIEEELikeFP(FltSem)) {
10594 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10595
10596 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10597 // constrain its range when the source can be neither.
10598 if (KnownSrc.isKnownNeverInfOrNaN()) {
10599 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10600
10601 // Offset to find the true minimum exponent value for a denormal.
10602 if (!KnownSrc.isKnownNeverSubnormal())
10603 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10604
10605 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10606
10607 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10609
10610 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10611 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10612
10613 MinExp = std::max(AdjustedMin, MinExp);
10614 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10615 MaxExp);
10616
10618 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10619 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10620 /*isSigned=*/true));
10621 }
10622 }
10623 }
10624 }
10625
10626 if (SQ.CxtI && SQ.AC) {
10627 // Try to restrict the range based on information from assumptions.
10628 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10629 if (!AssumeVH)
10630 continue;
10631 CallInst *I = cast<CallInst>(AssumeVH);
10632 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10633 "Got assumption for the wrong function!");
10634 assert(I->getIntrinsicID() == Intrinsic::assume &&
10635 "must be an assume intrinsic");
10636
10637 if (!isValidAssumeForContext(I, SQ))
10638 continue;
10639 Value *Arg = I->getArgOperand(0);
10640 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10641 // Currently we just use information from comparisons.
10642 if (!Cmp || Cmp->getOperand(0) != V)
10643 continue;
10644 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10645 ConstantRange RHS =
10646 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10647 SQ.getWithInstruction(I), Depth + 1);
10648 CR = CR.intersectWith(
10649 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10650 }
10651 }
10652
10653 return CR;
10654}
10655
10656static void
10658 function_ref<void(Value *)> InsertAffected) {
10659 assert(V != nullptr);
10660 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10661 InsertAffected(V);
10662 } else if (auto *I = dyn_cast<Instruction>(V)) {
10663 InsertAffected(V);
10664
10665 // Peek through unary operators to find the source of the condition.
10666 Value *Op;
10668 m_Trunc(m_Value(Op))))) {
10670 InsertAffected(Op);
10671 }
10672 }
10673}
10674
10676 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10677 auto AddAffected = [&InsertAffected](Value *V) {
10678 addValueAffectedByCondition(V, InsertAffected);
10679 };
10680
10681 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10682 if (IsAssume) {
10683 AddAffected(LHS);
10684 AddAffected(RHS);
10685 } else if (match(RHS, m_Constant()))
10686 AddAffected(LHS);
10687 };
10688
10689 SmallVector<Value *, 8> Worklist;
10691 Worklist.push_back(Cond);
10692 while (!Worklist.empty()) {
10693 Value *V = Worklist.pop_back_val();
10694 if (!Visited.insert(V).second)
10695 continue;
10696
10697 CmpPredicate Pred;
10698 Value *A, *B, *X;
10699
10700 if (IsAssume) {
10701 AddAffected(V);
10702 if (match(V, m_Not(m_Value(X))))
10703 AddAffected(X);
10704 }
10705
10706 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10707 // assume(A && B) is split to -> assume(A); assume(B);
10708 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10709 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10710 // enough information to be worth handling (intersection of information as
10711 // opposed to union).
10712 if (!IsAssume) {
10713 Worklist.push_back(A);
10714 Worklist.push_back(B);
10715 }
10716 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10717 bool HasRHSC = match(B, m_ConstantInt());
10718 if (ICmpInst::isEquality(Pred)) {
10719 AddAffected(A);
10720 if (IsAssume)
10721 AddAffected(B);
10722 if (HasRHSC) {
10723 Value *Y;
10724 // (X << C) or (X >>_s C) or (X >>_u C).
10725 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10726 AddAffected(X);
10727 // (X & C) or (X | C).
10728 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10729 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10730 AddAffected(X);
10731 AddAffected(Y);
10732 }
10733 // X - Y
10734 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10735 AddAffected(X);
10736 AddAffected(Y);
10737 }
10738 }
10739 } else {
10740 AddCmpOperands(A, B);
10741 if (HasRHSC) {
10742 // Handle (A + C1) u< C2, which is the canonical form of
10743 // A > C3 && A < C4.
10745 AddAffected(X);
10746
10747 if (ICmpInst::isUnsigned(Pred)) {
10748 Value *Y;
10749 // X & Y u> C -> X >u C && Y >u C
10750 // X | Y u< C -> X u< C && Y u< C
10751 // X nuw+ Y u< C -> X u< C && Y u< C
10752 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10753 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10754 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10755 AddAffected(X);
10756 AddAffected(Y);
10757 }
10758 // X nuw- Y u> C -> X u> C
10759 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10760 AddAffected(X);
10761 }
10762 }
10763
10764 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10765 // by computeKnownFPClass().
10767 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10768 InsertAffected(X);
10769 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10770 InsertAffected(X);
10771 }
10772 }
10773
10774 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10775 Value *SquareOp = nullptr;
10776 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10777 AddAffected(SquareOp);
10778 };
10779 AddNuwSquareOperand(A);
10780 AddNuwSquareOperand(B);
10781
10782 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10783 AddAffected(X);
10784 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10785 AddCmpOperands(A, B);
10786
10787 // fcmp fneg(x), y
10788 // fcmp fabs(x), y
10789 // fcmp fneg(fabs(x)), y
10790 if (match(A, m_FNeg(m_Value(A))))
10791 AddAffected(A);
10792 if (match(A, m_FAbs(m_Value(A))))
10793 AddAffected(A);
10794
10796 m_Value()))) {
10797 // Handle patterns that computeKnownFPClass() support.
10798 AddAffected(A);
10799 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10800 // Assume is checked here as X is already added above for assumes in
10801 // addValueAffectedByCondition
10802 AddAffected(X);
10803 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10804 // Assume is checked here to avoid issues with ephemeral values
10805 Worklist.push_back(X);
10806 }
10807 }
10808}
10809
10811 // (X >> C) or/add (X & mask(C) != 0)
10812 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
10813 if (BO->getOpcode() == Instruction::Add ||
10814 BO->getOpcode() == Instruction::Or) {
10815 const Value *X;
10816 const APInt *C1, *C2;
10817 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
10821 m_Zero())))) &&
10822 C2->popcount() == C1->getZExtValue())
10823 return X;
10824 }
10825 }
10826 return nullptr;
10827}
10828
10830 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
10831}
10832
10835 unsigned MaxCount, bool AllowUndefOrPoison) {
10838 auto Push = [&](const Value *V) -> bool {
10839 Constant *C;
10840 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
10841 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
10842 return false;
10843 // Check existence first to avoid unnecessary allocations.
10844 if (Constants.contains(C))
10845 return true;
10846 if (Constants.size() == MaxCount)
10847 return false;
10848 Constants.insert(C);
10849 return true;
10850 }
10851
10852 if (auto *Inst = dyn_cast<Instruction>(V)) {
10853 if (Visited.insert(Inst).second)
10854 Worklist.push_back(Inst);
10855 return true;
10856 }
10857 return false;
10858 };
10859 if (!Push(V))
10860 return false;
10861 while (!Worklist.empty()) {
10862 const Instruction *CurInst = Worklist.pop_back_val();
10863 switch (CurInst->getOpcode()) {
10864 case Instruction::Select:
10865 if (!Push(CurInst->getOperand(1)))
10866 return false;
10867 if (!Push(CurInst->getOperand(2)))
10868 return false;
10869 break;
10870 case Instruction::PHI:
10871 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
10872 // Fast path for recurrence PHI.
10873 if (IncomingValue == CurInst)
10874 continue;
10875 if (!Push(IncomingValue))
10876 return false;
10877 }
10878 break;
10879 default:
10880 return false;
10881 }
10882 }
10883 return true;
10884}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
Rewrite undef for PHI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
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 F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CxtI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static const Instruction * safeCxtI(const Value *V, const Instruction *CxtI)
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:287
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:262
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:283
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:258
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:254
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:291
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:279
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:304
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:295
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:6055
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1631
bool isFinite() const
Definition APFloat.h:1580
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1234
static APFloat getInf(const fltSemantics &Sem, bool Negative=false)
Factory for Positive and Negative Infinity.
Definition APFloat.h:1194
bool isInteger() const
Definition APFloat.h:1592
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2001
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1594
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1412
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
unsigned ceilLogBase2() const
Definition APInt.h:1785
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1254
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1665
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:785
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1079
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:468
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:402
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1409
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:793
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1426
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
Definition SmallPtrSet.h:99
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:36
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:727
iterator_range< user_iterator > users()
Definition Value.h:426
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3035
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
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_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:668
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:578
@ Length
Definition DWP.cpp:578
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1669
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:445
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1684
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:332
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....
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:244
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
gep_type_iterator gep_type_begin(const User *GEP)
UndefPoisonKind
Enumeration to track whether we are interested in Undef, Poison, or both.
Definition UndefPoison.h:20
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:197
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
FPClassTest KnownFPClasses
Floating-point classes the value could be one of.
bool isKnownNeverInfinity() const
Return true if it's known this can never be an infinity.
bool cannotBeOrderedGreaterThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never greater tha...
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedGreaterThanZeroMask
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS)
Report known values for atan2.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType)
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
std::optional< bool > SignBit
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 asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1033