LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1323 Value *Arm, bool Invert,
1324 const SimplifyQuery &Q, unsigned Depth) {
1325 // If we have a constant arm, we are done.
1326 if (Known.isConstant())
1327 return;
1328
1329 // See what condition implies about the bits of the select arm.
1330 KnownBits CondRes(Known.getBitWidth());
1331 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1332 // If we don't get any information from the condition, no reason to
1333 // proceed.
1334 if (CondRes.isUnknown())
1335 return;
1336
1337 // We can have conflict if the condition is dead. I.e if we have
1338 // (x | 64) < 32 ? (x | 64) : y
1339 // we will have conflict at bit 6 from the condition/the `or`.
1340 // In that case just return. Its not particularly important
1341 // what we do, as this select is going to be simplified soon.
1342 CondRes = CondRes.unionWith(Known);
1343 if (CondRes.hasConflict())
1344 return;
1345
1346 // Finally make sure the information we found is valid. This is relatively
1347 // expensive so it's left for the very end.
1348 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1349 return;
1350
1351 // Finally, we know we get information from the condition and its valid,
1352 // so return it.
1353 Known = std::move(CondRes);
1354}
1355
1356// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1357// Returns the input and lower/upper bounds.
1358static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1359 const APInt *&CLow, const APInt *&CHigh) {
1361 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1362 "Input should be a Select!");
1363
1364 const Value *LHS = nullptr, *RHS = nullptr;
1366 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1367 return false;
1368
1369 if (!match(RHS, m_APInt(CLow)))
1370 return false;
1371
1372 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1374 if (getInverseMinMaxFlavor(SPF) != SPF2)
1375 return false;
1376
1377 if (!match(RHS2, m_APInt(CHigh)))
1378 return false;
1379
1380 if (SPF == SPF_SMIN)
1381 std::swap(CLow, CHigh);
1382
1383 In = LHS2;
1384 return CLow->sle(*CHigh);
1385}
1386
1388 const APInt *&CLow,
1389 const APInt *&CHigh) {
1390 assert((II->getIntrinsicID() == Intrinsic::smin ||
1391 II->getIntrinsicID() == Intrinsic::smax) &&
1392 "Must be smin/smax");
1393
1394 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1395 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1396 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1397 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1398 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1399 return false;
1400
1401 if (II->getIntrinsicID() == Intrinsic::smin)
1402 std::swap(CLow, CHigh);
1403 return CLow->sle(*CHigh);
1404}
1405
1407 KnownBits &Known) {
1408 const APInt *CLow, *CHigh;
1409 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1410 Known = Known.unionWith(
1411 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1412}
1413
1415 const APInt &DemandedElts,
1417 const SimplifyQuery &Q,
1418 unsigned Depth) {
1419 unsigned BitWidth = Known.getBitWidth();
1420
1421 KnownBits Known2(BitWidth);
1422 switch (I->getOpcode()) {
1423 default: break;
1424 case Instruction::Load:
1425 if (MDNode *MD =
1426 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1428 break;
1429 case Instruction::And:
1430 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1431 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1432
1433 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1434 break;
1435 case Instruction::Or:
1436 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1437 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1438
1439 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1440 break;
1441 case Instruction::Xor:
1442 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1443 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1444
1445 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1446 break;
1447 case Instruction::Mul: {
1450 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1451 DemandedElts, Known, Known2, Q, Depth);
1452 break;
1453 }
1454 case Instruction::UDiv: {
1455 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1456 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1457 Known =
1459 break;
1460 }
1461 case Instruction::SDiv: {
1462 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1463 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1464 Known =
1466 break;
1467 }
1468 case Instruction::Select: {
1469 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1470 KnownBits Res(Known.getBitWidth());
1471 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1472 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1473 return Res;
1474 };
1475 // Only known if known in both the LHS and RHS.
1476 Known =
1477 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1478 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1479 break;
1480 }
1481 case Instruction::FPTrunc:
1482 case Instruction::FPExt:
1483 case Instruction::FPToUI:
1484 case Instruction::FPToSI:
1485 case Instruction::SIToFP:
1486 case Instruction::UIToFP:
1487 break; // Can't work with floating point.
1488 case Instruction::PtrToInt:
1489 case Instruction::PtrToAddr:
1490 case Instruction::IntToPtr:
1491 // Fall through and handle them the same as zext/trunc.
1492 [[fallthrough]];
1493 case Instruction::ZExt:
1494 case Instruction::Trunc: {
1495 Type *SrcTy = I->getOperand(0)->getType();
1496
1497 unsigned SrcBitWidth;
1498 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1499 // which fall through here.
1500 Type *ScalarTy = SrcTy->getScalarType();
1501 SrcBitWidth = ScalarTy->isPointerTy() ?
1502 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1503 Q.DL.getTypeSizeInBits(ScalarTy);
1504
1505 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1506 Known = Known.anyextOrTrunc(SrcBitWidth);
1507 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1508 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1509 Inst && Inst->hasNonNeg() && !Known.isNegative())
1510 Known.makeNonNegative();
1511 Known = Known.zextOrTrunc(BitWidth);
1512 break;
1513 }
1514 case Instruction::BitCast: {
1515 Type *SrcTy = I->getOperand(0)->getType();
1516 if (SrcTy->isIntOrPtrTy() &&
1517 // TODO: For now, not handling conversions like:
1518 // (bitcast i64 %x to <2 x i32>)
1519 !I->getType()->isVectorTy()) {
1520 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1521 break;
1522 }
1523
1524 const Value *V;
1525 // Handle bitcast from floating point to integer.
1526 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1527 V->getType()->isFPOrFPVectorTy()) {
1528 Type *FPType = V->getType()->getScalarType();
1529 KnownFPClass Result =
1530 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1531
1532 Known = Result.toKnownBits(FPType->getFltSemantics());
1533
1534 break;
1535 }
1536
1537 // Handle cast from vector integer type to scalar or vector integer.
1538 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1539 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1540 !I->getType()->isIntOrIntVectorTy() ||
1541 isa<ScalableVectorType>(I->getType()))
1542 break;
1543
1544 unsigned NumElts = DemandedElts.getBitWidth();
1545 bool IsLE = Q.DL.isLittleEndian();
1546 // Look through a cast from narrow vector elements to wider type.
1547 // Examples: v4i32 -> v2i64, v3i8 -> v24
1548 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1549 if (BitWidth % SubBitWidth == 0) {
1550 // Known bits are automatically intersected across demanded elements of a
1551 // vector. So for example, if a bit is computed as known zero, it must be
1552 // zero across all demanded elements of the vector.
1553 //
1554 // For this bitcast, each demanded element of the output is sub-divided
1555 // across a set of smaller vector elements in the source vector. To get
1556 // the known bits for an entire element of the output, compute the known
1557 // bits for each sub-element sequentially. This is done by shifting the
1558 // one-set-bit demanded elements parameter across the sub-elements for
1559 // consecutive calls to computeKnownBits. We are using the demanded
1560 // elements parameter as a mask operator.
1561 //
1562 // The known bits of each sub-element are then inserted into place
1563 // (dependent on endian) to form the full result of known bits.
1564 unsigned SubScale = BitWidth / SubBitWidth;
1565 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1566 for (unsigned i = 0; i != NumElts; ++i) {
1567 if (DemandedElts[i])
1568 SubDemandedElts.setBit(i * SubScale);
1569 }
1570
1571 KnownBits KnownSrc(SubBitWidth);
1572 for (unsigned i = 0; i != SubScale; ++i) {
1573 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1574 Depth + 1);
1575 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1576 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1577 }
1578 }
1579 // Look through a cast from wider vector elements to narrow type.
1580 // Examples: v2i64 -> v4i32
1581 if (SubBitWidth % BitWidth == 0) {
1582 unsigned SubScale = SubBitWidth / BitWidth;
1583 KnownBits KnownSrc(SubBitWidth);
1584 APInt SubDemandedElts =
1585 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1586 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1587 Depth + 1);
1588
1589 Known.setAllConflict();
1590 for (unsigned i = 0; i != NumElts; ++i) {
1591 if (DemandedElts[i]) {
1592 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1593 unsigned Offset = (Shifts % SubScale) * BitWidth;
1594 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1595 if (Known.isUnknown())
1596 break;
1597 }
1598 }
1599 }
1600 break;
1601 }
1602 case Instruction::SExt: {
1603 // Compute the bits in the result that are not present in the input.
1604 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1605
1606 Known = Known.trunc(SrcBitWidth);
1607 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1608 // If the sign bit of the input is known set or clear, then we know the
1609 // top bits of the result.
1610 Known = Known.sext(BitWidth);
1611 break;
1612 }
1613 case Instruction::Shl: {
1616 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1617 bool ShAmtNonZero) {
1618 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1619 };
1620 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1621 KF);
1622 // Trailing zeros of a right-shifted constant never decrease.
1623 const APInt *C;
1624 if (match(I->getOperand(0), m_APInt(C)))
1625 Known.Zero.setLowBits(C->countr_zero());
1626
1627 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1628 // lands at bit Y, when BitWidth is a power of 2.
1629 const APInt *YC;
1630 Value *X = I->getOperand(0);
1631 if (isPowerOf2_32(BitWidth) &&
1632 match(I->getOperand(1),
1634 m_SpecificInt(BitWidth - 1)))) &&
1635 YC->ult(BitWidth - 1)) {
1636 unsigned Y = YC->getZExtValue();
1637 Known.One.setBit(Y);
1638 Known.Zero.setBitsFrom(Y + 1);
1639 }
1640 break;
1641 }
1642 case Instruction::LShr: {
1643 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1644 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1645 bool ShAmtNonZero) {
1646 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1647 };
1648 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1649 KF);
1650 // Leading zeros of a left-shifted constant never decrease.
1651 const APInt *C;
1652 if (match(I->getOperand(0), m_APInt(C)))
1653 Known.Zero.setHighBits(C->countl_zero());
1654 break;
1655 }
1656 case Instruction::AShr: {
1657 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1658 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1659 bool ShAmtNonZero) {
1660 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1661 };
1662 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1663 KF);
1664 break;
1665 }
1666 case Instruction::Sub: {
1669 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1670 DemandedElts, Known, Known2, Q, Depth);
1671 break;
1672 }
1673 case Instruction::Add: {
1676 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1677 DemandedElts, Known, Known2, Q, Depth);
1678 break;
1679 }
1680 case Instruction::SRem:
1681 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1682 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1683 Known = KnownBits::srem(Known, Known2);
1684 break;
1685
1686 case Instruction::URem:
1687 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1688 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1689 Known = KnownBits::urem(Known, Known2);
1690 break;
1691 case Instruction::Alloca:
1692 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1693 break;
1694 case Instruction::GetElementPtr: {
1695 // Analyze all of the subscripts of this getelementptr instruction
1696 // to determine if we can prove known low zero bits.
1697 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1698 // Accumulate the constant indices in a separate variable
1699 // to minimize the number of calls to computeForAddSub.
1700 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1701 APInt AccConstIndices(IndexWidth, 0);
1702
1703 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1704 if (IndexWidth == BitWidth) {
1705 // Note that inbounds does *not* guarantee nsw for the addition, as only
1706 // the offset is signed, while the base address is unsigned.
1707 Known = KnownBits::add(Known, IndexBits);
1708 } else {
1709 // If the index width is smaller than the pointer width, only add the
1710 // value to the low bits.
1711 assert(IndexWidth < BitWidth &&
1712 "Index width can't be larger than pointer width");
1713 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1714 }
1715 };
1716
1718 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1719 // TrailZ can only become smaller, short-circuit if we hit zero.
1720 if (Known.isUnknown())
1721 break;
1722
1723 Value *Index = I->getOperand(i);
1724
1725 // Handle case when index is zero.
1726 Constant *CIndex = dyn_cast<Constant>(Index);
1727 if (CIndex && CIndex->isNullValue())
1728 continue;
1729
1730 if (StructType *STy = GTI.getStructTypeOrNull()) {
1731 // Handle struct member offset arithmetic.
1732
1733 assert(CIndex &&
1734 "Access to structure field must be known at compile time");
1735
1736 if (CIndex->getType()->isVectorTy())
1737 Index = CIndex->getSplatValue();
1738
1739 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1740 const StructLayout *SL = Q.DL.getStructLayout(STy);
1741 uint64_t Offset = SL->getElementOffset(Idx);
1742 AccConstIndices += Offset;
1743 continue;
1744 }
1745
1746 // Handle array index arithmetic.
1747 Type *IndexedTy = GTI.getIndexedType();
1748 if (!IndexedTy->isSized()) {
1749 Known.resetAll();
1750 break;
1751 }
1752
1753 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1754 uint64_t StrideInBytes = Stride.getKnownMinValue();
1755 if (!Stride.isScalable()) {
1756 // Fast path for constant offset.
1757 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1758 AccConstIndices +=
1759 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1760 continue;
1761 }
1762 }
1763
1764 KnownBits IndexBits =
1765 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1766 KnownBits ScalingFactor(IndexWidth);
1767 // Multiply by current sizeof type.
1768 // &A[i] == A + i * sizeof(*A[i]).
1769 if (Stride.isScalable()) {
1770 // For scalable types the only thing we know about sizeof is
1771 // that this is a multiple of the minimum size.
1772 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1773 } else {
1774 ScalingFactor =
1775 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1776 }
1777 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1778 }
1779 if (!Known.isUnknown() && !AccConstIndices.isZero())
1780 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1781 break;
1782 }
1783 case Instruction::PHI: {
1784 const PHINode *P = cast<PHINode>(I);
1785 BinaryOperator *BO = nullptr;
1786 Value *R = nullptr, *L = nullptr;
1787 if (matchSimpleRecurrence(P, BO, R, L)) {
1788 // Handle the case of a simple two-predecessor recurrence PHI.
1789 // There's a lot more that could theoretically be done here, but
1790 // this is sufficient to catch some interesting cases.
1791 unsigned Opcode = BO->getOpcode();
1792
1793 switch (Opcode) {
1794 // If this is a shift recurrence, we know the bits being shifted in. We
1795 // can combine that with information about the start value of the
1796 // recurrence to conclude facts about the result. If this is a udiv
1797 // recurrence, we know that the result can never exceed either the
1798 // numerator or the start value, whichever is greater.
1799 case Instruction::LShr:
1800 case Instruction::AShr:
1801 case Instruction::Shl:
1802 case Instruction::UDiv:
1803 if (BO->getOperand(0) != I)
1804 break;
1805 [[fallthrough]];
1806
1807 // For a urem recurrence, the result can never exceed the start value. The
1808 // phi could either be the numerator or the denominator.
1809 case Instruction::URem: {
1810 // We have matched a recurrence of the form:
1811 // %iv = [R, %entry], [%iv.next, %backedge]
1812 // %iv.next = shift_op %iv, L
1813
1814 // Recurse with the phi context to avoid concern about whether facts
1815 // inferred hold at original context instruction. TODO: It may be
1816 // correct to use the original context. IF warranted, explore and
1817 // add sufficient tests to cover.
1819 RecQ.CxtI = P;
1820 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1821 switch (Opcode) {
1822 case Instruction::Shl:
1823 // A shl recurrence will only increase the tailing zeros
1824 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1825 break;
1826 case Instruction::LShr:
1827 case Instruction::UDiv:
1828 case Instruction::URem:
1829 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1830 // the start value.
1831 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1832 break;
1833 case Instruction::AShr:
1834 // An ashr recurrence will extend the initial sign bit
1835 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1836 Known.One.setHighBits(Known2.countMinLeadingOnes());
1837 break;
1838 }
1839 break;
1840 }
1841
1842 // Check for operations that have the property that if
1843 // both their operands have low zero bits, the result
1844 // will have low zero bits.
1845 case Instruction::Add:
1846 case Instruction::Sub:
1847 case Instruction::And:
1848 case Instruction::Or:
1849 case Instruction::Mul: {
1850 // Change the context instruction to the "edge" that flows into the
1851 // phi. This is important because that is where the value is actually
1852 // "evaluated" even though it is used later somewhere else. (see also
1853 // D69571).
1855
1856 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1857 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1858 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1859
1860 // Ok, we have a PHI of the form L op= R. Check for low
1861 // zero bits.
1862 RecQ.CxtI = RInst;
1863 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1864
1865 // We need to take the minimum number of known bits
1866 KnownBits Known3(BitWidth);
1867 RecQ.CxtI = LInst;
1868 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1869
1870 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1871 Known3.countMinTrailingZeros()));
1872
1873 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1874 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1875 break;
1876
1877 switch (Opcode) {
1878 // If initial value of recurrence is nonnegative, and we are adding
1879 // a nonnegative number with nsw, the result can only be nonnegative
1880 // or poison value regardless of the number of times we execute the
1881 // add in phi recurrence. If initial value is negative and we are
1882 // adding a negative number with nsw, the result can only be
1883 // negative or poison value. Similar arguments apply to sub and mul.
1884 //
1885 // (add non-negative, non-negative) --> non-negative
1886 // (add negative, negative) --> negative
1887 case Instruction::Add: {
1888 if (Known2.isNonNegative() && Known3.isNonNegative())
1889 Known.makeNonNegative();
1890 else if (Known2.isNegative() && Known3.isNegative())
1891 Known.makeNegative();
1892 break;
1893 }
1894
1895 // (sub nsw non-negative, negative) --> non-negative
1896 // (sub nsw negative, non-negative) --> negative
1897 case Instruction::Sub: {
1898 if (BO->getOperand(0) != I)
1899 break;
1900 if (Known2.isNonNegative() && Known3.isNegative())
1901 Known.makeNonNegative();
1902 else if (Known2.isNegative() && Known3.isNonNegative())
1903 Known.makeNegative();
1904 break;
1905 }
1906
1907 // (mul nsw non-negative, non-negative) --> non-negative
1908 case Instruction::Mul:
1909 if (Known2.isNonNegative() && Known3.isNonNegative())
1910 Known.makeNonNegative();
1911 break;
1912
1913 default:
1914 break;
1915 }
1916 break;
1917 }
1918
1919 default:
1920 break;
1921 }
1922 }
1923
1924 // Unreachable blocks may have zero-operand PHI nodes.
1925 if (P->getNumIncomingValues() == 0)
1926 break;
1927
1928 // Otherwise take the unions of the known bit sets of the operands,
1929 // taking conservative care to avoid excessive recursion.
1930 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1931 // Skip if every incoming value references to ourself.
1932 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1933 break;
1934
1935 Known.setAllConflict();
1936 for (const Use &U : P->operands()) {
1937 Value *IncValue;
1938 const PHINode *CxtPhi;
1939 Instruction *CxtI;
1940 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1941 // Skip direct self references.
1942 if (IncValue == P)
1943 continue;
1944
1945 // Change the context instruction to the "edge" that flows into the
1946 // phi. This is important because that is where the value is actually
1947 // "evaluated" even though it is used later somewhere else. (see also
1948 // D69571).
1950
1951 Known2 = KnownBits(BitWidth);
1952
1953 // Recurse, but cap the recursion to one level, because we don't
1954 // want to waste time spinning around in loops.
1955 // TODO: See if we can base recursion limiter on number of incoming phi
1956 // edges so we don't overly clamp analysis.
1957 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1959
1960 // See if we can further use a conditional branch into the phi
1961 // to help us determine the range of the value.
1962 if (!Known2.isConstant()) {
1963 CmpPredicate Pred;
1964 const APInt *RHSC;
1965 BasicBlock *TrueSucc, *FalseSucc;
1966 // TODO: Use RHS Value and compute range from its known bits.
1967 if (match(RecQ.CxtI,
1968 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1969 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1970 // Check for cases of duplicate successors.
1971 if ((TrueSucc == CxtPhi->getParent()) !=
1972 (FalseSucc == CxtPhi->getParent())) {
1973 // If we're using the false successor, invert the predicate.
1974 if (FalseSucc == CxtPhi->getParent())
1975 Pred = CmpInst::getInversePredicate(Pred);
1976 // Get the knownbits implied by the incoming phi condition.
1977 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
1978 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
1979 // We can have conflicts here if we are analyzing deadcode (its
1980 // impossible for us reach this BB based the icmp).
1981 if (KnownUnion.hasConflict()) {
1982 // No reason to continue analyzing in a known dead region, so
1983 // just resetAll and break. This will cause us to also exit the
1984 // outer loop.
1985 Known.resetAll();
1986 break;
1987 }
1988 Known2 = KnownUnion;
1989 }
1990 }
1991 }
1992
1993 Known = Known.intersectWith(Known2);
1994 // If all bits have been ruled out, there's no need to check
1995 // more operands.
1996 if (Known.isUnknown())
1997 break;
1998 }
1999 }
2000 break;
2001 }
2002 case Instruction::Call:
2003 case Instruction::Invoke: {
2004 // If range metadata is attached to this call, set known bits from that,
2005 // and then intersect with known bits based on other properties of the
2006 // function.
2007 if (MDNode *MD =
2008 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2010
2011 const auto *CB = cast<CallBase>(I);
2012
2013 if (std::optional<ConstantRange> Range = CB->getRange())
2014 Known = Known.unionWith(Range->toKnownBits());
2015
2016 if (const Value *RV = CB->getReturnedArgOperand()) {
2017 if (RV->getType() == I->getType()) {
2018 computeKnownBits(RV, Known2, Q, Depth + 1);
2019 Known = Known.unionWith(Known2);
2020 // If the function doesn't return properly for all input values
2021 // (e.g. unreachable exits) then there might be conflicts between the
2022 // argument value and the range metadata. Simply discard the known bits
2023 // in case of conflicts.
2024 if (Known.hasConflict())
2025 Known.resetAll();
2026 }
2027 }
2028 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2029 switch (II->getIntrinsicID()) {
2030 default:
2031 break;
2032 case Intrinsic::abs: {
2033 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2034 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2035 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2036 break;
2037 }
2038 case Intrinsic::bitreverse:
2039 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2040 Known = Known.unionWith(Known2.reverseBits());
2041 break;
2042 case Intrinsic::bswap:
2043 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2044 Known = Known.unionWith(Known2.byteSwap());
2045 break;
2046 case Intrinsic::ctlz: {
2047 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2048 // If we have a known 1, its position is our upper bound.
2049 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2050 // If this call is poison for 0 input, the result will be less than 2^n.
2051 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2052 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2053 unsigned LowBits = llvm::bit_width(PossibleLZ);
2054 Known.Zero.setBitsFrom(LowBits);
2055 break;
2056 }
2057 case Intrinsic::cttz: {
2058 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2059 // If we have a known 1, its position is our upper bound.
2060 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2061 // If this call is poison for 0 input, the result will be less than 2^n.
2062 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2063 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2064 unsigned LowBits = llvm::bit_width(PossibleTZ);
2065 Known.Zero.setBitsFrom(LowBits);
2066 break;
2067 }
2068 case Intrinsic::ctpop: {
2069 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2070 // We can bound the space the count needs. Also, bits known to be zero
2071 // can't contribute to the population.
2072 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2073 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2074 Known.Zero.setBitsFrom(LowBits);
2075 // TODO: we could bound KnownOne using the lower bound on the number
2076 // of bits which might be set provided by popcnt KnownOne2.
2077 break;
2078 }
2079 case Intrinsic::fshr:
2080 case Intrinsic::fshl: {
2081 const APInt *SA;
2082 if (!match(I->getOperand(2), m_APInt(SA)))
2083 break;
2084
2085 KnownBits Known3(BitWidth);
2086 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2087 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2088 Known = II->getIntrinsicID() == Intrinsic::fshl
2089 ? KnownBits::fshl(Known2, Known3, *SA)
2090 : KnownBits::fshr(Known2, Known3, *SA);
2091 break;
2092 }
2093 case Intrinsic::clmul:
2094 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2095 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2096 Known = KnownBits::clmul(Known, Known2);
2097 break;
2098 case Intrinsic::pext:
2099 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2100 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2101 Known = KnownBits::pext(Known, Known2);
2102 break;
2103 case Intrinsic::pdep:
2104 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2105 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2106 Known = KnownBits::pdep(Known, Known2);
2107 break;
2108 case Intrinsic::uadd_sat:
2109 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2110 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2111 Known = KnownBits::uadd_sat(Known, Known2);
2112 break;
2113 case Intrinsic::usub_sat:
2114 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2115 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2116 Known = KnownBits::usub_sat(Known, Known2);
2117 break;
2118 case Intrinsic::sadd_sat:
2119 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2120 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2121 Known = KnownBits::sadd_sat(Known, Known2);
2122 break;
2123 case Intrinsic::ssub_sat:
2124 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2125 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2126 Known = KnownBits::ssub_sat(Known, Known2);
2127 break;
2128 // Vec reverse preserves bits from input vec.
2129 case Intrinsic::vector_reverse:
2130 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2131 Depth + 1);
2132 break;
2133 // for min/max/and/or reduce, any bit common to each element in the
2134 // input vec is set in the output.
2135 case Intrinsic::vector_reduce_and:
2136 case Intrinsic::vector_reduce_or:
2137 case Intrinsic::vector_reduce_umax:
2138 case Intrinsic::vector_reduce_umin:
2139 case Intrinsic::vector_reduce_smax:
2140 case Intrinsic::vector_reduce_smin:
2141 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2142 break;
2143 case Intrinsic::vector_reduce_xor: {
2144 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2145 // The zeros common to all vecs are zero in the output.
2146 // If the number of elements is odd, then the common ones remain. If the
2147 // number of elements is even, then the common ones becomes zeros.
2148 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2149 // Even, so the ones become zeros.
2150 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2151 if (EvenCnt)
2152 Known.Zero |= Known.One;
2153 // Maybe even element count so need to clear ones.
2154 if (VecTy->isScalableTy() || EvenCnt)
2155 Known.One.clearAllBits();
2156 break;
2157 }
2158 case Intrinsic::vector_reduce_add: {
2159 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2160 if (!VecTy)
2161 break;
2162 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2163 Known = Known.reduceAdd(VecTy->getNumElements());
2164 break;
2165 }
2166 case Intrinsic::umin:
2167 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2168 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2169 Known = KnownBits::umin(Known, Known2);
2170 break;
2171 case Intrinsic::umax:
2172 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2173 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2174 Known = KnownBits::umax(Known, Known2);
2175 break;
2176 case Intrinsic::smin:
2177 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2178 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2179 Known = KnownBits::smin(Known, Known2);
2181 break;
2182 case Intrinsic::smax:
2183 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2184 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2185 Known = KnownBits::smax(Known, Known2);
2187 break;
2188 case Intrinsic::ptrmask: {
2189 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2190
2191 const Value *Mask = I->getOperand(1);
2192 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2193 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2194 // TODO: 1-extend would be more precise.
2195 Known &= Known2.anyextOrTrunc(BitWidth);
2196 break;
2197 }
2198 case Intrinsic::x86_sse2_pmulh_w:
2199 case Intrinsic::x86_avx2_pmulh_w:
2200 case Intrinsic::x86_avx512_pmulh_w_512:
2201 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2202 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2203 Known = KnownBits::mulhs(Known, Known2);
2204 break;
2205 case Intrinsic::x86_sse2_pmulhu_w:
2206 case Intrinsic::x86_avx2_pmulhu_w:
2207 case Intrinsic::x86_avx512_pmulhu_w_512:
2208 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2209 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2210 Known = KnownBits::mulhu(Known, Known2);
2211 break;
2212 case Intrinsic::x86_sse42_crc32_64_64:
2213 Known.Zero.setBitsFrom(32);
2214 break;
2215 case Intrinsic::x86_ssse3_phadd_d_128:
2216 case Intrinsic::x86_ssse3_phadd_w_128:
2217 case Intrinsic::x86_avx2_phadd_d:
2218 case Intrinsic::x86_avx2_phadd_w: {
2220 I, DemandedElts, Q, Depth,
2221 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2222 return KnownBits::add(KnownLHS, KnownRHS);
2223 });
2224 break;
2225 }
2226 case Intrinsic::x86_ssse3_phadd_sw_128:
2227 case Intrinsic::x86_avx2_phadd_sw: {
2229 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2230 break;
2231 }
2232 case Intrinsic::x86_ssse3_phsub_d_128:
2233 case Intrinsic::x86_ssse3_phsub_w_128:
2234 case Intrinsic::x86_avx2_phsub_d:
2235 case Intrinsic::x86_avx2_phsub_w: {
2237 I, DemandedElts, Q, Depth,
2238 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2239 return KnownBits::sub(KnownLHS, KnownRHS);
2240 });
2241 break;
2242 }
2243 case Intrinsic::x86_ssse3_phsub_sw_128:
2244 case Intrinsic::x86_avx2_phsub_sw: {
2246 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2247 break;
2248 }
2249 case Intrinsic::riscv_vsetvli:
2250 case Intrinsic::riscv_vsetvlimax: {
2251 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2252 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2254 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2255 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2256 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2257 uint64_t MaxVLEN =
2258 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2259 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2260
2261 // Result of vsetvli must be not larger than AVL.
2262 if (HasAVL)
2263 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2264 MaxVL = std::min(MaxVL, CI->getZExtValue());
2265
2266 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2267 if (BitWidth > KnownZeroFirstBit)
2268 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2269 break;
2270 }
2271 case Intrinsic::amdgcn_mbcnt_hi:
2272 case Intrinsic::amdgcn_mbcnt_lo: {
2273 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2274 // most 31 + src1.
2275 Known.Zero.setBitsFrom(
2276 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2277 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2278 Known = KnownBits::add(Known, Known2);
2279 break;
2280 }
2281 case Intrinsic::vscale: {
2282 if (!II->getParent() || !II->getFunction())
2283 break;
2284
2285 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2286 break;
2287 }
2288 }
2289 }
2290 break;
2291 }
2292 case Instruction::ShuffleVector: {
2293 if (auto *Splat = getSplatValue(I)) {
2295 break;
2296 }
2297
2298 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2299 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2300 if (!Shuf) {
2301 Known.resetAll();
2302 return;
2303 }
2304 // For undef elements, we don't know anything about the common state of
2305 // the shuffle result.
2306 APInt DemandedLHS, DemandedRHS;
2307 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2308 Known.resetAll();
2309 return;
2310 }
2311 Known.setAllConflict();
2312 if (!!DemandedLHS) {
2313 const Value *LHS = Shuf->getOperand(0);
2314 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2315 // If we don't know any bits, early out.
2316 if (Known.isUnknown())
2317 break;
2318 }
2319 if (!!DemandedRHS) {
2320 const Value *RHS = Shuf->getOperand(1);
2321 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2322 Known = Known.intersectWith(Known2);
2323 }
2324 break;
2325 }
2326 case Instruction::InsertElement: {
2327 if (isa<ScalableVectorType>(I->getType())) {
2328 Known.resetAll();
2329 return;
2330 }
2331 const Value *Vec = I->getOperand(0);
2332 const Value *Elt = I->getOperand(1);
2333 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2334 unsigned NumElts = DemandedElts.getBitWidth();
2335 APInt DemandedVecElts = DemandedElts;
2336 bool NeedsElt = true;
2337 // If we know the index we are inserting too, clear it from Vec check.
2338 if (CIdx && CIdx->getValue().ult(NumElts)) {
2339 DemandedVecElts.clearBit(CIdx->getZExtValue());
2340 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2341 }
2342
2343 Known.setAllConflict();
2344 if (NeedsElt) {
2345 computeKnownBits(Elt, Known, Q, Depth + 1);
2346 // If we don't know any bits, early out.
2347 if (Known.isUnknown())
2348 break;
2349 }
2350
2351 if (!DemandedVecElts.isZero()) {
2352 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2353 Known = Known.intersectWith(Known2);
2354 }
2355 break;
2356 }
2357 case Instruction::ExtractElement: {
2358 // Look through extract element. If the index is non-constant or
2359 // out-of-range demand all elements, otherwise just the extracted element.
2360 const Value *Vec = I->getOperand(0);
2361 const Value *Idx = I->getOperand(1);
2362 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2363 if (isa<ScalableVectorType>(Vec->getType())) {
2364 // FIXME: there's probably *something* we can do with scalable vectors
2365 Known.resetAll();
2366 break;
2367 }
2368 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2369 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2370 if (CIdx && CIdx->getValue().ult(NumElts))
2371 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2372 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2373 break;
2374 }
2375 case Instruction::ExtractValue:
2376 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2378 if (EVI->getNumIndices() != 1) break;
2379 if (EVI->getIndices()[0] == 0) {
2380 switch (II->getIntrinsicID()) {
2381 default: break;
2382 case Intrinsic::uadd_with_overflow:
2383 case Intrinsic::sadd_with_overflow:
2385 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2386 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2387 break;
2388 case Intrinsic::usub_with_overflow:
2389 case Intrinsic::ssub_with_overflow:
2391 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2392 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2393 break;
2394 case Intrinsic::umul_with_overflow:
2395 case Intrinsic::smul_with_overflow:
2396 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2397 false, DemandedElts, Known, Known2, Q, Depth);
2398 break;
2399 }
2400 }
2401 }
2402 break;
2403 case Instruction::Freeze:
2404 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2405 Depth + 1))
2406 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2407 break;
2408 }
2409}
2410
2411/// Determine which bits of V are known to be either zero or one and return
2412/// them.
2413KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2414 const SimplifyQuery &Q, unsigned Depth) {
2415 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2416 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2417 return Known;
2418}
2419
2420/// Determine which bits of V are known to be either zero or one and return
2421/// them.
2423 unsigned Depth) {
2424 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2426 return Known;
2427}
2428
2429/// Determine which bits of V are known to be either zero or one and return
2430/// them in the Known bit set.
2431///
2432/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2433/// we cannot optimize based on the assumption that it is zero without changing
2434/// it to be an explicit zero. If we don't change it to zero, other code could
2435/// optimized based on the contradictory assumption that it is non-zero.
2436/// Because instcombine aggressively folds operations with undef args anyway,
2437/// this won't lose us code quality.
2438///
2439/// This function is defined on values with integer type, values with pointer
2440/// type, and vectors of integers. In the case
2441/// where V is a vector, known zero, and known one values are the
2442/// same width as the vector element, and the bit is set only if it is true
2443/// for all of the demanded elements in the vector specified by DemandedElts.
2444void computeKnownBits(const Value *V, const APInt &DemandedElts,
2445 KnownBits &Known, const SimplifyQuery &Q,
2446 unsigned Depth) {
2447 if (!DemandedElts) {
2448 // No demanded elts, better to assume we don't know anything.
2449 Known.resetAll();
2450 return;
2451 }
2452
2453 assert(V && "No Value?");
2454 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2455
2456#ifndef NDEBUG
2457 Type *Ty = V->getType();
2458 unsigned BitWidth = Known.getBitWidth();
2459
2460 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2461 "Not integer or pointer type!");
2462
2463 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2464 assert(
2465 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2466 "DemandedElt width should equal the fixed vector number of elements");
2467 } else {
2468 assert(DemandedElts == APInt(1, 1) &&
2469 "DemandedElt width should be 1 for scalars or scalable vectors");
2470 }
2471
2472 Type *ScalarTy = Ty->getScalarType();
2473 if (ScalarTy->isPointerTy()) {
2474 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2475 "V and Known should have same BitWidth");
2476 } else {
2477 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2478 "V and Known should have same BitWidth");
2479 }
2480#endif
2481
2482 const APInt *C;
2483 if (match(V, m_APInt(C))) {
2484 // We know all of the bits for a scalar constant or a splat vector constant!
2486 return;
2487 }
2488 // Null and aggregate-zero are all-zeros.
2490 Known.setAllZero();
2491 return;
2492 }
2493 // Handle a constant vector by taking the intersection of the known bits of
2494 // each element.
2496 assert(!isa<ScalableVectorType>(V->getType()));
2497 // We know that CDV must be a vector of integers. Take the intersection of
2498 // each element.
2499 Known.setAllConflict();
2500 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2501 if (!DemandedElts[i])
2502 continue;
2503 APInt Elt = CDV->getElementAsAPInt(i);
2504 Known.Zero &= ~Elt;
2505 Known.One &= Elt;
2506 }
2507 if (Known.hasConflict())
2508 Known.resetAll();
2509 return;
2510 }
2511
2512 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2513 assert(!isa<ScalableVectorType>(V->getType()));
2514 // We know that CV must be a vector of integers. Take the intersection of
2515 // each element.
2516 Known.setAllConflict();
2517 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2518 if (!DemandedElts[i])
2519 continue;
2520 Constant *Element = CV->getAggregateElement(i);
2521 if (isa<PoisonValue>(Element))
2522 continue;
2523 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2524 if (!ElementCI) {
2525 Known.resetAll();
2526 return;
2527 }
2528 const APInt &Elt = ElementCI->getValue();
2529 Known.Zero &= ~Elt;
2530 Known.One &= Elt;
2531 }
2532 if (Known.hasConflict())
2533 Known.resetAll();
2534 return;
2535 }
2536
2537 // Start out not knowing anything.
2538 Known.resetAll();
2539
2540 // We can't imply anything about undefs.
2541 if (isa<UndefValue>(V))
2542 return;
2543
2544 // There's no point in looking through other users of ConstantData for
2545 // assumptions. Confirm that we've handled them all.
2546 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2547
2548 if (const auto *A = dyn_cast<Argument>(V))
2549 if (std::optional<ConstantRange> Range = A->getRange())
2550 Known = Range->toKnownBits();
2551
2552 // All recursive calls that increase depth must come after this.
2554 return;
2555
2556 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2557 // the bits of its aliasee.
2558 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2559 if (!GA->isInterposable())
2560 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2561 return;
2562 }
2563
2564 if (const Operator *I = dyn_cast<Operator>(V))
2565 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2566 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2567 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2568 Known = CR->toKnownBits();
2569 }
2570
2571 // Aligned pointers have trailing zeros - refine Known.Zero set
2572 if (isa<PointerType>(V->getType())) {
2573 Align Alignment = V->getPointerAlignment(Q.DL);
2574 Known.Zero.setLowBits(Log2(Alignment));
2575 }
2576
2577 // computeKnownBitsFromContext strictly refines Known.
2578 // Therefore, we run them after computeKnownBitsFromOperator.
2579
2580 // Check whether we can determine known bits from context such as assumes.
2582}
2583
2584/// Try to detect a recurrence that the value of the induction variable is
2585/// always a power of two (or zero).
2586static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2587 SimplifyQuery &Q, unsigned Depth) {
2588 BinaryOperator *BO = nullptr;
2589 Value *Start = nullptr, *Step = nullptr;
2590 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2591 return false;
2592
2593 // Initial value must be a power of two.
2594 for (const Use &U : PN->operands()) {
2595 if (U.get() == Start) {
2596 // Initial value comes from a different BB, need to adjust context
2597 // instruction for analysis.
2598 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2599 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2600 return false;
2601 }
2602 }
2603
2604 // Except for Mul, the induction variable must be on the left side of the
2605 // increment expression, otherwise its value can be arbitrary.
2606 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2607 return false;
2608
2609 Q.CxtI = BO->getParent()->getTerminator();
2610 switch (BO->getOpcode()) {
2611 case Instruction::Mul:
2612 // Power of two is closed under multiplication.
2613 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2614 Q.IIQ.hasNoSignedWrap(BO)) &&
2615 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2616 case Instruction::SDiv:
2617 // Start value must not be signmask for signed division, so simply being a
2618 // power of two is not sufficient, and it has to be a constant.
2619 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2620 return false;
2621 [[fallthrough]];
2622 case Instruction::UDiv:
2623 // Divisor must be a power of two.
2624 // If OrZero is false, cannot guarantee induction variable is non-zero after
2625 // division, same for Shr, unless it is exact division.
2626 return (OrZero || Q.IIQ.isExact(BO)) &&
2627 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2628 case Instruction::Shl:
2629 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2630 case Instruction::AShr:
2631 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2632 return false;
2633 [[fallthrough]];
2634 case Instruction::LShr:
2635 return OrZero || Q.IIQ.isExact(BO);
2636 default:
2637 return false;
2638 }
2639}
2640
2641/// Return true if we can infer that \p V is known to be a power of 2 from
2642/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2643static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2644 const Value *Cond,
2645 bool CondIsTrue) {
2646 CmpPredicate Pred;
2647 const APInt *RHSC;
2648 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2649 return false;
2650 if (!CondIsTrue)
2651 Pred = ICmpInst::getInversePredicate(Pred);
2652 // ctpop(V) u< 2
2653 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2654 return true;
2655 // ctpop(V) == 1
2656 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2657}
2658
2659/// Return true if the given value is known to have exactly one
2660/// bit set when defined. For vectors return true if every element is known to
2661/// be a power of two when defined. Supports values with integer or pointer
2662/// types and vectors of integers.
2663bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2664 const SimplifyQuery &Q, unsigned Depth) {
2665 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2666
2667 if (isa<Constant>(V))
2668 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2669
2670 // i1 is by definition a power of 2 or zero.
2671 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2672 return true;
2673
2674 // Try to infer from assumptions.
2675 if (Q.AC && Q.CxtI) {
2676 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2677 if (!AssumeVH)
2678 continue;
2679 CallInst *I = cast<CallInst>(AssumeVH);
2680 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2681 /*CondIsTrue=*/true) &&
2683 return true;
2684 }
2685 }
2686
2687 // Handle dominating conditions.
2688 if (Q.DC && Q.CxtI && Q.DT) {
2689 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2690 Value *Cond = BI->getCondition();
2691
2692 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2694 /*CondIsTrue=*/true) &&
2695 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2696 return true;
2697
2698 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2700 /*CondIsTrue=*/false) &&
2701 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2702 return true;
2703 }
2704 }
2705
2706 auto *I = dyn_cast<Instruction>(V);
2707 if (!I)
2708 return false;
2709
2710 if (Q.CxtI && match(V, m_VScale())) {
2711 const Function *F = Q.CxtI->getFunction();
2712 // The vscale_range indicates vscale is a power-of-two.
2713 return F->hasFnAttribute(Attribute::VScaleRange);
2714 }
2715
2716 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2717 // it is shifted off the end then the result is undefined.
2718 if (match(I, m_Shl(m_One(), m_Value())))
2719 return true;
2720
2721 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2722 // the bottom. If it is shifted off the bottom then the result is undefined.
2723 if (match(I, m_LShr(m_SignMask(), m_Value())))
2724 return true;
2725
2726 // The remaining tests are all recursive, so bail out if we hit the limit.
2728 return false;
2729
2730 switch (I->getOpcode()) {
2731 case Instruction::ZExt:
2732 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2733 case Instruction::Trunc:
2734 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2735 case Instruction::Shl:
2736 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2737 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2738 return false;
2739 case Instruction::LShr:
2740 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2741 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2742 return false;
2743 case Instruction::UDiv:
2745 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2746 return false;
2747 case Instruction::Mul:
2748 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2749 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2750 (OrZero || isKnownNonZero(I, Q, Depth));
2751 case Instruction::And:
2752 // A power of two and'd with anything is a power of two or zero.
2753 if (OrZero &&
2754 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2755 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2756 return true;
2757 // X & (-X) is always a power of two or zero.
2758 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2759 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2760 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2761 return false;
2762 case Instruction::Add: {
2763 // Adding a power-of-two or zero to the same power-of-two or zero yields
2764 // either the original power-of-two, a larger power-of-two or zero.
2766 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2767 Q.IIQ.hasNoSignedWrap(VOBO)) {
2768 if (match(I->getOperand(0),
2769 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2770 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2771 return true;
2772 if (match(I->getOperand(1),
2773 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2774 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2775 return true;
2776
2777 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2778 KnownBits LHSBits(BitWidth);
2779 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2780
2781 KnownBits RHSBits(BitWidth);
2782 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2783 // If i8 V is a power of two or zero:
2784 // ZeroBits: 1 1 1 0 1 1 1 1
2785 // ~ZeroBits: 0 0 0 1 0 0 0 0
2786 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2787 // If OrZero isn't set, we cannot give back a zero result.
2788 // Make sure either the LHS or RHS has a bit set.
2789 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2790 return true;
2791 }
2792
2793 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2794 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2795 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2796 return true;
2797 return false;
2798 }
2799 case Instruction::Select:
2800 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2801 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2802 case Instruction::PHI: {
2803 // A PHI node is power of two if all incoming values are power of two, or if
2804 // it is an induction variable where in each step its value is a power of
2805 // two.
2806 auto *PN = cast<PHINode>(I);
2808
2809 // Check if it is an induction variable and always power of two.
2810 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2811 return true;
2812
2813 // Recursively check all incoming values. Limit recursion to 2 levels, so
2814 // that search complexity is limited to number of operands^2.
2815 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2816 return llvm::all_of(PN->operands(), [&](const Use &U) {
2817 // Value is power of 2 if it is coming from PHI node itself by induction.
2818 if (U.get() == PN)
2819 return true;
2820
2821 // Change the context instruction to the incoming block where it is
2822 // evaluated.
2823 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2824 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2825 });
2826 }
2827 case Instruction::Invoke:
2828 case Instruction::Call: {
2829 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2830 switch (II->getIntrinsicID()) {
2831 case Intrinsic::umax:
2832 case Intrinsic::smax:
2833 case Intrinsic::umin:
2834 case Intrinsic::smin:
2835 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2836 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2837 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2838 // thus dont change pow2/non-pow2 status.
2839 case Intrinsic::bitreverse:
2840 case Intrinsic::bswap:
2841 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2842 case Intrinsic::fshr:
2843 case Intrinsic::fshl:
2844 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2845 if (II->getArgOperand(0) == II->getArgOperand(1))
2846 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2847 break;
2848 case Intrinsic::riscv_vsetvlimax:
2849 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2850 // for any valid vtype, so it is a power of two regardless of OrZero.
2851 return true;
2852 default:
2853 break;
2854 }
2855 }
2856 return false;
2857 }
2858 default:
2859 return false;
2860 }
2861}
2862
2863/// Test whether a GEP's result is known to be non-null.
2864///
2865/// Uses properties inherent in a GEP to try to determine whether it is known
2866/// to be non-null.
2867///
2868/// Currently this routine does not support vector GEPs.
2869static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2870 unsigned Depth) {
2871 const Function *F = nullptr;
2872 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2873 F = I->getFunction();
2874
2875 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2876 // may be null iff the base pointer is null and the offset is zero.
2877 if (!GEP->hasNoUnsignedWrap() &&
2878 !(GEP->isInBounds() &&
2879 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2880 return false;
2881
2882 // FIXME: Support vector-GEPs.
2883 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2884
2885 // If the base pointer is non-null, we cannot walk to a null address with an
2886 // inbounds GEP in address space zero.
2887 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2888 return true;
2889
2890 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2891 // If so, then the GEP cannot produce a null pointer, as doing so would
2892 // inherently violate the inbounds contract within address space zero.
2894 GTI != GTE; ++GTI) {
2895 // Struct types are easy -- they must always be indexed by a constant.
2896 if (StructType *STy = GTI.getStructTypeOrNull()) {
2897 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2898 unsigned ElementIdx = OpC->getZExtValue();
2899 const StructLayout *SL = Q.DL.getStructLayout(STy);
2900 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2901 if (ElementOffset > 0)
2902 return true;
2903 continue;
2904 }
2905
2906 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2907 if (GTI.getSequentialElementStride(Q.DL).isZero())
2908 continue;
2909
2910 // Fast path the constant operand case both for efficiency and so we don't
2911 // increment Depth when just zipping down an all-constant GEP.
2912 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2913 if (!OpC->isZero())
2914 return true;
2915 continue;
2916 }
2917
2918 // We post-increment Depth here because while isKnownNonZero increments it
2919 // as well, when we pop back up that increment won't persist. We don't want
2920 // to recurse 10k times just because we have 10k GEP operands. We don't
2921 // bail completely out because we want to handle constant GEPs regardless
2922 // of depth.
2924 continue;
2925
2926 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2927 return true;
2928 }
2929
2930 return false;
2931}
2932
2934 const Instruction *CtxI,
2935 const DominatorTree *DT) {
2936 assert(!isa<Constant>(V) && "Called for constant?");
2937
2938 if (!CtxI || !DT)
2939 return false;
2940
2941 unsigned NumUsesExplored = 0;
2942 for (auto &U : V->uses()) {
2943 // Avoid massive lists
2944 if (NumUsesExplored >= DomConditionsMaxUses)
2945 break;
2946 NumUsesExplored++;
2947
2948 const Instruction *UI = cast<Instruction>(U.getUser());
2949 // If the value is used as an argument to a call or invoke, then argument
2950 // attributes may provide an answer about null-ness.
2951 if (V->getType()->isPointerTy()) {
2952 if (const auto *CB = dyn_cast<CallBase>(UI)) {
2953 if (CB->isArgOperand(&U) &&
2954 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
2955 /*AllowUndefOrPoison=*/false) &&
2956 DT->dominates(CB, CtxI))
2957 return true;
2958 }
2959 }
2960
2961 // If the value is used as a load/store, then the pointer must be non null.
2962 if (V == getLoadStorePointerOperand(UI)) {
2965 DT->dominates(UI, CtxI))
2966 return true;
2967 }
2968
2969 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
2970 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
2971 isValidAssumeForContext(UI, CtxI, DT))
2972 return true;
2973
2974 // Consider only compare instructions uniquely controlling a branch
2975 Value *RHS;
2976 CmpPredicate Pred;
2977 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2978 continue;
2979
2980 bool NonNullIfTrue;
2981 if (cmpExcludesZero(Pred, RHS))
2982 NonNullIfTrue = true;
2984 NonNullIfTrue = false;
2985 else
2986 continue;
2987
2990 for (const auto *CmpU : UI->users()) {
2991 assert(WorkList.empty() && "Should be!");
2992 if (Visited.insert(CmpU).second)
2993 WorkList.push_back(CmpU);
2994
2995 while (!WorkList.empty()) {
2996 auto *Curr = WorkList.pop_back_val();
2997
2998 // If a user is an AND, add all its users to the work list. We only
2999 // propagate "pred != null" condition through AND because it is only
3000 // correct to assume that all conditions of AND are met in true branch.
3001 // TODO: Support similar logic of OR and EQ predicate?
3002 if (NonNullIfTrue)
3003 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3004 for (const auto *CurrU : Curr->users())
3005 if (Visited.insert(CurrU).second)
3006 WorkList.push_back(CurrU);
3007 continue;
3008 }
3009
3010 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3011 BasicBlock *NonNullSuccessor =
3012 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3013 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3014 if (DT->dominates(Edge, CtxI->getParent()))
3015 return true;
3016 } else if (NonNullIfTrue && isGuard(Curr) &&
3017 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3018 return true;
3019 }
3020 }
3021 }
3022 }
3023
3024 return false;
3025}
3026
3027/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3028/// ensure that the value it's attached to is never Value? 'RangeType' is
3029/// is the type of the value described by the range.
3030static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3031 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3032 assert(NumRanges >= 1);
3033 for (unsigned i = 0; i < NumRanges; ++i) {
3035 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3037 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3038 ConstantRange Range(Lower->getValue(), Upper->getValue());
3039 if (Range.contains(Value))
3040 return false;
3041 }
3042 return true;
3043}
3044
3045/// Try to detect a recurrence that monotonically increases/decreases from a
3046/// non-zero starting value. These are common as induction variables.
3047static bool isNonZeroRecurrence(const PHINode *PN) {
3048 BinaryOperator *BO = nullptr;
3049 Value *Start = nullptr, *Step = nullptr;
3050 const APInt *StartC, *StepC;
3051 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3052 !match(Start, m_APInt(StartC)) || StartC->isZero())
3053 return false;
3054
3055 switch (BO->getOpcode()) {
3056 case Instruction::Add:
3057 // Starting from non-zero and stepping away from zero can never wrap back
3058 // to zero.
3059 return BO->hasNoUnsignedWrap() ||
3060 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3061 StartC->isNegative() == StepC->isNegative());
3062 case Instruction::Mul:
3063 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3064 match(Step, m_APInt(StepC)) && !StepC->isZero();
3065 case Instruction::Shl:
3066 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3067 case Instruction::AShr:
3068 case Instruction::LShr:
3069 return BO->isExact();
3070 default:
3071 return false;
3072 }
3073}
3074
3075static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3077 m_Specific(Op1), m_Zero()))) ||
3079 m_Specific(Op0), m_Zero())));
3080}
3081
3082static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3083 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3084 bool NUW, unsigned Depth) {
3085 // (X + (X != 0)) is non zero
3086 if (matchOpWithOpEqZero(X, Y))
3087 return true;
3088
3089 if (NUW)
3090 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3091 isKnownNonZero(X, DemandedElts, Q, Depth);
3092
3093 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3094 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3095
3096 // If X and Y are both non-negative (as signed values) then their sum is not
3097 // zero unless both X and Y are zero.
3098 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3099 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3100 isKnownNonZero(X, DemandedElts, Q, Depth))
3101 return true;
3102
3103 // If X and Y are both negative (as signed values) then their sum is not
3104 // zero unless both X and Y equal INT_MIN.
3105 if (XKnown.isNegative() && YKnown.isNegative()) {
3107 // The sign bit of X is set. If some other bit is set then X is not equal
3108 // to INT_MIN.
3109 if (XKnown.One.intersects(Mask))
3110 return true;
3111 // The sign bit of Y is set. If some other bit is set then Y is not equal
3112 // to INT_MIN.
3113 if (YKnown.One.intersects(Mask))
3114 return true;
3115 }
3116
3117 // The sum of a non-negative number and a power of two is not zero.
3118 if (XKnown.isNonNegative() &&
3119 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3120 return true;
3121 if (YKnown.isNonNegative() &&
3122 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3123 return true;
3124
3125 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3126}
3127
3128static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3129 unsigned BitWidth, Value *X, Value *Y,
3130 unsigned Depth) {
3131 // (X - (X != 0)) is non zero
3132 // ((X != 0) - X) is non zero
3133 if (matchOpWithOpEqZero(X, Y))
3134 return true;
3135
3136 // TODO: Move this case into isKnownNonEqual().
3137 if (auto *C = dyn_cast<Constant>(X))
3138 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3139 return true;
3140
3141 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3142}
3143
3144static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3145 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3146 bool NUW, unsigned Depth) {
3147 // If X and Y are non-zero then so is X * Y as long as the multiplication
3148 // does not overflow.
3149 if (NSW || NUW)
3150 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3151 isKnownNonZero(Y, DemandedElts, Q, Depth);
3152
3153 // If either X or Y is odd, then if the other is non-zero the result can't
3154 // be zero.
3155 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3156 if (XKnown.One[0])
3157 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3158
3159 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3160 if (YKnown.One[0])
3161 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3162
3163 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3164 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3165 // the lowest known One of X and Y. If they are non-zero, the result
3166 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3167 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3168 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3169 BitWidth;
3170}
3171
3172static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3173 const SimplifyQuery &Q, const KnownBits &KnownVal,
3174 unsigned Depth) {
3175 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3176 switch (I->getOpcode()) {
3177 case Instruction::Shl:
3178 return Lhs.shl(Rhs);
3179 case Instruction::LShr:
3180 return Lhs.lshr(Rhs);
3181 case Instruction::AShr:
3182 return Lhs.ashr(Rhs);
3183 default:
3184 llvm_unreachable("Unknown Shift Opcode");
3185 }
3186 };
3187
3188 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3189 switch (I->getOpcode()) {
3190 case Instruction::Shl:
3191 return Lhs.lshr(Rhs);
3192 case Instruction::LShr:
3193 case Instruction::AShr:
3194 return Lhs.shl(Rhs);
3195 default:
3196 llvm_unreachable("Unknown Shift Opcode");
3197 }
3198 };
3199
3200 if (KnownVal.isUnknown())
3201 return false;
3202
3203 KnownBits KnownCnt =
3204 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3205 APInt MaxShift = KnownCnt.getMaxValue();
3206 unsigned NumBits = KnownVal.getBitWidth();
3207 if (MaxShift.uge(NumBits))
3208 return false;
3209
3210 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3211 return true;
3212
3213 // If all of the bits shifted out are known to be zero, and Val is known
3214 // non-zero then at least one non-zero bit must remain.
3215 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3216 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3217 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3218 return true;
3219
3220 return false;
3221}
3222
3224 const APInt &DemandedElts,
3225 const SimplifyQuery &Q, unsigned Depth) {
3226 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3227 switch (I->getOpcode()) {
3228 case Instruction::Alloca:
3229 // Alloca never returns null, malloc might.
3230 return I->getType()->getPointerAddressSpace() == 0;
3231 case Instruction::GetElementPtr:
3232 if (I->getType()->isPointerTy())
3234 break;
3235 case Instruction::BitCast: {
3236 // We need to be a bit careful here. We can only peek through the bitcast
3237 // if the scalar size of elements in the operand are smaller than and a
3238 // multiple of the size they are casting too. Take three cases:
3239 //
3240 // 1) Unsafe:
3241 // bitcast <2 x i16> %NonZero to <4 x i8>
3242 //
3243 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3244 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3245 // guranteed (imagine just sign bit set in the 2 i16 elements).
3246 //
3247 // 2) Unsafe:
3248 // bitcast <4 x i3> %NonZero to <3 x i4>
3249 //
3250 // Even though the scalar size of the src (`i3`) is smaller than the
3251 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3252 // its possible for the `3 x i4` elements to be zero because there are
3253 // some elements in the destination that don't contain any full src
3254 // element.
3255 //
3256 // 3) Safe:
3257 // bitcast <4 x i8> %NonZero to <2 x i16>
3258 //
3259 // This is always safe as non-zero in the 4 i8 elements implies
3260 // non-zero in the combination of any two adjacent ones. Since i8 is a
3261 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3262 // This all implies the 2 i16 elements are non-zero.
3263 Type *FromTy = I->getOperand(0)->getType();
3264 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3265 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3266 return isKnownNonZero(I->getOperand(0), Q, Depth);
3267 } break;
3268 case Instruction::IntToPtr:
3269 // Note that we have to take special care to avoid looking through
3270 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3271 // as casts that can alter the value, e.g., AddrSpaceCasts.
3272 if (!isa<ScalableVectorType>(I->getType()) &&
3273 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3274 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3275 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3276 break;
3277 case Instruction::PtrToAddr:
3278 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3279 // so we can directly forward.
3280 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3281 case Instruction::PtrToInt:
3282 // For inttoptr, make sure the result size is >= the address size. If the
3283 // address is non-zero, any larger value is also non-zero.
3284 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3285 I->getType()->getScalarSizeInBits())
3286 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3287 break;
3288 case Instruction::Trunc:
3289 // nuw/nsw trunc preserves zero/non-zero status of input.
3290 if (auto *TI = dyn_cast<TruncInst>(I))
3291 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3292 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3293 break;
3294
3295 // Iff x - y != 0, then x ^ y != 0
3296 // Therefore we can do the same exact checks
3297 case Instruction::Xor:
3298 case Instruction::Sub:
3299 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3300 I->getOperand(1), Depth);
3301 case Instruction::Or:
3302 // (X | (X != 0)) is non zero
3303 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3304 return true;
3305 // X | Y != 0 if X != Y.
3306 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3307 Depth))
3308 return true;
3309 // X | Y != 0 if X != 0 or Y != 0.
3310 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3311 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3312 case Instruction::SExt:
3313 case Instruction::ZExt:
3314 // ext X != 0 if X != 0.
3315 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3316
3317 case Instruction::Shl: {
3318 // shl nsw/nuw can't remove any non-zero bits.
3320 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3321 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3322
3323 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3324 // if the lowest bit is shifted off the end.
3326 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3327 if (Known.One[0])
3328 return true;
3329
3330 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3331 }
3332 case Instruction::LShr:
3333 case Instruction::AShr: {
3334 // shr exact can only shift out zero bits.
3336 if (BO->isExact())
3337 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3338
3339 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3340 // defined if the sign bit is shifted off the end.
3342 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3343 if (Known.isNegative())
3344 return true;
3345
3346 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3347 // position >= C, because the sum >= max(A, B).
3348 Value *A, *B;
3349 const APInt *C;
3350 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3351 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3352 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3353 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3354 if (!KnownA.One.lshr(*C).isZero())
3355 return true;
3356 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3357 if (!KnownB.One.lshr(*C).isZero())
3358 return true;
3359 }
3360
3361 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3362 }
3363 case Instruction::UDiv:
3364 case Instruction::SDiv: {
3365 // X / Y
3366 // div exact can only produce a zero if the dividend is zero.
3367 if (cast<PossiblyExactOperator>(I)->isExact())
3368 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3369
3370 KnownBits XKnown =
3371 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3372 // If X is fully unknown we won't be able to figure anything out so don't
3373 // both computing knownbits for Y.
3374 if (XKnown.isUnknown())
3375 return false;
3376
3377 KnownBits YKnown =
3378 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3379 if (I->getOpcode() == Instruction::SDiv) {
3380 // For signed division need to compare abs value of the operands.
3381 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3382 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3383 }
3384 // If X u>= Y then div is non zero (0/0 is UB).
3385 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3386 // If X is total unknown or X u< Y we won't be able to prove non-zero
3387 // with compute known bits so just return early.
3388 return XUgeY && *XUgeY;
3389 }
3390 case Instruction::Add: {
3391 // X + Y.
3392
3393 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3394 // non-zero.
3396 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3397 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3398 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3399 }
3400 case Instruction::Mul: {
3402 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3403 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3404 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3405 }
3406 case Instruction::Select: {
3407 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3408
3409 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3410 // then see if the select condition implies the arm is non-zero. For example
3411 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3412 // dominated by `X != 0`.
3413 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3414 Value *Op;
3415 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3416 // Op is trivially non-zero.
3417 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3418 return true;
3419
3420 // The condition of the select dominates the true/false arm. Check if the
3421 // condition implies that a given arm is non-zero.
3422 Value *X;
3423 CmpPredicate Pred;
3424 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3425 return false;
3426
3427 if (!IsTrueArm)
3428 Pred = ICmpInst::getInversePredicate(Pred);
3429
3430 return cmpExcludesZero(Pred, X);
3431 };
3432
3433 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3434 SelectArmIsNonZero(/* IsTrueArm */ false))
3435 return true;
3436 break;
3437 }
3438 case Instruction::PHI: {
3439 auto *PN = cast<PHINode>(I);
3441 return true;
3442
3443 // Check if all incoming values are non-zero using recursion.
3445 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3446 return llvm::all_of(PN->operands(), [&](const Use &U) {
3447 if (U.get() == PN)
3448 return true;
3449 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3450 // Check if the branch on the phi excludes zero.
3451 CmpPredicate Pred;
3452 Value *X;
3453 BasicBlock *TrueSucc, *FalseSucc;
3454 if (match(RecQ.CxtI,
3455 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3456 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3457 // Check for cases of duplicate successors.
3458 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3459 // If we're using the false successor, invert the predicate.
3460 if (FalseSucc == PN->getParent())
3461 Pred = CmpInst::getInversePredicate(Pred);
3462 if (cmpExcludesZero(Pred, X))
3463 return true;
3464 }
3465 }
3466 // Finally recurse on the edge and check it directly.
3467 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3468 });
3469 }
3470 case Instruction::InsertElement: {
3471 if (isa<ScalableVectorType>(I->getType()))
3472 break;
3473
3474 const Value *Vec = I->getOperand(0);
3475 const Value *Elt = I->getOperand(1);
3476 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3477
3478 unsigned NumElts = DemandedElts.getBitWidth();
3479 APInt DemandedVecElts = DemandedElts;
3480 bool SkipElt = false;
3481 // If we know the index we are inserting too, clear it from Vec check.
3482 if (CIdx && CIdx->getValue().ult(NumElts)) {
3483 DemandedVecElts.clearBit(CIdx->getZExtValue());
3484 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3485 }
3486
3487 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3488 // are non-zero.
3489 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3490 (DemandedVecElts.isZero() ||
3491 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3492 }
3493 case Instruction::ExtractElement:
3494 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3495 const Value *Vec = EEI->getVectorOperand();
3496 const Value *Idx = EEI->getIndexOperand();
3497 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3498 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3499 unsigned NumElts = VecTy->getNumElements();
3500 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3501 if (CIdx && CIdx->getValue().ult(NumElts))
3502 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3503 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3504 }
3505 }
3506 break;
3507 case Instruction::ShuffleVector: {
3508 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3509 if (!Shuf)
3510 break;
3511 APInt DemandedLHS, DemandedRHS;
3512 // For undef elements, we don't know anything about the common state of
3513 // the shuffle result.
3514 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3515 break;
3516 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3517 return (DemandedRHS.isZero() ||
3518 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3519 (DemandedLHS.isZero() ||
3520 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3521 }
3522 case Instruction::Freeze:
3523 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3524 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3525 Depth);
3526 case Instruction::Load: {
3527 auto *LI = cast<LoadInst>(I);
3528 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3529 // is never null.
3530 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3531 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3532 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3533 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3534 return true;
3535 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3537 }
3538
3539 // No need to fall through to computeKnownBits as range metadata is already
3540 // handled in isKnownNonZero.
3541 return false;
3542 }
3543 case Instruction::ExtractValue: {
3544 const WithOverflowInst *WO;
3546 switch (WO->getBinaryOp()) {
3547 default:
3548 break;
3549 case Instruction::Add:
3550 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3551 WO->getArgOperand(1),
3552 /*NSW=*/false,
3553 /*NUW=*/false, Depth);
3554 case Instruction::Sub:
3555 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3556 WO->getArgOperand(1), Depth);
3557 case Instruction::Mul:
3558 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3559 WO->getArgOperand(1),
3560 /*NSW=*/false, /*NUW=*/false, Depth);
3561 break;
3562 }
3563 }
3564 break;
3565 }
3566 case Instruction::Call:
3567 case Instruction::Invoke: {
3568 const auto *Call = cast<CallBase>(I);
3569 if (I->getType()->isPointerTy()) {
3570 if (Call->isReturnNonNull())
3571 return true;
3572 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3573 Call, /*MustPreserveOffset=*/true))
3574 return isKnownNonZero(RP, Q, Depth);
3575 } else {
3576 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3578 if (std::optional<ConstantRange> Range = Call->getRange()) {
3579 const APInt ZeroValue(Range->getBitWidth(), 0);
3580 if (!Range->contains(ZeroValue))
3581 return true;
3582 }
3583 if (const Value *RV = Call->getReturnedArgOperand())
3584 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3585 return true;
3586 }
3587
3588 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3589 switch (II->getIntrinsicID()) {
3590 case Intrinsic::sshl_sat:
3591 case Intrinsic::ushl_sat:
3592 case Intrinsic::abs:
3593 case Intrinsic::bitreverse:
3594 case Intrinsic::bswap:
3595 case Intrinsic::ctpop:
3596 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3597 // NB: We don't do usub_sat here as in any case we can prove its
3598 // non-zero, we will fold it to `sub nuw` in InstCombine.
3599 case Intrinsic::ssub_sat:
3600 // For most types, if x != y then ssub.sat x, y != 0. But
3601 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3602 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3603 if (BitWidth == 1)
3604 return false;
3605 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3606 II->getArgOperand(1), Depth);
3607 case Intrinsic::sadd_sat:
3608 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3609 II->getArgOperand(1),
3610 /*NSW=*/true, /* NUW=*/false, Depth);
3611 // Vec reverse preserves zero/non-zero status from input vec.
3612 case Intrinsic::vector_reverse:
3613 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3614 Q, Depth);
3615 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3616 case Intrinsic::vector_reduce_or:
3617 case Intrinsic::vector_reduce_umax:
3618 case Intrinsic::vector_reduce_umin:
3619 case Intrinsic::vector_reduce_smax:
3620 case Intrinsic::vector_reduce_smin:
3621 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3622 case Intrinsic::umax:
3623 case Intrinsic::uadd_sat:
3624 // umax(X, (X != 0)) is non zero
3625 // X +usat (X != 0) is non zero
3626 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3627 return true;
3628
3629 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3630 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3631 case Intrinsic::smax: {
3632 // If either arg is strictly positive the result is non-zero. Otherwise
3633 // the result is non-zero if both ops are non-zero.
3634 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3635 const KnownBits &OpKnown) {
3636 if (!OpNonZero.has_value())
3637 OpNonZero = OpKnown.isNonZero() ||
3638 isKnownNonZero(Op, DemandedElts, Q, Depth);
3639 return *OpNonZero;
3640 };
3641 // Avoid re-computing isKnownNonZero.
3642 std::optional<bool> Op0NonZero, Op1NonZero;
3643 KnownBits Op1Known =
3644 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3645 if (Op1Known.isNonNegative() &&
3646 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3647 return true;
3648 KnownBits Op0Known =
3649 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3650 if (Op0Known.isNonNegative() &&
3651 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3652 return true;
3653 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3654 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3655 }
3656 case Intrinsic::smin: {
3657 // If either arg is negative the result is non-zero. Otherwise
3658 // the result is non-zero if both ops are non-zero.
3659 KnownBits Op1Known =
3660 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3661 if (Op1Known.isNegative())
3662 return true;
3663 KnownBits Op0Known =
3664 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3665 if (Op0Known.isNegative())
3666 return true;
3667
3668 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3669 return true;
3670 }
3671 [[fallthrough]];
3672 case Intrinsic::umin:
3673 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3674 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3675 case Intrinsic::cttz:
3676 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3677 .Zero[0];
3678 case Intrinsic::ctlz:
3679 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3680 .isNonNegative();
3681 case Intrinsic::fshr:
3682 case Intrinsic::fshl:
3683 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3684 if (II->getArgOperand(0) == II->getArgOperand(1))
3685 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3686 break;
3687 case Intrinsic::vscale:
3688 return true;
3689 case Intrinsic::experimental_get_vector_length:
3690 return isKnownNonZero(I->getOperand(0), Q, Depth);
3691 default:
3692 break;
3693 }
3694 break;
3695 }
3696
3697 return false;
3698 }
3699 }
3700
3702 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3703 return Known.One != 0;
3704}
3705
3706/// Return true if the given value is known to be non-zero when defined. For
3707/// vectors, return true if every demanded element is known to be non-zero when
3708/// defined. For pointers, if the context instruction and dominator tree are
3709/// specified, perform context-sensitive analysis and return true if the
3710/// pointer couldn't possibly be null at the specified instruction.
3711/// Supports values with integer or pointer type and vectors of integers.
3712bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3713 const SimplifyQuery &Q, unsigned Depth) {
3714 Type *Ty = V->getType();
3715
3716#ifndef NDEBUG
3717 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3718
3719 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3720 assert(
3721 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3722 "DemandedElt width should equal the fixed vector number of elements");
3723 } else {
3724 assert(DemandedElts == APInt(1, 1) &&
3725 "DemandedElt width should be 1 for scalars");
3726 }
3727#endif
3728
3729 if (auto *C = dyn_cast<Constant>(V)) {
3730 if (C->isNullValue())
3731 return false;
3732 if (isa<ConstantInt>(C))
3733 // Must be non-zero due to null test above.
3734 return true;
3735
3736 // For constant vectors, check that all elements are poison or known
3737 // non-zero to determine that the whole vector is known non-zero.
3738 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3739 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3740 if (!DemandedElts[i])
3741 continue;
3742 Constant *Elt = C->getAggregateElement(i);
3743 if (!Elt || Elt->isNullValue())
3744 return false;
3745 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3746 return false;
3747 }
3748 return true;
3749 }
3750
3751 // Constant ptrauth can be null, iff the base pointer can be.
3752 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3753 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3754
3755 // A global variable in address space 0 is non null unless extern weak
3756 // or an absolute symbol reference. Other address spaces may have null as a
3757 // valid address for a global, so we can't assume anything.
3758 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3759 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3760 GV->getType()->getAddressSpace() == 0)
3761 return true;
3762 }
3763
3764 // For constant expressions, fall through to the Operator code below.
3765 if (!isa<ConstantExpr>(V))
3766 return false;
3767 }
3768
3769 if (const auto *A = dyn_cast<Argument>(V))
3770 if (std::optional<ConstantRange> Range = A->getRange()) {
3771 const APInt ZeroValue(Range->getBitWidth(), 0);
3772 if (!Range->contains(ZeroValue))
3773 return true;
3774 }
3775
3776 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3777 return true;
3778
3779 // Some of the tests below are recursive, so bail out if we hit the limit.
3781 return false;
3782
3783 // Check for pointer simplifications.
3784
3785 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3786 // A byval, inalloca may not be null in a non-default addres space. A
3787 // nonnull argument is assumed never 0.
3788 if (const Argument *A = dyn_cast<Argument>(V)) {
3789 if (((A->hasPassPointeeByValueCopyAttr() &&
3790 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3791 A->hasNonNullAttr()))
3792 return true;
3793 }
3794 }
3795
3796 if (const auto *I = dyn_cast<Operator>(V))
3797 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3798 return true;
3799
3800 if (!isa<Constant>(V) &&
3802 return true;
3803
3804 if (const Value *Stripped = stripNullTest(V))
3805 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3806
3807 return false;
3808}
3809
3811 unsigned Depth) {
3812 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3813 APInt DemandedElts =
3814 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3815 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3816}
3817
3818/// If the pair of operators are the same invertible function, return the
3819/// the operands of the function corresponding to each input. Otherwise,
3820/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3821/// every input value to exactly one output value. This is equivalent to
3822/// saying that Op1 and Op2 are equal exactly when the specified pair of
3823/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3824static std::optional<std::pair<Value*, Value*>>
3826 const Operator *Op2) {
3827 if (Op1->getOpcode() != Op2->getOpcode())
3828 return std::nullopt;
3829
3830 auto getOperands = [&](unsigned OpNum) -> auto {
3831 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3832 };
3833
3834 switch (Op1->getOpcode()) {
3835 default:
3836 break;
3837 case Instruction::Or:
3838 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3839 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3840 break;
3841 [[fallthrough]];
3842 case Instruction::Xor:
3843 case Instruction::Add: {
3844 Value *Other;
3845 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3846 return std::make_pair(Op1->getOperand(1), Other);
3847 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3848 return std::make_pair(Op1->getOperand(0), Other);
3849 break;
3850 }
3851 case Instruction::Sub:
3852 if (Op1->getOperand(0) == Op2->getOperand(0))
3853 return getOperands(1);
3854 if (Op1->getOperand(1) == Op2->getOperand(1))
3855 return getOperands(0);
3856 break;
3857 case Instruction::Mul: {
3858 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3859 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3860 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3861 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3862 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3863 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3864 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3865 break;
3866
3867 // Assume operand order has been canonicalized
3868 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3869 isa<ConstantInt>(Op1->getOperand(1)) &&
3870 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3871 return getOperands(0);
3872 break;
3873 }
3874 case Instruction::Shl: {
3875 // Same as multiplies, with the difference that we don't need to check
3876 // for a non-zero multiply. Shifts always multiply by non-zero.
3877 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3878 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3879 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3880 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3881 break;
3882
3883 if (Op1->getOperand(1) == Op2->getOperand(1))
3884 return getOperands(0);
3885 break;
3886 }
3887 case Instruction::AShr:
3888 case Instruction::LShr: {
3889 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3890 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3891 if (!PEO1->isExact() || !PEO2->isExact())
3892 break;
3893
3894 if (Op1->getOperand(1) == Op2->getOperand(1))
3895 return getOperands(0);
3896 break;
3897 }
3898 case Instruction::SExt:
3899 case Instruction::ZExt:
3900 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3901 return getOperands(0);
3902 break;
3903 case Instruction::PHI: {
3904 const PHINode *PN1 = cast<PHINode>(Op1);
3905 const PHINode *PN2 = cast<PHINode>(Op2);
3906
3907 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3908 // are a single invertible function of the start values? Note that repeated
3909 // application of an invertible function is also invertible
3910 BinaryOperator *BO1 = nullptr;
3911 Value *Start1 = nullptr, *Step1 = nullptr;
3912 BinaryOperator *BO2 = nullptr;
3913 Value *Start2 = nullptr, *Step2 = nullptr;
3914 if (PN1->getParent() != PN2->getParent() ||
3915 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3916 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3917 break;
3918
3920 cast<Operator>(BO2));
3921 if (!Values)
3922 break;
3923
3924 // We have to be careful of mutually defined recurrences here. Ex:
3925 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3926 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3927 // The invertibility of these is complicated, and not worth reasoning
3928 // about (yet?).
3929 if (Values->first != PN1 || Values->second != PN2)
3930 break;
3931
3932 return std::make_pair(Start1, Start2);
3933 }
3934 }
3935 return std::nullopt;
3936}
3937
3938/// Return true if V1 == (binop V2, X), where X is known non-zero.
3939/// Only handle a small subset of binops where (binop V2, X) with non-zero X
3940/// implies V2 != V1.
3941static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
3942 const APInt &DemandedElts,
3943 const SimplifyQuery &Q, unsigned Depth) {
3945 if (!BO)
3946 return false;
3947 switch (BO->getOpcode()) {
3948 default:
3949 break;
3950 case Instruction::Or:
3951 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3952 break;
3953 [[fallthrough]];
3954 case Instruction::Xor:
3955 case Instruction::Add:
3956 Value *Op = nullptr;
3957 if (V2 == BO->getOperand(0))
3958 Op = BO->getOperand(1);
3959 else if (V2 == BO->getOperand(1))
3960 Op = BO->getOperand(0);
3961 else
3962 return false;
3963 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
3964 }
3965 return false;
3966}
3967
3968/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3969/// the multiplication is nuw or nsw.
3970static bool isNonEqualMul(const Value *V1, const Value *V2,
3971 const APInt &DemandedElts, const SimplifyQuery &Q,
3972 unsigned Depth) {
3973 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3974 const APInt *C;
3975 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
3976 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3977 !C->isZero() && !C->isOne() &&
3978 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
3979 }
3980 return false;
3981}
3982
3983/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
3984/// the shift is nuw or nsw.
3985static bool isNonEqualShl(const Value *V1, const Value *V2,
3986 const APInt &DemandedElts, const SimplifyQuery &Q,
3987 unsigned Depth) {
3988 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3989 const APInt *C;
3990 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
3991 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3992 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
3993 }
3994 return false;
3995}
3996
3997static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
3998 const APInt &DemandedElts, const SimplifyQuery &Q,
3999 unsigned Depth) {
4000 // Check two PHIs are in same block.
4001 if (PN1->getParent() != PN2->getParent())
4002 return false;
4003
4005 bool UsedFullRecursion = false;
4006 for (const BasicBlock *IncomBB : PN1->blocks()) {
4007 if (!VisitedBBs.insert(IncomBB).second)
4008 continue; // Don't reprocess blocks that we have dealt with already.
4009 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4010 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4011 const APInt *C1, *C2;
4012 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4013 continue;
4014
4015 // Only one pair of phi operands is allowed for full recursion.
4016 if (UsedFullRecursion)
4017 return false;
4018
4020 RecQ.CxtI = IncomBB->getTerminator();
4021 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4022 return false;
4023 UsedFullRecursion = true;
4024 }
4025 return true;
4026}
4027
4028static bool isNonEqualSelect(const Value *V1, const Value *V2,
4029 const APInt &DemandedElts, const SimplifyQuery &Q,
4030 unsigned Depth) {
4031 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4032 if (!SI1)
4033 return false;
4034
4035 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4036 const Value *Cond1 = SI1->getCondition();
4037 const Value *Cond2 = SI2->getCondition();
4038 if (Cond1 == Cond2)
4039 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4040 DemandedElts, Q, Depth + 1) &&
4041 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4042 DemandedElts, Q, Depth + 1);
4043 }
4044 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4045 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4046}
4047
4048// Check to see if A is both a GEP and is the incoming value for a PHI in the
4049// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4050// one of them being the recursive GEP A and the other a ptr at same base and at
4051// the same/higher offset than B we are only incrementing the pointer further in
4052// loop if offset of recursive GEP is greater than 0.
4054 const SimplifyQuery &Q) {
4055 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4056 return false;
4057
4058 auto *GEPA = dyn_cast<GEPOperator>(A);
4059 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4060 return false;
4061
4062 // Handle 2 incoming PHI values with one being a recursive GEP.
4063 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4064 if (!PN || PN->getNumIncomingValues() != 2)
4065 return false;
4066
4067 // Search for the recursive GEP as an incoming operand, and record that as
4068 // Step.
4069 Value *Start = nullptr;
4070 Value *Step = const_cast<Value *>(A);
4071 if (PN->getIncomingValue(0) == Step)
4072 Start = PN->getIncomingValue(1);
4073 else if (PN->getIncomingValue(1) == Step)
4074 Start = PN->getIncomingValue(0);
4075 else
4076 return false;
4077
4078 // Other incoming node base should match the B base.
4079 // StartOffset >= OffsetB && StepOffset > 0?
4080 // StartOffset <= OffsetB && StepOffset < 0?
4081 // Is non-equal if above are true.
4082 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4083 // optimisation to inbounds GEPs only.
4084 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4085 APInt StartOffset(IndexWidth, 0);
4086 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4087 APInt StepOffset(IndexWidth, 0);
4088 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4089
4090 // Check if Base Pointer of Step matches the PHI.
4091 if (Step != PN)
4092 return false;
4093 APInt OffsetB(IndexWidth, 0);
4094 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4095 return Start == B &&
4096 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4097 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4098}
4099
4100static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4101 const SimplifyQuery &Q, unsigned Depth) {
4102 if (!Q.CxtI)
4103 return false;
4104
4105 // Try to infer NonEqual based on information from dominating conditions.
4106 if (Q.DC && Q.DT) {
4107 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4108 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4109 Value *Cond = BI->getCondition();
4110 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4111 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4113 /*LHSIsTrue=*/true, Depth)
4114 .value_or(false))
4115 return true;
4116
4117 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4118 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4120 /*LHSIsTrue=*/false, Depth)
4121 .value_or(false))
4122 return true;
4123 }
4124
4125 return false;
4126 };
4127
4128 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4129 IsKnownNonEqualFromDominatingCondition(V2))
4130 return true;
4131 }
4132
4133 if (!Q.AC)
4134 return false;
4135
4136 // Try to infer NonEqual based on information from assumptions.
4137 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4138 if (!AssumeVH)
4139 continue;
4140 CallInst *I = cast<CallInst>(AssumeVH);
4141
4142 assert(I->getFunction() == Q.CxtI->getFunction() &&
4143 "Got assumption for the wrong function!");
4144 assert(I->getIntrinsicID() == Intrinsic::assume &&
4145 "must be an assume intrinsic");
4146
4147 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4148 /*LHSIsTrue=*/true, Depth)
4149 .value_or(false) &&
4151 return true;
4152 }
4153
4154 return false;
4155}
4156
4157static bool isNonEqualURem(const Value *X, const Value *Rem,
4158 const SimplifyQuery &Q) {
4159 const Value *Y;
4160 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4161 return false;
4162
4163 // For a defined urem, X != X urem Y exactly when X u>= Y.
4164 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4166 return true;
4167
4168 std::optional<bool> Implied =
4170 return Implied && *Implied;
4171}
4172
4173/// Return true if it is known that V1 != V2.
4174static bool isKnownNonEqual(const Value *V1, const Value *V2,
4175 const APInt &DemandedElts, const SimplifyQuery &Q,
4176 unsigned Depth) {
4177 if (V1 == V2)
4178 return false;
4179 if (V1->getType() != V2->getType())
4180 // We can't look through casts yet.
4181 return false;
4182
4184 return false;
4185
4186 // See if we can recurse through (exactly one of) our operands. This
4187 // requires our operation be 1-to-1 and map every input value to exactly
4188 // one output value. Such an operation is invertible.
4189 auto *O1 = dyn_cast<Operator>(V1);
4190 auto *O2 = dyn_cast<Operator>(V2);
4191 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4192 if (auto Values = getInvertibleOperands(O1, O2))
4193 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4194 Depth + 1);
4195
4196 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4197 const PHINode *PN2 = cast<PHINode>(V2);
4198 // FIXME: This is missing a generalization to handle the case where one is
4199 // a PHI and another one isn't.
4200 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4201 return true;
4202 };
4203 }
4204
4205 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4206 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4207 return true;
4208
4209 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4210 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4211 return true;
4212
4213 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4214 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4215 return true;
4216
4217 if (V1->getType()->isIntOrIntVectorTy()) {
4218 // Are any known bits in V1 contradictory to known bits in V2? If V1
4219 // has a known zero where V2 has a known one, they must not be equal.
4220 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4221 if (!Known1.isUnknown()) {
4222 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4223 if (Known1.Zero.intersects(Known2.One) ||
4224 Known2.Zero.intersects(Known1.One))
4225 return true;
4226 }
4227 }
4228
4229 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4230 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4231 return true;
4232
4235 return true;
4236
4237 Value *A, *B;
4238 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4239 // Check PtrToInt type matches the pointer size.
4240 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4242 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4243
4244 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4245 return true;
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 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4686
4687 LibFunc Func = TLI->getLibFunc(CB);
4688 if (Func == NotLibFunc)
4690
4691 switch (Func) {
4692 default:
4693 break;
4694 case LibFunc_sin:
4695 case LibFunc_sinf:
4696 case LibFunc_sinl:
4697 return Intrinsic::sin;
4698 case LibFunc_cos:
4699 case LibFunc_cosf:
4700 case LibFunc_cosl:
4701 return Intrinsic::cos;
4702 case LibFunc_tan:
4703 case LibFunc_tanf:
4704 case LibFunc_tanl:
4705 return Intrinsic::tan;
4706 case LibFunc_asin:
4707 case LibFunc_asinf:
4708 case LibFunc_asinl:
4709 return Intrinsic::asin;
4710 case LibFunc_acos:
4711 case LibFunc_acosf:
4712 case LibFunc_acosl:
4713 return Intrinsic::acos;
4714 case LibFunc_atan:
4715 case LibFunc_atanf:
4716 case LibFunc_atanl:
4717 return Intrinsic::atan;
4718 case LibFunc_atan2:
4719 case LibFunc_atan2f:
4720 case LibFunc_atan2l:
4721 return Intrinsic::atan2;
4722 case LibFunc_sinh:
4723 case LibFunc_sinhf:
4724 case LibFunc_sinhl:
4725 return Intrinsic::sinh;
4726 case LibFunc_cosh:
4727 case LibFunc_coshf:
4728 case LibFunc_coshl:
4729 return Intrinsic::cosh;
4730 case LibFunc_tanh:
4731 case LibFunc_tanhf:
4732 case LibFunc_tanhl:
4733 return Intrinsic::tanh;
4734 case LibFunc_exp:
4735 case LibFunc_expf:
4736 case LibFunc_expl:
4737 return Intrinsic::exp;
4738 case LibFunc_exp2:
4739 case LibFunc_exp2f:
4740 case LibFunc_exp2l:
4741 return Intrinsic::exp2;
4742 case LibFunc_exp10:
4743 case LibFunc_exp10f:
4744 case LibFunc_exp10l:
4745 return Intrinsic::exp10;
4746 case LibFunc_log:
4747 case LibFunc_logf:
4748 case LibFunc_logl:
4749 return Intrinsic::log;
4750 case LibFunc_log10:
4751 case LibFunc_log10f:
4752 case LibFunc_log10l:
4753 return Intrinsic::log10;
4754 case LibFunc_log2:
4755 case LibFunc_log2f:
4756 case LibFunc_log2l:
4757 return Intrinsic::log2;
4758 case LibFunc_fabs:
4759 case LibFunc_fabsf:
4760 case LibFunc_fabsl:
4761 return Intrinsic::fabs;
4762 case LibFunc_fmin:
4763 case LibFunc_fminf:
4764 case LibFunc_fminl:
4765 return Intrinsic::minnum;
4766 case LibFunc_fmax:
4767 case LibFunc_fmaxf:
4768 case LibFunc_fmaxl:
4769 return Intrinsic::maxnum;
4770 case LibFunc_copysign:
4771 case LibFunc_copysignf:
4772 case LibFunc_copysignl:
4773 return Intrinsic::copysign;
4774 case LibFunc_floor:
4775 case LibFunc_floorf:
4776 case LibFunc_floorl:
4777 return Intrinsic::floor;
4778 case LibFunc_ceil:
4779 case LibFunc_ceilf:
4780 case LibFunc_ceill:
4781 return Intrinsic::ceil;
4782 case LibFunc_trunc:
4783 case LibFunc_truncf:
4784 case LibFunc_truncl:
4785 return Intrinsic::trunc;
4786 case LibFunc_rint:
4787 case LibFunc_rintf:
4788 case LibFunc_rintl:
4789 return Intrinsic::rint;
4790 case LibFunc_nearbyint:
4791 case LibFunc_nearbyintf:
4792 case LibFunc_nearbyintl:
4793 return Intrinsic::nearbyint;
4794 case LibFunc_round:
4795 case LibFunc_roundf:
4796 case LibFunc_roundl:
4797 return Intrinsic::round;
4798 case LibFunc_roundeven:
4799 case LibFunc_roundevenf:
4800 case LibFunc_roundevenl:
4801 return Intrinsic::roundeven;
4802 case LibFunc_pow:
4803 case LibFunc_powf:
4804 case LibFunc_powl:
4805 return Intrinsic::pow;
4806 case LibFunc_sqrt:
4807 case LibFunc_sqrtf:
4808 case LibFunc_sqrtl:
4809 return Intrinsic::sqrt;
4810 }
4811
4813}
4814
4815/// Given an exploded icmp instruction, return true if the comparison only
4816/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4817/// the result of the comparison is true when the input value is signed.
4819 bool &TrueIfSigned) {
4820 switch (Pred) {
4821 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4822 TrueIfSigned = true;
4823 return RHS.isZero();
4824 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4825 TrueIfSigned = true;
4826 return RHS.isAllOnes();
4827 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4828 TrueIfSigned = false;
4829 return RHS.isAllOnes();
4830 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4831 TrueIfSigned = false;
4832 return RHS.isZero();
4833 case ICmpInst::ICMP_UGT:
4834 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4835 TrueIfSigned = true;
4836 return RHS.isMaxSignedValue();
4837 case ICmpInst::ICMP_UGE:
4838 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4839 TrueIfSigned = true;
4840 return RHS.isMinSignedValue();
4841 case ICmpInst::ICMP_ULT:
4842 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4843 TrueIfSigned = false;
4844 return RHS.isMinSignedValue();
4845 case ICmpInst::ICMP_ULE:
4846 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4847 TrueIfSigned = false;
4848 return RHS.isMaxSignedValue();
4849 default:
4850 return false;
4851 }
4852}
4853
4855 bool CondIsTrue,
4856 const Instruction *CxtI,
4857 KnownFPClass &KnownFromContext,
4858 unsigned Depth = 0) {
4859 Value *A, *B;
4861 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4862 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4863 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4864 Depth + 1);
4865 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4866 Depth + 1);
4867 return;
4868 }
4870 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4871 Depth + 1);
4872 return;
4873 }
4874 CmpPredicate Pred;
4875 Value *LHS;
4876 uint64_t ClassVal = 0;
4877 const APFloat *CRHS;
4878 const APInt *RHS;
4879 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4880 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4881 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4882 LHS != V);
4883 if (CmpVal == V)
4884 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4886 m_Specific(V), m_ConstantInt(ClassVal)))) {
4887 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4888 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4889 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4890 m_APInt(RHS)))) {
4891 bool TrueIfSigned;
4892 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4893 return;
4894 if (TrueIfSigned == CondIsTrue)
4895 KnownFromContext.signBitMustBeOne();
4896 else
4897 KnownFromContext.signBitMustBeZero();
4898 }
4899}
4900
4901/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4902/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4903/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4904/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4905/// exponent range is [-149, -2], but the 0 edge case is above this range).
4906static std::tuple<int, int, int>
4908 if (!Q.CxtI || !Q.DC || !Q.DT)
4910
4911 // Intersect the bounds implied by every dominating condition, keeping the
4912 // tightest maximum. A value may participate in multiple compares
4913 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4914 int MaxExp = APFloat::IEK_Inf;
4915 int MaxExpNonZero = APFloat::IEK_Inf;
4916
4917 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4918 CmpPredicate Pred;
4919 const APFloat *LimitC;
4920 if (!match(BI->getCondition(),
4921 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4922 continue;
4923
4924 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4925 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4926 continue;
4927
4928 // If fabs(x) <= K, implies the exponent min exp range.
4929 // if fabs(x) >= K, swap the successor
4930 bool IsLessEqual =
4931 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
4932 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
4933 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
4934
4935 bool KnownStrictlyLess =
4936 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
4937 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
4938
4939 BasicBlockEdge Edge1(BI->getParent(),
4940 BI->getSuccessor(IsLessEqual ? 0 : 1));
4941 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
4942 // frexp returns an exponent one greater than ilogb.
4943 int Exp = ilogb(*LimitC) + 1;
4944
4945 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
4946 // exponent drops by one when K is exact power of two.
4947 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
4948 --Exp;
4949
4950 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
4951 // may exclude.
4952
4953 // TODO: Figure out lower bound to detect no-underflow.
4954 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
4955 MaxExp = std::min(MaxExp, std::max(Exp, 0));
4956 }
4957 }
4958
4959 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
4960}
4961
4963 const SimplifyQuery &Q) {
4964 KnownFPClass KnownFromContext;
4965
4966 if (Q.CC && Q.CC->AffectedValues.contains(V))
4968 KnownFromContext);
4969
4970 if (!Q.CxtI)
4971 return KnownFromContext;
4972
4973 if (Q.DC && Q.DT) {
4974 // Handle dominating conditions.
4975 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4976 Value *Cond = BI->getCondition();
4977
4978 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4979 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
4980 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
4981 KnownFromContext);
4982
4983 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4984 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
4985 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
4986 KnownFromContext);
4987 }
4988 }
4989
4990 if (!Q.AC)
4991 return KnownFromContext;
4992
4993 // Try to restrict the floating-point classes based on information from
4994 // assumptions.
4995 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
4996 if (!AssumeVH)
4997 continue;
4998 CallInst *I = cast<CallInst>(AssumeVH);
4999
5000 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5001 "Got assumption for the wrong function!");
5002 assert(I->getIntrinsicID() == Intrinsic::assume &&
5003 "must be an assume intrinsic");
5004
5005 if (!isValidAssumeForContext(I, Q))
5006 continue;
5007
5008 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5009 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5010 }
5011
5012 return KnownFromContext;
5013}
5014
5016 Value *Arm, bool Invert,
5017 const SimplifyQuery &SQ,
5018 unsigned Depth) {
5019
5020 KnownFPClass KnownSrc;
5022 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5023 Depth + 1);
5024 KnownSrc = KnownSrc.unionWith(Known);
5025 if (KnownSrc.isUnknown())
5026 return;
5027
5028 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5029 Known = KnownSrc;
5030}
5031
5032void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5033 FPClassTest InterestedClasses, KnownFPClass &Known,
5034 const SimplifyQuery &Q, unsigned Depth);
5035
5037 FPClassTest InterestedClasses,
5038 const SimplifyQuery &Q, unsigned Depth) {
5039 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5040 APInt DemandedElts =
5041 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5042 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5043}
5044
5046 const APInt &DemandedElts,
5047 FPClassTest InterestedClasses,
5049 const SimplifyQuery &Q,
5050 unsigned Depth) {
5051 if ((InterestedClasses &
5053 return;
5054
5055 KnownFPClass KnownSrc;
5056 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5057 KnownSrc, Q, Depth + 1);
5058 Known = KnownFPClass::fptrunc(KnownSrc);
5059}
5060
5062 switch (IID) {
5063 case Intrinsic::minimum:
5065 case Intrinsic::maximum:
5067 case Intrinsic::minimumnum:
5069 case Intrinsic::maximumnum:
5071 case Intrinsic::minnum:
5073 case Intrinsic::maxnum:
5075 default:
5076 llvm_unreachable("not a floating-point min-max intrinsic");
5077 }
5078}
5079
5080/// \return true if this is a floating point value that is known to have a
5081/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5082static bool isAbsoluteValueULEOne(const Value *V) {
5083 // TODO: Handle frexp
5084 // TODO: Other rounding intrinsics?
5085 // TODO: Try computeKnownExponentRangeFromContext
5086
5087 // fabs(x - floor(x)) <= 1
5088 const Value *SubFloorX;
5089 if (match(V, m_FSub(m_Value(SubFloorX),
5091 return true;
5092
5095}
5096
5097void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5098 FPClassTest InterestedClasses, KnownFPClass &Known,
5099 const SimplifyQuery &Q, unsigned Depth) {
5100 assert(Known.isUnknown() && "should not be called with known information");
5101
5102 if (!DemandedElts) {
5103 // No demanded elts, better to assume we don't know anything.
5104 Known.resetAll();
5105 return;
5106 }
5107
5108 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5109
5110 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5111 Known = KnownFPClass(CFP->getValueAPF());
5112 return;
5113 }
5114
5116 Known.KnownFPClasses = fcPosZero;
5117 Known.SignBit = false;
5118 return;
5119 }
5120
5121 if (isa<PoisonValue>(V)) {
5122 Known.KnownFPClasses = fcNone;
5123 Known.SignBit = false;
5124 return;
5125 }
5126
5127 // Try to handle fixed width vector constants
5128 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5129 const Constant *CV = dyn_cast<Constant>(V);
5130 if (VFVTy && CV) {
5131 Known.KnownFPClasses = fcNone;
5132 bool SignBitAllZero = true;
5133 bool SignBitAllOne = true;
5134
5135 // For vectors, verify that each element is not NaN.
5136 unsigned NumElts = VFVTy->getNumElements();
5137 for (unsigned i = 0; i != NumElts; ++i) {
5138 if (!DemandedElts[i])
5139 continue;
5140
5141 Constant *Elt = CV->getAggregateElement(i);
5142 if (!Elt) {
5143 Known = KnownFPClass();
5144 return;
5145 }
5146 if (isa<PoisonValue>(Elt))
5147 continue;
5148 auto *CElt = dyn_cast<ConstantFP>(Elt);
5149 if (!CElt) {
5150 Known = KnownFPClass();
5151 return;
5152 }
5153
5154 const APFloat &C = CElt->getValueAPF();
5155 Known.KnownFPClasses |= C.classify();
5156 if (C.isNegative())
5157 SignBitAllZero = false;
5158 else
5159 SignBitAllOne = false;
5160 }
5161 if (SignBitAllOne != SignBitAllZero)
5162 Known.SignBit = SignBitAllOne;
5163 return;
5164 }
5165
5166 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5167 Known.KnownFPClasses = fcNone;
5168 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5169 Known |= CDS->getElementAsAPFloat(I).classify();
5170 return;
5171 }
5172
5173 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5174 // TODO: Handle complex aggregates
5175 Known.KnownFPClasses = fcNone;
5176 for (const Use &Op : CA->operands()) {
5177 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5178 if (!CFP) {
5179 Known = KnownFPClass();
5180 return;
5181 }
5182
5183 Known |= CFP->getValueAPF().classify();
5184 }
5185
5186 return;
5187 }
5188
5189 FPClassTest KnownNotFromFlags = fcNone;
5190 if (const auto *CB = dyn_cast<CallBase>(V))
5191 KnownNotFromFlags |= CB->getRetNoFPClass();
5192 else if (const auto *Arg = dyn_cast<Argument>(V))
5193 KnownNotFromFlags |= Arg->getNoFPClass();
5194
5195 const Operator *Op = dyn_cast<Operator>(V);
5197 if (FPOp->hasNoNaNs())
5198 KnownNotFromFlags |= fcNan;
5199 if (FPOp->hasNoInfs())
5200 KnownNotFromFlags |= fcInf;
5201 }
5202
5203 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5204 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5205
5206 // We no longer need to find out about these bits from inputs if we can
5207 // assume this from flags/attributes.
5208 InterestedClasses &= ~KnownNotFromFlags;
5209
5210 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5211 Known.knownNot(KnownNotFromFlags);
5212 if (!Known.SignBit && AssumedClasses.SignBit) {
5213 if (*AssumedClasses.SignBit)
5214 Known.signBitMustBeOne();
5215 else
5216 Known.signBitMustBeZero();
5217 }
5218 });
5219
5220 if (!Op)
5221 return;
5222
5223 // All recursive calls that increase depth must come after this.
5225 return;
5226
5227 const unsigned Opc = Op->getOpcode();
5228 switch (Opc) {
5229 case Instruction::FNeg: {
5230 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5231 Known, Q, Depth + 1);
5232 Known.fneg();
5233 break;
5234 }
5235 case Instruction::Select: {
5236 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5237 KnownFPClass Res;
5238 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5239 Depth + 1);
5240 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5241 Depth);
5242 return Res;
5243 };
5244 // Only known if known in both the LHS and RHS.
5245 Known =
5246 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5247 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5248 break;
5249 }
5250 case Instruction::Load: {
5251 const MDNode *NoFPClass =
5252 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5253 if (!NoFPClass)
5254 break;
5255
5256 ConstantInt *MaskVal =
5258 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5259 break;
5260 }
5261 case Instruction::Call: {
5262 const CallInst *II = cast<CallInst>(Op);
5263 const Intrinsic::ID IID = II->getIntrinsicID();
5264 switch (IID) {
5265 case Intrinsic::fabs: {
5266 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5267 // If we only care about the sign bit we don't need to inspect the
5268 // operand.
5269 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5270 InterestedClasses, Known, Q, Depth + 1);
5271 }
5272
5273 Known.fabs();
5274 break;
5275 }
5276 case Intrinsic::copysign: {
5277 KnownFPClass KnownSign;
5278
5279 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5280 Known, Q, Depth + 1);
5281 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5282 KnownSign, Q, Depth + 1);
5283 Known.copysign(KnownSign);
5284 break;
5285 }
5286 case Intrinsic::fma:
5287 case Intrinsic::fmuladd: {
5288 if ((InterestedClasses & fcNegative) == fcNone)
5289 break;
5290
5291 // FIXME: This should check isGuaranteedNotToBeUndef
5292 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5293 KnownFPClass KnownSrc, KnownAddend;
5294 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5295 InterestedClasses, KnownAddend, Q, Depth + 1);
5296 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5297 InterestedClasses, KnownSrc, Q, Depth + 1);
5298
5299 const Function *F = II->getFunction();
5300 const fltSemantics &FltSem =
5301 II->getType()->getScalarType()->getFltSemantics();
5303 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5304
5305 if (KnownNotFromFlags & fcNan) {
5306 KnownSrc.knownNot(fcNan);
5307 KnownAddend.knownNot(fcNan);
5308 }
5309
5310 if (KnownNotFromFlags & fcInf) {
5311 KnownSrc.knownNot(fcInf);
5312 KnownAddend.knownNot(fcInf);
5313 }
5314
5315 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5316 break;
5317 }
5318
5319 KnownFPClass KnownSrc[3];
5320 for (int I = 0; I != 3; ++I) {
5321 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5322 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5323 if (KnownSrc[I].isUnknown())
5324 return;
5325
5326 if (KnownNotFromFlags & fcNan)
5327 KnownSrc[I].knownNot(fcNan);
5328 if (KnownNotFromFlags & fcInf)
5329 KnownSrc[I].knownNot(fcInf);
5330 }
5331
5332 const Function *F = II->getFunction();
5333 const fltSemantics &FltSem =
5334 II->getType()->getScalarType()->getFltSemantics();
5336 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5337 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5338 break;
5339 }
5340 case Intrinsic::sqrt:
5341 case Intrinsic::experimental_constrained_sqrt: {
5342 KnownFPClass KnownSrc;
5343 FPClassTest InterestedSrcs = InterestedClasses;
5344 if (InterestedClasses & fcNan)
5345 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5346
5347 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5348 KnownSrc, Q, Depth + 1);
5349
5351
5352 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5353 if (!HasNSZ) {
5354 const Function *F = II->getFunction();
5355 const fltSemantics &FltSem =
5356 II->getType()->getScalarType()->getFltSemantics();
5357 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5358 }
5359
5360 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5361 if (HasNSZ)
5362 Known.knownNot(fcNegZero);
5363
5364 break;
5365 }
5366 case Intrinsic::sin: {
5367 KnownFPClass KnownSrc;
5368 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5369 KnownSrc, Q, Depth + 1);
5370 Known = KnownFPClass::sin(KnownSrc);
5371 break;
5372 }
5373 case Intrinsic::cos: {
5374 KnownFPClass KnownSrc;
5375 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5376 KnownSrc, Q, Depth + 1);
5377 Known = KnownFPClass::cos(KnownSrc);
5378 break;
5379 }
5380 case Intrinsic::tan: {
5381 KnownFPClass KnownSrc;
5382 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5383 KnownSrc, Q, Depth + 1);
5384 Known = KnownFPClass::tan(KnownSrc);
5385 break;
5386 }
5387 case Intrinsic::sinh: {
5388 KnownFPClass KnownSrc;
5389 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5390 KnownSrc, Q, Depth + 1);
5391 Known = KnownFPClass::sinh(KnownSrc);
5392 break;
5393 }
5394 case Intrinsic::cosh: {
5395 KnownFPClass KnownSrc;
5396 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5397 KnownSrc, Q, Depth + 1);
5398 Known = KnownFPClass::cosh(KnownSrc);
5399 break;
5400 }
5401 case Intrinsic::tanh: {
5402 KnownFPClass KnownSrc;
5403 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5404 KnownSrc, Q, Depth + 1);
5405 Known = KnownFPClass::tanh(KnownSrc);
5406 break;
5407 }
5408 case Intrinsic::asin: {
5409 KnownFPClass KnownSrc;
5410 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5411 KnownSrc, Q, Depth + 1);
5412 Known = KnownFPClass::asin(KnownSrc);
5413 break;
5414 }
5415 case Intrinsic::acos: {
5416 KnownFPClass KnownSrc;
5417 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5418 KnownSrc, Q, Depth + 1);
5419 Known = KnownFPClass::acos(KnownSrc);
5420 break;
5421 }
5422 case Intrinsic::atan: {
5423 KnownFPClass KnownSrc;
5424 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5425 KnownSrc, Q, Depth + 1);
5426 Known = KnownFPClass::atan(KnownSrc);
5427 break;
5428 }
5429 case Intrinsic::atan2: {
5430 KnownFPClass KnownLHS, KnownRHS;
5431 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5432 KnownLHS, Q, Depth + 1);
5433 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5434 KnownRHS, Q, Depth + 1);
5435 Known = KnownFPClass::atan2(KnownLHS, KnownRHS);
5436 break;
5437 }
5438 case Intrinsic::maxnum:
5439 case Intrinsic::minnum:
5440 case Intrinsic::minimum:
5441 case Intrinsic::maximum:
5442 case Intrinsic::minimumnum:
5443 case Intrinsic::maximumnum: {
5444 KnownFPClass KnownLHS, KnownRHS;
5445 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5446 KnownLHS, Q, Depth + 1);
5447 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5448 KnownRHS, Q, Depth + 1);
5449
5450 const Function *F = II->getFunction();
5451
5453 F ? F->getDenormalMode(
5454 II->getType()->getScalarType()->getFltSemantics())
5456
5457 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5458 Mode);
5459 break;
5460 }
5461 case Intrinsic::canonicalize: {
5462 KnownFPClass KnownSrc;
5463 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5464 KnownSrc, Q, Depth + 1);
5465
5466 const Function *F = II->getFunction();
5467 DenormalMode DenormMode =
5468 F ? F->getDenormalMode(
5469 II->getType()->getScalarType()->getFltSemantics())
5471 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5472 break;
5473 }
5474 case Intrinsic::vector_reduce_fmax:
5475 case Intrinsic::vector_reduce_fmin:
5476 case Intrinsic::vector_reduce_fmaximum:
5477 case Intrinsic::vector_reduce_fminimum: {
5478 // reduce min/max will choose an element from one of the vector elements,
5479 // so we can infer and class information that is common to all elements.
5480 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5481 InterestedClasses, Q, Depth + 1);
5482 // Can only propagate sign if output is never NaN.
5483 if (!Known.isKnownNeverNaN())
5484 Known.SignBit.reset();
5485 break;
5486 }
5487 // reverse preserves all characteristics of the input vec's element.
5488 case Intrinsic::vector_reverse:
5490 II->getArgOperand(0), DemandedElts.reverseBits(),
5491 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5492 break;
5493 case Intrinsic::trunc:
5494 case Intrinsic::floor:
5495 case Intrinsic::ceil:
5496 case Intrinsic::rint:
5497 case Intrinsic::nearbyint:
5498 case Intrinsic::round:
5499 case Intrinsic::roundeven: {
5500 KnownFPClass KnownSrc;
5501 FPClassTest InterestedSrcs = InterestedClasses;
5502 if (InterestedSrcs & fcPosFinite)
5503 InterestedSrcs |= fcPosFinite;
5504 if (InterestedSrcs & fcNegFinite)
5505 InterestedSrcs |= fcNegFinite;
5506 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5507 KnownSrc, Q, Depth + 1);
5508
5510 KnownSrc, IID == Intrinsic::trunc,
5511 V->getType()->getScalarType()->isMultiUnitFPType());
5512 break;
5513 }
5514 case Intrinsic::exp:
5515 case Intrinsic::exp2:
5516 case Intrinsic::exp10:
5517 case Intrinsic::amdgcn_exp2: {
5518 KnownFPClass KnownSrc;
5519 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5520 KnownSrc, Q, Depth + 1);
5521
5522 Known = KnownFPClass::exp(KnownSrc);
5523
5524 Type *EltTy = II->getType()->getScalarType();
5525 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5526 Known.knownNot(fcSubnormal);
5527
5528 break;
5529 }
5530 case Intrinsic::fptrunc_round: {
5531 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5532 Q, Depth);
5533 break;
5534 }
5535 case Intrinsic::log:
5536 case Intrinsic::log10:
5537 case Intrinsic::log2:
5538 case Intrinsic::experimental_constrained_log:
5539 case Intrinsic::experimental_constrained_log10:
5540 case Intrinsic::experimental_constrained_log2:
5541 case Intrinsic::amdgcn_log: {
5542 Type *EltTy = II->getType()->getScalarType();
5543
5544 // log(+inf) -> +inf
5545 // log([+-]0.0) -> -inf
5546 // log(-inf) -> nan
5547 // log(-x) -> nan
5548 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5549 FPClassTest InterestedSrcs = InterestedClasses;
5550 if ((InterestedClasses & fcNegInf) != fcNone)
5551 InterestedSrcs |= fcZero | fcSubnormal;
5552 if ((InterestedClasses & fcNan) != fcNone)
5553 InterestedSrcs |= fcNan | fcNegative;
5554
5555 KnownFPClass KnownSrc;
5556 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5557 KnownSrc, Q, Depth + 1);
5558
5559 const Function *F = II->getFunction();
5560 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5562 Known = KnownFPClass::log(KnownSrc, Mode);
5563 }
5564
5565 break;
5566 }
5567 case Intrinsic::pow: {
5568 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5569 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5570 if (!WantNaN && !WantNegative)
5571 break;
5572
5573 FPClassTest InterestedLHS = fcNone;
5574 FPClassTest InterestedRHS = fcNone;
5575 if (WantNaN) {
5576 // pow may return NaN if one of the arguments is NaN. NaN may also be
5577 // produced from a negative, non-zero finite base and a non-integer
5578 // exponent.
5579 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5580 InterestedRHS |= fcNan;
5581 }
5582 if (WantNegative) {
5583 // A negative value is returned when a negative base is raised to an odd
5584 // integer power. Only normal values can be odd integers.
5585 InterestedLHS |= fcNegative;
5586 InterestedRHS |= fcNormal;
5587 }
5588
5589 KnownFPClass KnownLHS;
5590 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5591 KnownLHS, Q, Depth + 1);
5592
5593 // If the LHS is unknown, then querying the RHS is only useful for rare
5594 // edge cases.
5595 if (KnownLHS.isUnknown())
5596 break;
5597
5598 KnownFPClass KnownRHS;
5599 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5600 KnownRHS, Q, Depth + 1);
5601 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5602 break;
5603 }
5604 case Intrinsic::powi: {
5605 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5606 break;
5607
5608 // The exponent is always a scalar, even when raising a vector to a power.
5609 const Value *Exp = II->getArgOperand(1);
5610 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5611 KnownBits ExponentKnownBits(BitWidth);
5612 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5613
5614 FPClassTest InterestedSrcs = fcNone;
5615 if (InterestedClasses & fcNan)
5616 InterestedSrcs |= fcNan;
5617 if (!ExponentKnownBits.isZero()) {
5618 if (InterestedClasses & fcInf)
5619 InterestedSrcs |= fcFinite | fcInf;
5620 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5621 InterestedSrcs |= fcNegative;
5622 }
5623
5624 KnownFPClass KnownSrc;
5625 if (InterestedSrcs != fcNone)
5626 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5627 KnownSrc, Q, Depth + 1);
5628
5629 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5630 break;
5631 }
5632 case Intrinsic::ldexp: {
5633 KnownFPClass KnownSrc;
5634 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5635 KnownSrc, Q, Depth + 1);
5636 // Can refine inf/zero handling based on the exponent operand.
5637 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5638
5639 const Value *ExpArg = II->getArgOperand(1);
5640 ConstantRange ExpKnownRange =
5641 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5642 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5643 : ConstantRange::getFull(
5644 ExpArg->getType()->getScalarSizeInBits());
5645
5646 const fltSemantics &Flt =
5647 II->getType()->getScalarType()->getFltSemantics();
5648
5649 const Function *F = II->getFunction();
5651 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5652
5653 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5654 ExpKnownRange.getSignedMax(), Flt, Mode);
5655 break;
5656 }
5657 case Intrinsic::arithmetic_fence: {
5658 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5659 Known, Q, Depth + 1);
5660 break;
5661 }
5662 case Intrinsic::experimental_constrained_sitofp:
5663 case Intrinsic::experimental_constrained_uitofp:
5664 // Cannot produce nan
5665 Known.knownNot(fcNan);
5666
5667 // sitofp and uitofp turn into +0.0 for zero.
5668 Known.knownNot(fcNegZero);
5669
5670 // Integers cannot be subnormal
5671 Known.knownNot(fcSubnormal);
5672
5673 if (IID == Intrinsic::experimental_constrained_uitofp)
5674 Known.signBitMustBeZero();
5675
5676 // TODO: Copy inf handling from instructions
5677 break;
5678
5679 case Intrinsic::amdgcn_fract: {
5680 Known.knownNot(fcInf);
5681
5682 if (InterestedClasses & fcNan) {
5683 KnownFPClass KnownSrc;
5684 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5685 InterestedClasses, KnownSrc, Q, Depth + 1);
5686
5687 if (KnownSrc.isKnownNeverInfOrNaN())
5688 Known.knownNot(fcNan);
5689 else if (KnownSrc.isKnownNever(fcSNan))
5690 Known.knownNot(fcSNan);
5691 }
5692
5693 break;
5694 }
5695 case Intrinsic::amdgcn_rcp: {
5696 KnownFPClass KnownSrc;
5697 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5698 KnownSrc, Q, Depth + 1);
5699
5700 Known.propagateNonNaN(KnownSrc);
5701
5702 Type *EltTy = II->getType()->getScalarType();
5703
5704 // f32 denormal always flushed.
5705 if (EltTy->isFloatTy()) {
5706 Known.knownNot(fcSubnormal);
5707 KnownSrc.knownNot(fcSubnormal);
5708 }
5709
5710 if (KnownSrc.isKnownNever(fcNegative))
5711 Known.knownNot(fcNegative);
5712 if (KnownSrc.isKnownNever(fcPositive))
5713 Known.knownNot(fcPositive);
5714
5715 if (const Function *F = II->getFunction()) {
5716 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5717 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5718 Known.knownNot(fcPosInf);
5719 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5720 Known.knownNot(fcNegInf);
5721 }
5722
5723 break;
5724 }
5725 case Intrinsic::amdgcn_rsq: {
5726 KnownFPClass KnownSrc;
5727 // The only negative value that can be returned is -inf for -0 inputs.
5729
5730 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5731 KnownSrc, Q, Depth + 1);
5732
5733 // Negative -> nan
5734 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5735 Known.knownNot(fcNan);
5736 else if (KnownSrc.isKnownNever(fcSNan))
5737 Known.knownNot(fcSNan);
5738
5739 // +inf -> +0
5740 if (KnownSrc.isKnownNeverPosInfinity())
5741 Known.knownNot(fcPosZero);
5742
5743 Type *EltTy = II->getType()->getScalarType();
5744
5745 // f32 denormal always flushed.
5746 if (EltTy->isFloatTy())
5747 Known.knownNot(fcPosSubnormal);
5748
5749 if (const Function *F = II->getFunction()) {
5750 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5751
5752 // -0 -> -inf
5753 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5754 Known.knownNot(fcNegInf);
5755
5756 // +0 -> +inf
5757 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5758 Known.knownNot(fcPosInf);
5759 }
5760
5761 break;
5762 }
5763 case Intrinsic::amdgcn_trig_preop: {
5764 // Always returns a value [0, 1)
5765 Known.knownNot(fcNan | fcInf | fcNegative);
5766 break;
5767 }
5768 case Intrinsic::convert_from_arbitrary_fp: {
5769 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5770 StringRef FormatStr = cast<MDString>(MD)->getString();
5771
5772 const fltSemantics *SrcSemantics =
5774 if (!SrcSemantics)
5775 break;
5776
5777 const fltSemantics DstSemantics =
5778 II->getType()->getScalarType()->getFltSemantics();
5779
5780 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5781 Known.knownNot(fcNan);
5782
5783 // fcInf can only be cleared if the source format has no Inf encoding
5784 // and the dst max exp can accommodate src max exp.
5785 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5786 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5787 APFloat::semanticsMaxExponent(DstSemantics))
5788 Known.knownNot(fcInf);
5789
5790 // Check and clear all neg flags for formats that do not have signed
5791 // representation.
5792 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5793 Known.knownNot(fcNegative);
5794
5795 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5796 // zero.
5797 if (!APFloat::semanticsHasZero(*SrcSemantics))
5798 Known.knownNot(fcZero);
5799 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5800 Known.knownNot(fcNegZero);
5801
5802 // If src lands normally in dest, the result can never be subnormal.
5803 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5804 Known.knownNot(fcSubnormal);
5805 break;
5806 }
5807 default:
5808 break;
5809 }
5810
5811 break;
5812 }
5813 case Instruction::FAdd:
5814 case Instruction::FSub: {
5815 KnownFPClass KnownLHS, KnownRHS;
5816 bool WantNegative =
5817 Op->getOpcode() == Instruction::FAdd &&
5818 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5819 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5820 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5821
5822 if (!WantNaN && !WantNegative && !WantNegZero)
5823 break;
5824
5825 FPClassTest InterestedSrcs = InterestedClasses;
5826 if (WantNegative)
5827 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5828 if (InterestedClasses & fcNan)
5829 InterestedSrcs |= fcInf;
5830 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5831 KnownRHS, Q, Depth + 1);
5832
5833 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5834 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5835 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5836 Depth + 1);
5837 if (Self)
5838 KnownLHS = KnownRHS;
5839
5840 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5841 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5842 WantNegZero || Opc == Instruction::FSub) {
5843
5844 // FIXME: Context function should always be passed in separately
5845 const Function *F = cast<Instruction>(Op)->getFunction();
5846 const fltSemantics &FltSem =
5847 Op->getType()->getScalarType()->getFltSemantics();
5849 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5850
5851 if (Self && Opc == Instruction::FAdd) {
5852 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5853 } else {
5854 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5855 // there's no point.
5856
5857 if (!Self) {
5858 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5859 KnownLHS, Q, Depth + 1);
5860 }
5861
5862 Known = Opc == Instruction::FAdd
5863 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5864 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5865 }
5866 }
5867
5868 break;
5869 }
5870 case Instruction::FMul: {
5871 const Function *F = cast<Instruction>(Op)->getFunction();
5873 F ? F->getDenormalMode(
5874 Op->getType()->getScalarType()->getFltSemantics())
5876
5877 Value *LHS = Op->getOperand(0);
5878 Value *RHS = Op->getOperand(1);
5879 // X * X is always non-negative or a NaN.
5880 // FIXME: Should check isGuaranteedNotToBeUndef
5881 if (LHS == RHS) {
5882 KnownFPClass KnownSrc;
5883 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5884 Depth + 1);
5885 Known = KnownFPClass::square(KnownSrc, Mode);
5886 break;
5887 }
5888
5889 KnownFPClass KnownLHS, KnownRHS;
5890
5891 const APFloat *CRHS;
5892 if (match(RHS, m_APFloat(CRHS))) {
5893 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5894 Depth + 1);
5895 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5896 } else {
5897 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5898 Depth + 1);
5899 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5900 // additional not-nan if the addend is known-not negative infinity if the
5901 // multiply is known-not infinity.
5902
5903 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5904 Depth + 1);
5905 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5906 }
5907
5908 /// Propgate no-infs if the other source is known smaller than one, such
5909 /// that this cannot introduce overflow.
5910 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5911 Known.knownNot(fcInf);
5912 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5913 Known.knownNot(fcInf);
5914
5915 break;
5916 }
5917 case Instruction::FDiv:
5918 case Instruction::FRem: {
5919 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5920
5921 if (Op->getOpcode() == Instruction::FRem)
5922 Known.knownNot(fcInf);
5923
5924 if (Op->getOperand(0) == Op->getOperand(1) &&
5925 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5926 if (Op->getOpcode() == Instruction::FDiv) {
5927 // X / X is always exactly 1.0 or a NaN.
5928 Known.KnownFPClasses = fcNan | fcPosNormal;
5929 } else {
5930 // X % X is always exactly [+-]0.0 or a NaN.
5931 Known.KnownFPClasses = fcNan | fcZero;
5932 }
5933
5934 if (!WantNan)
5935 break;
5936
5937 KnownFPClass KnownSrc;
5938 computeKnownFPClass(Op->getOperand(0), DemandedElts,
5939 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
5940 Depth + 1);
5941 const Function *F = cast<Instruction>(Op)->getFunction();
5942 const fltSemantics &FltSem =
5943 Op->getType()->getScalarType()->getFltSemantics();
5944
5946 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5947
5948 Known = Op->getOpcode() == Instruction::FDiv
5949 ? KnownFPClass::fdiv_self(KnownSrc, Mode)
5950 : KnownFPClass::frem_self(KnownSrc, Mode);
5951 break;
5952 }
5953
5954 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5955 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
5956 if (!WantNan && !WantNegative && !WantPositive)
5957 break;
5958
5959 KnownFPClass KnownLHS, KnownRHS;
5960 const bool IsFDiv = Opc == Instruction::FDiv;
5961 FPClassTest InterestedRHS =
5962 IsFDiv ? fcAllFlags : fcNan | fcInf | fcZero | fcNegative;
5963
5964 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
5965 KnownRHS, Q, Depth + 1);
5966
5967 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN();
5968 if (IsFDiv) {
5969 KnowSomethingUseful |=
5972 } else {
5973 KnowSomethingUseful |= KnownRHS.isKnownNever(fcNegative) ||
5974 KnownRHS.isKnownNever(fcPositive);
5975 }
5976
5977 if (KnowSomethingUseful || (!IsFDiv && WantPositive)) {
5978 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
5979 Q, Depth + 1);
5980 }
5981
5982 const Function *F = cast<Instruction>(Op)->getFunction();
5983 const fltSemantics &FltSem =
5984 Op->getType()->getScalarType()->getFltSemantics();
5985
5986 if (IsFDiv) {
5988 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5989 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
5990 } else {
5991 // Inf REM x and x REM 0 produce NaN.
5992 if (KnownLHS.isKnownNeverNaN() && KnownRHS.isKnownNeverNaN() &&
5993 KnownLHS.isKnownNeverInfinity() && F &&
5994 KnownRHS.isKnownNeverLogicalZero(F->getDenormalMode(FltSem))) {
5995 Known.knownNot(fcNan);
5996 }
5997
5998 // The sign for frem is the same as the first operand.
5999 if (KnownLHS.cannotBeOrderedLessThanZero())
6001 if (KnownLHS.cannotBeOrderedGreaterThanZero())
6003
6004 // See if we can be more aggressive about the sign of 0.
6005 if (KnownLHS.isKnownNever(fcNegative))
6006 Known.knownNot(fcNegative);
6007 if (KnownLHS.isKnownNever(fcPositive))
6008 Known.knownNot(fcPositive);
6009 }
6010
6011 break;
6012 }
6013 case Instruction::FPExt: {
6014 KnownFPClass KnownSrc;
6015 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6016 KnownSrc, Q, Depth + 1);
6017
6018 const fltSemantics &DstTy =
6019 Op->getType()->getScalarType()->getFltSemantics();
6020 const fltSemantics &SrcTy =
6021 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6022
6023 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6024 break;
6025 }
6026 case Instruction::FPTrunc: {
6027 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6028 Depth);
6029 break;
6030 }
6031 case Instruction::SIToFP:
6032 case Instruction::UIToFP: {
6033 // Cannot produce nan
6034 Known.knownNot(fcNan);
6035
6036 // Integers cannot be subnormal
6037 Known.knownNot(fcSubnormal);
6038
6039 // sitofp and uitofp turn into +0.0 for zero.
6040 Known.knownNot(fcNegZero);
6041
6042 // UIToFP is always non-negative regardless of known bits.
6043 if (Op->getOpcode() == Instruction::UIToFP)
6044 Known.signBitMustBeZero();
6045
6046 // Only compute known bits if we can learn something useful from them.
6047 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6048 break;
6049
6050 KnownBits IntKnown =
6051 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6052
6053 // If the integer is non-zero, the result cannot be +0.0
6054 if (IntKnown.isNonZero())
6055 Known.knownNot(fcPosZero);
6056
6057 if (Op->getOpcode() == Instruction::SIToFP) {
6058 // If the signed integer is known non-negative, the result is
6059 // non-negative. If the signed integer is known negative, the result is
6060 // negative.
6061 if (IntKnown.isNonNegative()) {
6062 Known.signBitMustBeZero();
6063 } else if (IntKnown.isNegative()) {
6064 Known.signBitMustBeOne();
6065 }
6066 }
6067
6068 // Guard kept for ilogb()
6069 if (InterestedClasses & fcInf) {
6070 // Get width of largest magnitude integer known.
6071 // This still works for a signed minimum value because the largest FP
6072 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6073 int IntSize = IntKnown.getBitWidth();
6074 if (Op->getOpcode() == Instruction::UIToFP)
6075 IntSize -= IntKnown.countMinLeadingZeros();
6076 else if (Op->getOpcode() == Instruction::SIToFP)
6077 IntSize -= IntKnown.countMinSignBits();
6078
6079 // If the exponent of the largest finite FP value can hold the largest
6080 // integer, the result of the cast must be finite.
6081 Type *FPTy = Op->getType()->getScalarType();
6082 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6083 Known.knownNot(fcInf);
6084 }
6085
6086 break;
6087 }
6088 case Instruction::ExtractElement: {
6089 // Look through extract element. If the index is non-constant or
6090 // out-of-range demand all elements, otherwise just the extracted element.
6091 const Value *Vec = Op->getOperand(0);
6092
6093 APInt DemandedVecElts;
6094 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6095 unsigned NumElts = VecTy->getNumElements();
6096 DemandedVecElts = APInt::getAllOnes(NumElts);
6097 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6098 if (CIdx && CIdx->getValue().ult(NumElts))
6099 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6100 } else {
6101 DemandedVecElts = APInt(1, 1);
6102 }
6103
6104 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6105 Q, Depth + 1);
6106 }
6107 case Instruction::InsertElement: {
6108 if (isa<ScalableVectorType>(Op->getType()))
6109 return;
6110
6111 const Value *Vec = Op->getOperand(0);
6112 const Value *Elt = Op->getOperand(1);
6113 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6114 unsigned NumElts = DemandedElts.getBitWidth();
6115 APInt DemandedVecElts = DemandedElts;
6116 bool NeedsElt = true;
6117 // If we know the index we are inserting to, clear it from Vec check.
6118 if (CIdx && CIdx->getValue().ult(NumElts)) {
6119 DemandedVecElts.clearBit(CIdx->getZExtValue());
6120 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6121 }
6122
6123 // Do we demand the inserted element?
6124 if (NeedsElt) {
6125 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6126 // If we don't know any bits, early out.
6127 if (Known.isUnknown())
6128 break;
6129 } else {
6130 Known.KnownFPClasses = fcNone;
6131 }
6132
6133 // Do we need anymore elements from Vec?
6134 if (!DemandedVecElts.isZero()) {
6135 KnownFPClass Known2;
6136 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6137 Depth + 1);
6138 Known |= Known2;
6139 }
6140
6141 break;
6142 }
6143 case Instruction::ShuffleVector: {
6144 // Handle vector splat idiom
6145 if (Value *Splat = getSplatValue(V)) {
6146 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6147 break;
6148 }
6149
6150 // For undef elements, we don't know anything about the common state of
6151 // the shuffle result.
6152 APInt DemandedLHS, DemandedRHS;
6153 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6154 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6155 return;
6156
6157 if (!!DemandedLHS) {
6158 const Value *LHS = Shuf->getOperand(0);
6159 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6160 Depth + 1);
6161
6162 // If we don't know any bits, early out.
6163 if (Known.isUnknown())
6164 break;
6165 } else {
6166 Known.KnownFPClasses = fcNone;
6167 }
6168
6169 if (!!DemandedRHS) {
6170 KnownFPClass Known2;
6171 const Value *RHS = Shuf->getOperand(1);
6172 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6173 Depth + 1);
6174 Known |= Known2;
6175 }
6176
6177 break;
6178 }
6179 case Instruction::ExtractValue: {
6180 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6181 ArrayRef<unsigned> Indices = Extract->getIndices();
6182 const Value *Src = Extract->getAggregateOperand();
6183 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6184 Indices[0] == 0) {
6185 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6186 switch (II->getIntrinsicID()) {
6187 case Intrinsic::frexp: {
6188 Known.knownNot(fcSubnormal);
6189
6190 KnownFPClass KnownSrc;
6191 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6192 InterestedClasses, KnownSrc, Q, Depth + 1);
6193
6194 const Function *F = cast<Instruction>(Op)->getFunction();
6195 const fltSemantics &FltSem =
6196 Op->getType()->getScalarType()->getFltSemantics();
6197
6199 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6200 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6201 return;
6202 }
6203 default:
6204 break;
6205 }
6206 }
6207 }
6208
6209 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6210 Depth + 1);
6211 break;
6212 }
6213 case Instruction::PHI: {
6214 const PHINode *P = cast<PHINode>(Op);
6215 // Unreachable blocks may have zero-operand PHI nodes.
6216 if (P->getNumIncomingValues() == 0)
6217 break;
6218
6219 // Otherwise take the unions of the known bit sets of the operands,
6220 // taking conservative care to avoid excessive recursion.
6221 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6222
6223 if (Depth < PhiRecursionLimit) {
6224 // Skip if every incoming value references to ourself.
6225 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6226 break;
6227
6228 bool First = true;
6229
6230 for (const Use &U : P->operands()) {
6231 Value *IncValue;
6232 Instruction *CxtI;
6233 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6234 // Skip direct self references.
6235 if (IncValue == P)
6236 continue;
6237
6238 KnownFPClass KnownSrc;
6239 // Recurse, but cap the recursion to two levels, because we don't want
6240 // to waste time spinning around in loops. We need at least depth 2 to
6241 // detect known sign bits.
6242 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6244 PhiRecursionLimit);
6245
6246 if (First) {
6247 Known = KnownSrc;
6248 First = false;
6249 } else {
6250 Known |= KnownSrc;
6251 }
6252
6253 if (Known.KnownFPClasses == fcAllFlags)
6254 break;
6255 }
6256 }
6257
6258 // Look for the case of a for loop which has a positive
6259 // initial value and is incremented by a squared value.
6260 // This will propagate sign information out of such loops.
6261 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6262 break;
6263 for (unsigned I = 0; I < 2; I++) {
6264 Value *RecurValue = P->getIncomingValue(1 - I);
6266 if (!II)
6267 continue;
6268 Value *R, *L, *Init;
6269 PHINode *PN;
6271 PN == P) {
6272 switch (II->getIntrinsicID()) {
6273 case Intrinsic::fma:
6274 case Intrinsic::fmuladd: {
6275 KnownFPClass KnownStart;
6276 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6277 Q, Depth + 1);
6278 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6279 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6281 break;
6282 }
6283 }
6284 }
6285 }
6286 break;
6287 }
6288 case Instruction::BitCast: {
6289 const Value *Src;
6290 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6291 !Src->getType()->isIntOrIntVectorTy())
6292 break;
6293
6294 const Type *Ty = Op->getType();
6295
6296 Value *CastLHS, *CastRHS;
6297
6298 // Match bitcast(umax(bitcast(a), bitcast(b)))
6299 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6300 m_BitCast(m_Value(CastRHS)))) &&
6301 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6302 KnownFPClass KnownLHS, KnownRHS;
6303 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6304 Depth + 1);
6305 if (!KnownRHS.isUnknown()) {
6306 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6307 Q, Depth + 1);
6308 Known = KnownLHS | KnownRHS;
6309 }
6310
6311 return;
6312 }
6313
6314 const Type *EltTy = Ty->getScalarType();
6315 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6316 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6317
6319 break;
6320 }
6321 default:
6322 break;
6323 }
6324}
6325
6327 const APInt &DemandedElts,
6328 FPClassTest InterestedClasses,
6329 const SimplifyQuery &SQ,
6330 unsigned Depth) {
6331 KnownFPClass KnownClasses;
6332 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6333 Depth);
6334 return KnownClasses;
6335}
6336
6338 FPClassTest InterestedClasses,
6339 const SimplifyQuery &SQ,
6340 unsigned Depth) {
6342 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6343 return Known;
6344}
6345
6347 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6348 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6349 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6350 return computeKnownFPClass(V, InterestedClasses,
6351 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6352 Depth);
6353}
6354
6356llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6357 FastMathFlags FMF, FPClassTest InterestedClasses,
6358 const SimplifyQuery &SQ, unsigned Depth) {
6359 if (FMF.noNaNs())
6360 InterestedClasses &= ~fcNan;
6361 if (FMF.noInfs())
6362 InterestedClasses &= ~fcInf;
6363
6364 KnownFPClass Result =
6365 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6366
6367 if (FMF.noNaNs())
6368 Result.KnownFPClasses &= ~fcNan;
6369 if (FMF.noInfs())
6370 Result.KnownFPClasses &= ~fcInf;
6371 return Result;
6372}
6373
6375 FPClassTest InterestedClasses,
6376 const SimplifyQuery &SQ,
6377 unsigned Depth) {
6378 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6379 APInt DemandedElts =
6380 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6381 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6382 Depth);
6383}
6384
6386 unsigned Depth) {
6388 return Known.isKnownNeverNegZero();
6389}
6390
6392 unsigned Depth) {
6395 return Known.cannotBeOrderedLessThanZero();
6396}
6397
6399 unsigned Depth) {
6401 return Known.isKnownNeverInfinity();
6402}
6403
6404/// Return true if the floating-point value can never contain a NaN or infinity.
6406 unsigned Depth) {
6408 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6409}
6410
6411/// Return true if the floating-point scalar value is not a NaN or if the
6412/// floating-point vector value has no NaN elements. Return false if a value
6413/// could ever be NaN.
6415 unsigned Depth) {
6417 return Known.isKnownNeverNaN();
6418}
6419
6420/// Return false if we can prove that the specified FP value's sign bit is 0.
6421/// Return true if we can prove that the specified FP value's sign bit is 1.
6422/// Otherwise return std::nullopt.
6423std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6424 const SimplifyQuery &SQ,
6425 unsigned Depth) {
6427 return Known.SignBit;
6428}
6429
6431 auto *User = cast<Instruction>(U.getUser());
6432 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6433 if (FPOp->hasNoSignedZeros())
6434 return true;
6435 }
6436
6437 switch (User->getOpcode()) {
6438 case Instruction::FPToSI:
6439 case Instruction::FPToUI:
6440 return true;
6441 case Instruction::FCmp:
6442 // fcmp treats both positive and negative zero as equal.
6443 return true;
6444 case Instruction::Call:
6445 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6446 switch (II->getIntrinsicID()) {
6447 case Intrinsic::fabs:
6448 return true;
6449 case Intrinsic::copysign:
6450 return U.getOperandNo() == 0;
6451 case Intrinsic::is_fpclass: {
6452 auto Test =
6453 static_cast<FPClassTest>(
6454 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6457 }
6458 default:
6459 return false;
6460 }
6461 }
6462 return false;
6463 default:
6464 return false;
6465 }
6466}
6467
6469 auto *User = cast<Instruction>(U.getUser());
6470 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6471 if (FPOp->hasNoNaNs())
6472 return true;
6473 }
6474
6475 switch (User->getOpcode()) {
6476 case Instruction::FPToSI:
6477 case Instruction::FPToUI:
6478 return true;
6479 // Proper FP math operations ignore the sign bit of NaN.
6480 case Instruction::FAdd:
6481 case Instruction::FSub:
6482 case Instruction::FMul:
6483 case Instruction::FDiv:
6484 case Instruction::FRem:
6485 case Instruction::FPTrunc:
6486 case Instruction::FPExt:
6487 case Instruction::FCmp:
6488 return true;
6489 // Bitwise FP operations should preserve the sign bit of NaN.
6490 case Instruction::FNeg:
6491 case Instruction::Select:
6492 case Instruction::PHI:
6493 return false;
6494 case Instruction::Ret:
6495 return User->getFunction()->getAttributes().getRetNoFPClass() &
6497 case Instruction::Call:
6498 case Instruction::Invoke: {
6499 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6500 switch (II->getIntrinsicID()) {
6501 case Intrinsic::fabs:
6502 return true;
6503 case Intrinsic::copysign:
6504 return U.getOperandNo() == 0;
6505 // Other proper FP math intrinsics ignore the sign bit of NaN.
6506 case Intrinsic::maxnum:
6507 case Intrinsic::minnum:
6508 case Intrinsic::maximum:
6509 case Intrinsic::minimum:
6510 case Intrinsic::maximumnum:
6511 case Intrinsic::minimumnum:
6512 case Intrinsic::canonicalize:
6513 case Intrinsic::fma:
6514 case Intrinsic::fmuladd:
6515 case Intrinsic::sqrt:
6516 case Intrinsic::pow:
6517 case Intrinsic::powi:
6518 case Intrinsic::fptoui_sat:
6519 case Intrinsic::fptosi_sat:
6520 case Intrinsic::is_fpclass:
6521 return true;
6522 default:
6523 return false;
6524 }
6525 }
6526
6527 FPClassTest NoFPClass =
6528 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6529 return NoFPClass & FPClassTest::fcNan;
6530 }
6531 default:
6532 return false;
6533 }
6534}
6535
6537 FastMathFlags FMF) {
6538 if (isa<PoisonValue>(V))
6539 return true;
6540 if (isa<UndefValue>(V))
6541 return false;
6542
6543 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6544 return true;
6545
6547 if (!I)
6548 return false;
6549
6550 switch (I->getOpcode()) {
6551 case Instruction::SIToFP:
6552 case Instruction::UIToFP:
6553 // TODO: Could check nofpclass(inf) on incoming argument
6554 if (FMF.noInfs())
6555 return true;
6556
6557 // Need to check int size cannot produce infinity, which computeKnownFPClass
6558 // knows how to do already.
6559 return isKnownNeverInfinity(I, SQ);
6560 case Instruction::Call: {
6561 const CallInst *CI = cast<CallInst>(I);
6562 switch (CI->getIntrinsicID()) {
6563 case Intrinsic::trunc:
6564 case Intrinsic::floor:
6565 case Intrinsic::ceil:
6566 case Intrinsic::rint:
6567 case Intrinsic::nearbyint:
6568 case Intrinsic::round:
6569 case Intrinsic::roundeven:
6570 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6571 default:
6572 break;
6573 }
6574
6575 break;
6576 }
6577 default:
6578 break;
6579 }
6580
6581 return false;
6582}
6583
6585
6586 // All byte-wide stores are splatable, even of arbitrary variables.
6587 if (V->getType()->isIntegerTy(8))
6588 return V;
6589
6590 LLVMContext &Ctx = V->getContext();
6591
6592 // Undef don't care.
6593 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6594 if (isa<UndefValue>(V))
6595 return UndefInt8;
6596
6597 // Return poison for zero-sized type.
6598 if (DL.getTypeStoreSize(V->getType()).isZero())
6599 return PoisonValue::get(Type::getInt8Ty(Ctx));
6600
6602 if (!C) {
6603 // Conceptually, we could handle things like:
6604 // %a = zext i8 %X to i16
6605 // %b = shl i16 %a, 8
6606 // %c = or i16 %a, %b
6607 // but until there is an example that actually needs this, it doesn't seem
6608 // worth worrying about.
6609 return nullptr;
6610 }
6611
6612 // Handle 'null' ConstantArrayZero etc.
6613 if (C->isNullValue())
6615
6616 // Constant floating-point values can be handled as integer values if the
6617 // corresponding integer value is "byteable". An important case is 0.0.
6618 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6619 Type *ScalarTy = CFP->getType()->getScalarType();
6620 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6621 return isBytewiseValue(
6622 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6623
6624 // Don't handle long double formats, which have strange constraints.
6625 return nullptr;
6626 }
6627
6628 // We can handle constant integers that are multiple of 8 bits.
6629 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6630 if (CI->getBitWidth() % 8 == 0) {
6631 if (!CI->getValue().isSplat(8))
6632 return nullptr;
6633 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6634 }
6635 }
6636
6637 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6638 if (CE->getOpcode() == Instruction::IntToPtr) {
6639 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6640 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6642 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6643 return isBytewiseValue(Op, DL);
6644 }
6645 }
6646 }
6647
6648 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6649 if (LHS == RHS)
6650 return LHS;
6651 if (!LHS || !RHS)
6652 return nullptr;
6653 if (LHS == UndefInt8)
6654 return RHS;
6655 if (RHS == UndefInt8)
6656 return LHS;
6657 return nullptr;
6658 };
6659
6661 Value *Val = UndefInt8;
6662 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6663 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6664 return nullptr;
6665 return Val;
6666 }
6667
6669 Value *Val = UndefInt8;
6670 for (Value *Op : C->operands())
6671 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6672 return nullptr;
6673 return Val;
6674 }
6675
6676 // Don't try to handle the handful of other constants.
6677 return nullptr;
6678}
6679
6680// This is the recursive version of BuildSubAggregate. It takes a few different
6681// arguments. Idxs is the index within the nested struct From that we are
6682// looking at now (which is of type IndexedType). IdxSkip is the number of
6683// indices from Idxs that should be left out when inserting into the resulting
6684// struct. To is the result struct built so far, new insertvalue instructions
6685// build on that.
6686static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6688 unsigned IdxSkip,
6689 BasicBlock::iterator InsertBefore) {
6690 StructType *STy = dyn_cast<StructType>(IndexedType);
6691 if (STy) {
6692 // Save the original To argument so we can modify it
6693 Value *OrigTo = To;
6694 // General case, the type indexed by Idxs is a struct
6695 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6696 // Process each struct element recursively
6697 Idxs.push_back(i);
6698 Value *PrevTo = To;
6699 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6700 InsertBefore);
6701 Idxs.pop_back();
6702 if (!To) {
6703 // Couldn't find any inserted value for this index? Cleanup
6704 while (PrevTo != OrigTo) {
6706 PrevTo = Del->getAggregateOperand();
6707 Del->eraseFromParent();
6708 }
6709 // Stop processing elements
6710 break;
6711 }
6712 }
6713 // If we successfully found a value for each of our subaggregates
6714 if (To)
6715 return To;
6716 }
6717 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6718 // the struct's elements had a value that was inserted directly. In the latter
6719 // case, perhaps we can't determine each of the subelements individually, but
6720 // we might be able to find the complete struct somewhere.
6721
6722 // Find the value that is at that particular spot
6723 Value *V = FindInsertedValue(From, Idxs);
6724
6725 if (!V)
6726 return nullptr;
6727
6728 // Insert the value in the new (sub) aggregate
6729 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6730 InsertBefore);
6731}
6732
6733// This helper takes a nested struct and extracts a part of it (which is again a
6734// struct) into a new value. For example, given the struct:
6735// { a, { b, { c, d }, e } }
6736// and the indices "1, 1" this returns
6737// { c, d }.
6738//
6739// It does this by inserting an insertvalue for each element in the resulting
6740// struct, as opposed to just inserting a single struct. This will only work if
6741// each of the elements of the substruct are known (ie, inserted into From by an
6742// insertvalue instruction somewhere).
6743//
6744// All inserted insertvalue instructions are inserted before InsertBefore
6746 BasicBlock::iterator InsertBefore) {
6747 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6748 idx_range);
6749 Value *To = PoisonValue::get(IndexedType);
6750 SmallVector<unsigned, 10> Idxs(idx_range);
6751 unsigned IdxSkip = Idxs.size();
6752
6753 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6754}
6755
6756/// Given an aggregate and a sequence of indices, see if the scalar value
6757/// indexed is already around as a register, for example if it was inserted
6758/// directly into the aggregate.
6759///
6760/// If InsertBefore is not null, this function will duplicate (modified)
6761/// insertvalues when a part of a nested struct is extracted.
6762Value *
6764 std::optional<BasicBlock::iterator> InsertBefore) {
6765 // Nothing to index? Just return V then (this is useful at the end of our
6766 // recursion).
6767 if (idx_range.empty())
6768 return V;
6769 // We have indices, so V should have an indexable type.
6770 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6771 "Not looking at a struct or array?");
6772 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6773 "Invalid indices for type?");
6774
6775 if (Constant *C = dyn_cast<Constant>(V)) {
6776 C = C->getAggregateElement(idx_range[0]);
6777 if (!C) return nullptr;
6778 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6779 }
6780
6782 // Loop the indices for the insertvalue instruction in parallel with the
6783 // requested indices
6784 const unsigned *req_idx = idx_range.begin();
6785 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6786 i != e; ++i, ++req_idx) {
6787 if (req_idx == idx_range.end()) {
6788 // We can't handle this without inserting insertvalues
6789 if (!InsertBefore)
6790 return nullptr;
6791
6792 // The requested index identifies a part of a nested aggregate. Handle
6793 // this specially. For example,
6794 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6795 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6796 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6797 // This can be changed into
6798 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6799 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6800 // which allows the unused 0,0 element from the nested struct to be
6801 // removed.
6802 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6803 *InsertBefore);
6804 }
6805
6806 // This insert value inserts something else than what we are looking for.
6807 // See if the (aggregate) value inserted into has the value we are
6808 // looking for, then.
6809 if (*req_idx != *i)
6810 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6811 InsertBefore);
6812 }
6813 // If we end up here, the indices of the insertvalue match with those
6814 // requested (though possibly only partially). Now we recursively look at
6815 // the inserted value, passing any remaining indices.
6816 return FindInsertedValue(I->getInsertedValueOperand(),
6817 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6818 }
6819
6821 // If we're extracting a value from an aggregate that was extracted from
6822 // something else, we can extract from that something else directly instead.
6823 // However, we will need to chain I's indices with the requested indices.
6824
6825 // Calculate the number of indices required
6826 unsigned size = I->getNumIndices() + idx_range.size();
6827 // Allocate some space to put the new indices in
6829 Idxs.reserve(size);
6830 // Add indices from the extract value instruction
6831 Idxs.append(I->idx_begin(), I->idx_end());
6832
6833 // Add requested indices
6834 Idxs.append(idx_range.begin(), idx_range.end());
6835
6836 assert(Idxs.size() == size
6837 && "Number of indices added not correct?");
6838
6839 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6840 }
6841 // Otherwise, we don't know (such as, extracting from a function return value
6842 // or load instruction)
6843 return nullptr;
6844}
6845
6846// If V refers to an initialized global constant, set Slice either to
6847// its initializer if the size of its elements equals ElementSize, or,
6848// for ElementSize == 8, to its representation as an array of unsiged
6849// char. Return true on success.
6850// Offset is in the unit "nr of ElementSize sized elements".
6853 unsigned ElementSize, uint64_t Offset) {
6854 assert(V && "V should not be null.");
6855 assert((ElementSize % 8) == 0 &&
6856 "ElementSize expected to be a multiple of the size of a byte.");
6857 unsigned ElementSizeInBytes = ElementSize / 8;
6858
6859 // Drill down into the pointer expression V, ignoring any intervening
6860 // casts, and determine the identity of the object it references along
6861 // with the cumulative byte offset into it.
6862 const GlobalVariable *GV =
6864 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6865 // Fail if V is not based on constant global object.
6866 return false;
6867
6868 const DataLayout &DL = GV->getDataLayout();
6869 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6870
6871 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6872 /*AllowNonInbounds*/ true))
6873 // Fail if a constant offset could not be determined.
6874 return false;
6875
6876 uint64_t StartIdx = Off.getLimitedValue();
6877 if (StartIdx == UINT64_MAX)
6878 // Fail if the constant offset is excessive.
6879 return false;
6880
6881 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6882 // elements. Simply bail out if that isn't possible.
6883 if ((StartIdx % ElementSizeInBytes) != 0)
6884 return false;
6885
6886 Offset += StartIdx / ElementSizeInBytes;
6887 ConstantDataArray *Array = nullptr;
6888 ArrayType *ArrayTy = nullptr;
6889
6890 if (GV->getInitializer()->isNullValue()) {
6891 Type *GVTy = GV->getValueType();
6892 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6893 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6894
6895 Slice.Array = nullptr;
6896 Slice.Offset = 0;
6897 // Return an empty Slice for undersized constants to let callers
6898 // transform even undefined library calls into simpler, well-defined
6899 // expressions. This is preferable to making the calls although it
6900 // prevents sanitizers from detecting such calls.
6901 Slice.Length = Length < Offset ? 0 : Length - Offset;
6902 return true;
6903 }
6904
6905 auto *Init = const_cast<Constant *>(GV->getInitializer());
6906 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6907 Type *InitElTy = ArrayInit->getElementType();
6908 if (InitElTy->isIntegerTy(ElementSize)) {
6909 // If Init is an initializer for an array of the expected type
6910 // and size, use it as is.
6911 Array = ArrayInit;
6912 ArrayTy = ArrayInit->getType();
6913 }
6914 }
6915
6916 if (!Array) {
6917 if (ElementSize != 8)
6918 // TODO: Handle conversions to larger integral types.
6919 return false;
6920
6921 // Otherwise extract the portion of the initializer starting
6922 // at Offset as an array of bytes, and reset Offset.
6924 if (!Init)
6925 return false;
6926
6927 Offset = 0;
6929 ArrayTy = dyn_cast<ArrayType>(Init->getType());
6930 }
6931
6932 uint64_t NumElts = ArrayTy->getArrayNumElements();
6933 if (Offset > NumElts)
6934 return false;
6935
6936 Slice.Array = Array;
6937 Slice.Offset = Offset;
6938 Slice.Length = NumElts - Offset;
6939 return true;
6940}
6941
6942/// Extract bytes from the initializer of the constant array V, which need
6943/// not be a nul-terminated string. On success, store the bytes in Str and
6944/// return true. When TrimAtNul is set, Str will contain only the bytes up
6945/// to but not including the first nul. Return false on failure.
6947 bool TrimAtNul) {
6949 if (!getConstantDataArrayInfo(V, Slice, 8))
6950 return false;
6951
6952 if (Slice.Array == nullptr) {
6953 if (TrimAtNul) {
6954 // Return a nul-terminated string even for an empty Slice. This is
6955 // safe because all existing SimplifyLibcalls callers require string
6956 // arguments and the behavior of the functions they fold is undefined
6957 // otherwise. Folding the calls this way is preferable to making
6958 // the undefined library calls, even though it prevents sanitizers
6959 // from reporting such calls.
6960 Str = StringRef();
6961 return true;
6962 }
6963 if (Slice.Length == 1) {
6964 Str = StringRef("", 1);
6965 return true;
6966 }
6967 // We cannot instantiate a StringRef as we do not have an appropriate string
6968 // of 0s at hand.
6969 return false;
6970 }
6971
6972 // Start out with the entire array in the StringRef.
6973 Str = Slice.Array->getAsString();
6974 // Skip over 'offset' bytes.
6975 Str = Str.substr(Slice.Offset);
6976
6977 if (TrimAtNul) {
6978 // Trim off the \0 and anything after it. If the array is not nul
6979 // terminated, we just return the whole end of string. The client may know
6980 // some other way that the string is length-bound.
6981 Str = Str.substr(0, Str.find('\0'));
6982 }
6983 return true;
6984}
6985
6986// These next two are very similar to the above, but also look through PHI
6987// nodes.
6988// TODO: See if we can integrate these two together.
6989
6990/// If we can compute the length of the string pointed to by
6991/// the specified pointer, return 'len+1'. If we can't, return 0.
6994 unsigned CharSize) {
6995 // Look through noop bitcast instructions.
6996 V = V->stripPointerCasts();
6997
6998 // If this is a PHI node, there are two cases: either we have already seen it
6999 // or we haven't.
7000 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7001 if (!PHIs.insert(PN).second)
7002 return ~0ULL; // already in the set.
7003
7004 // If it was new, see if all the input strings are the same length.
7005 uint64_t LenSoFar = ~0ULL;
7006 for (Value *IncValue : PN->incoming_values()) {
7007 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7008 if (Len == 0) return 0; // Unknown length -> unknown.
7009
7010 if (Len == ~0ULL) continue;
7011
7012 if (Len != LenSoFar && LenSoFar != ~0ULL)
7013 return 0; // Disagree -> unknown.
7014 LenSoFar = Len;
7015 }
7016
7017 // Success, all agree.
7018 return LenSoFar;
7019 }
7020
7021 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7022 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7023 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7024 if (Len1 == 0) return 0;
7025 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7026 if (Len2 == 0) return 0;
7027 if (Len1 == ~0ULL) return Len2;
7028 if (Len2 == ~0ULL) return Len1;
7029 if (Len1 != Len2) return 0;
7030 return Len1;
7031 }
7032
7033 // Otherwise, see if we can read the string.
7035 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7036 return 0;
7037
7038 if (Slice.Array == nullptr)
7039 // Zeroinitializer (including an empty one).
7040 return 1;
7041
7042 // Search for the first nul character. Return a conservative result even
7043 // when there is no nul. This is safe since otherwise the string function
7044 // being folded such as strlen is undefined, and can be preferable to
7045 // making the undefined library call.
7046 unsigned NullIndex = 0;
7047 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7048 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7049 break;
7050 }
7051
7052 return NullIndex + 1;
7053}
7054
7055/// If we can compute the length of the string pointed to by
7056/// the specified pointer, return 'len+1'. If we can't, return 0.
7057uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7058 if (!V->getType()->isPointerTy())
7059 return 0;
7060
7062 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7063 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7064 // an empty string as a length.
7065 return Len == ~0ULL ? 1 : Len;
7066}
7067
7068const Value *
7070 bool MustPreserveOffset) {
7071 assert(Call &&
7072 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7073 if (const Value *RV = Call->getReturnedArgOperand())
7074 return RV;
7075 // This can be used only as a aliasing property.
7077 Call, MustPreserveOffset))
7078 return Call->getArgOperand(0);
7079 return nullptr;
7080}
7081
7083 const CallBase *Call, bool MustPreserveOffset) {
7084 switch (Call->getIntrinsicID()) {
7085 case Intrinsic::launder_invariant_group:
7086 case Intrinsic::strip_invariant_group:
7087 case Intrinsic::aarch64_irg:
7088 case Intrinsic::aarch64_tagp:
7089 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7090 // input pointer (and thus preserves the byte offset, which is the property
7091 // the MustPreserveOffset flag selects). However, it will not necessarily
7092 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7093 // descriptor", which has "all loads return 0, all stores are dropped"
7094 // semantics. Given the context of this intrinsic list, no one should be
7095 // relying on such a strict bit-exact null mapping (and, at time of
7096 // writing, they are not), but we document this fact out of an abundance
7097 // of caution.
7098 case Intrinsic::amdgcn_make_buffer_rsrc:
7099 return true;
7100 case Intrinsic::ptrmask:
7101 return !MustPreserveOffset;
7102 case Intrinsic::threadlocal_address:
7103 // The underlying variable changes with thread ID. The Thread ID may change
7104 // at coroutine suspend points.
7105 return !Call->getParent()->getParent()->isPresplitCoroutine();
7106 default:
7107 return false;
7108 }
7109}
7110
7111/// \p PN defines a loop-variant pointer to an object. Check if the
7112/// previous iteration of the loop was referring to the same object as \p PN.
7114 const LoopInfo *LI) {
7115 // Find the loop-defined value.
7116 Loop *L = LI->getLoopFor(PN->getParent());
7117 if (PN->getNumIncomingValues() != 2)
7118 return true;
7119
7120 // Find the value from previous iteration.
7121 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7122 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7123 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7124 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7125 return true;
7126
7127 // If a new pointer is loaded in the loop, the pointer references a different
7128 // object in every iteration. E.g.:
7129 // for (i)
7130 // int *p = a[i];
7131 // ...
7132 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7133 if (!L->isLoopInvariant(Load->getPointerOperand()))
7134 return false;
7135 return true;
7136}
7137
7138const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7139 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7140 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7141 const Value *PtrOp = GEP->getPointerOperand();
7142 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7143 return V;
7144 V = PtrOp;
7145 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7146 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7147 Value *NewV = cast<Operator>(V)->getOperand(0);
7148 if (!NewV->getType()->isPointerTy())
7149 return V;
7150 V = NewV;
7151 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7152 if (GA->isInterposable())
7153 return V;
7154 V = GA->getAliasee();
7155 } else {
7156 if (auto *PHI = dyn_cast<PHINode>(V)) {
7157 // Look through single-arg phi nodes created by LCSSA.
7158 if (PHI->getNumIncomingValues() == 1) {
7159 V = PHI->getIncomingValue(0);
7160 continue;
7161 }
7162 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7163 // CaptureTracking can know about special capturing properties of some
7164 // intrinsics like launder.invariant.group, that can't be expressed with
7165 // the attributes, but have properties like returning aliasing pointer.
7166 // Because some analysis may assume that nocaptured pointer is not
7167 // returned from some special intrinsic (because function would have to
7168 // be marked with returns attribute), it is crucial to use this function
7169 // because it should be in sync with CaptureTracking. Not using it may
7170 // cause weird miscompilations where 2 aliasing pointers are assumed to
7171 // noalias.
7173 Call, /*MustPreserveOffset=*/false)) {
7174 V = RP;
7175 continue;
7176 }
7177 }
7178
7179 return V;
7180 }
7181 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7182 }
7183 return V;
7184}
7185
7188 const LoopInfo *LI, unsigned MaxLookup) {
7191 Worklist.push_back(V);
7192 do {
7193 const Value *P = Worklist.pop_back_val();
7194 P = getUnderlyingObject(P, MaxLookup);
7195
7196 if (!Visited.insert(P).second)
7197 continue;
7198
7199 if (auto *SI = dyn_cast<SelectInst>(P)) {
7200 Worklist.push_back(SI->getTrueValue());
7201 Worklist.push_back(SI->getFalseValue());
7202 continue;
7203 }
7204
7205 if (auto *PN = dyn_cast<PHINode>(P)) {
7206 // If this PHI changes the underlying object in every iteration of the
7207 // loop, don't look through it. Consider:
7208 // int **A;
7209 // for (i) {
7210 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7211 // Curr = A[i];
7212 // *Prev, *Curr;
7213 //
7214 // Prev is tracking Curr one iteration behind so they refer to different
7215 // underlying objects.
7216 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7218 append_range(Worklist, PN->incoming_values());
7219 else
7220 Objects.push_back(P);
7221 continue;
7222 }
7223
7224 Objects.push_back(P);
7225 } while (!Worklist.empty());
7226}
7227
7229 const unsigned MaxVisited = 8;
7230
7233 Worklist.push_back(V);
7234 const Value *Object = nullptr;
7235 // Used as fallback if we can't find a common underlying object through
7236 // recursion.
7237 bool First = true;
7238 const Value *FirstObject = getUnderlyingObject(V);
7239 do {
7240 const Value *P = Worklist.pop_back_val();
7241 P = First ? FirstObject : getUnderlyingObject(P);
7242 First = false;
7243
7244 if (!Visited.insert(P).second)
7245 continue;
7246
7247 if (Visited.size() == MaxVisited)
7248 return FirstObject;
7249
7250 if (auto *SI = dyn_cast<SelectInst>(P)) {
7251 Worklist.push_back(SI->getTrueValue());
7252 Worklist.push_back(SI->getFalseValue());
7253 continue;
7254 }
7255
7256 if (auto *PN = dyn_cast<PHINode>(P)) {
7257 append_range(Worklist, PN->incoming_values());
7258 continue;
7259 }
7260
7261 if (!Object)
7262 Object = P;
7263 else if (Object != P)
7264 return FirstObject;
7265 } while (!Worklist.empty());
7266
7267 return Object ? Object : FirstObject;
7268}
7269
7270/// This is the function that does the work of looking through basic
7271/// ptrtoint+arithmetic+inttoptr sequences.
7272static const Value *getUnderlyingObjectFromInt(const Value *V) {
7273 do {
7274 if (const Operator *U = dyn_cast<Operator>(V)) {
7275 // If we find a ptrtoint, we can transfer control back to the
7276 // regular getUnderlyingObjectFromInt.
7277 if (U->getOpcode() == Instruction::PtrToInt)
7278 return U->getOperand(0);
7279 // If we find an add of a constant, a multiplied value, or a phi, it's
7280 // likely that the other operand will lead us to the base
7281 // object. We don't have to worry about the case where the
7282 // object address is somehow being computed by the multiply,
7283 // because our callers only care when the result is an
7284 // identifiable object.
7285 if (U->getOpcode() != Instruction::Add ||
7286 (!isa<ConstantInt>(U->getOperand(1)) &&
7287 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7288 !isa<PHINode>(U->getOperand(1))))
7289 return V;
7290 V = U->getOperand(0);
7291 } else {
7292 return V;
7293 }
7294 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7295 } while (true);
7296}
7297
7298/// This is a wrapper around getUnderlyingObjects and adds support for basic
7299/// ptrtoint+arithmetic+inttoptr sequences.
7300/// It returns false if unidentified object is found in getUnderlyingObjects.
7302 SmallVectorImpl<Value *> &Objects) {
7304 SmallVector<const Value *, 4> Working(1, V);
7305 do {
7306 V = Working.pop_back_val();
7307
7309 getUnderlyingObjects(V, Objs);
7310
7311 for (const Value *V : Objs) {
7312 if (!Visited.insert(V).second)
7313 continue;
7314 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7315 const Value *O =
7316 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7317 if (O->getType()->isPointerTy()) {
7318 Working.push_back(O);
7319 continue;
7320 }
7321 }
7322 // If getUnderlyingObjects fails to find an identifiable object,
7323 // getUnderlyingObjectsForCodeGen also fails for safety.
7324 if (!isIdentifiedObject(V)) {
7325 Objects.clear();
7326 return false;
7327 }
7328 Objects.push_back(const_cast<Value *>(V));
7329 }
7330 } while (!Working.empty());
7331 return true;
7332}
7333
7335 AllocaInst *Result = nullptr;
7337 SmallVector<Value *, 4> Worklist;
7338
7339 auto AddWork = [&](Value *V) {
7340 if (Visited.insert(V).second)
7341 Worklist.push_back(V);
7342 };
7343
7344 AddWork(V);
7345 do {
7346 V = Worklist.pop_back_val();
7347 assert(Visited.count(V));
7348
7349 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7350 if (Result && Result != AI)
7351 return nullptr;
7352 Result = AI;
7353 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7354 AddWork(CI->getOperand(0));
7355 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7356 for (Value *IncValue : PN->incoming_values())
7357 AddWork(IncValue);
7358 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7359 AddWork(SI->getTrueValue());
7360 AddWork(SI->getFalseValue());
7362 if (OffsetZero && !GEP->hasAllZeroIndices())
7363 return nullptr;
7364 AddWork(GEP->getPointerOperand());
7365 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7366 Value *Returned = CB->getReturnedArgOperand();
7367 if (Returned)
7368 AddWork(Returned);
7369 else
7370 return nullptr;
7371 } else {
7372 return nullptr;
7373 }
7374 } while (!Worklist.empty());
7375
7376 return Result;
7377}
7378
7380 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7381 for (const User *U : V->users()) {
7383 if (!II)
7384 return false;
7385
7386 if (AllowLifetime && II->isLifetimeStartOrEnd())
7387 continue;
7388
7389 if (AllowDroppable && II->isDroppable())
7390 continue;
7391
7392 return false;
7393 }
7394 return true;
7395}
7396
7399 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7400}
7403 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7404}
7405
7407 if (auto *II = dyn_cast<IntrinsicInst>(I))
7408 return isTriviallyVectorizable(II->getIntrinsicID());
7409 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7410 return (!Shuffle || Shuffle->isSelect()) &&
7412}
7413
7415 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7416 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7417 bool IgnoreUBImplyingAttrs) {
7418 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7419 AC, DT, TLI, UseVariableInfo,
7420 IgnoreUBImplyingAttrs);
7421}
7422
7424 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7425 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7426 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7427#ifndef NDEBUG
7428 if (Inst->getOpcode() != Opcode) {
7429 // Check that the operands are actually compatible with the Opcode override.
7430 auto hasEqualReturnAndLeadingOperandTypes =
7431 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7432 if (Inst->getNumOperands() < NumLeadingOperands)
7433 return false;
7434 const Type *ExpectedType = Inst->getType();
7435 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7436 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7437 return false;
7438 return true;
7439 };
7441 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7442 assert(!Instruction::isUnaryOp(Opcode) ||
7443 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7444 }
7445#endif
7446
7447 switch (Opcode) {
7448 default:
7449 return true;
7450 case Instruction::UDiv:
7451 case Instruction::URem: {
7452 // x / y is undefined if y == 0.
7453 const APInt *V;
7454 if (match(Inst->getOperand(1), m_APInt(V)))
7455 return *V != 0;
7456 return false;
7457 }
7458 case Instruction::SDiv:
7459 case Instruction::SRem: {
7460 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7461 const APInt *Numerator, *Denominator;
7462 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7463 return false;
7464 // We cannot hoist this division if the denominator is 0.
7465 if (*Denominator == 0)
7466 return false;
7467 // It's safe to hoist if the denominator is not 0 or -1.
7468 if (!Denominator->isAllOnes())
7469 return true;
7470 // At this point we know that the denominator is -1. It is safe to hoist as
7471 // long we know that the numerator is not INT_MIN.
7472 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7473 return !Numerator->isMinSignedValue();
7474 // The numerator *might* be MinSignedValue.
7475 return false;
7476 }
7477 case Instruction::Load: {
7478 if (!UseVariableInfo)
7479 return false;
7480
7481 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7482 if (!LI)
7483 return false;
7484 if (mustSuppressSpeculation(*LI))
7485 return false;
7486 const DataLayout &DL = LI->getDataLayout();
7488 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7489 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7490 }
7491 case Instruction::Call: {
7492 auto *CI = dyn_cast<const CallInst>(Inst);
7493 if (!CI)
7494 return false;
7495 const Function *Callee = CI->getCalledFunction();
7496
7497 // The called function could have undefined behavior or side-effects, even
7498 // if marked readnone nounwind.
7499 if (!Callee || !Callee->isSpeculatable())
7500 return false;
7501 // Since the operands may be changed after hoisting, undefined behavior may
7502 // be triggered by some UB-implying attributes.
7503 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7504 }
7505 case Instruction::VAArg:
7506 case Instruction::Alloca:
7507 case Instruction::Invoke:
7508 case Instruction::CallBr:
7509 case Instruction::PHI:
7510 case Instruction::Store:
7511 case Instruction::Ret:
7512 case Instruction::UncondBr:
7513 case Instruction::CondBr:
7514 case Instruction::IndirectBr:
7515 case Instruction::Switch:
7516 case Instruction::Unreachable:
7517 case Instruction::Fence:
7518 case Instruction::AtomicRMW:
7519 case Instruction::AtomicCmpXchg:
7520 case Instruction::LandingPad:
7521 case Instruction::Resume:
7522 case Instruction::CatchSwitch:
7523 case Instruction::CatchPad:
7524 case Instruction::CatchRet:
7525 case Instruction::CleanupPad:
7526 case Instruction::CleanupRet:
7527 return false; // Misc instructions which have effects
7528 }
7529}
7530
7532 if (I.mayReadOrWriteMemory())
7533 // Memory dependency possible
7534 return true;
7536 // Can't move above a maythrow call or infinite loop. Or if an
7537 // inalloca alloca, above a stacksave call.
7538 return true;
7540 // 1) Can't reorder two inf-loop calls, even if readonly
7541 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7542 // safe to speculative execute. (Inverse of above)
7543 return true;
7544 return false;
7545}
7546
7547/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7561
7562/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7565 bool ForSigned,
7566 const SimplifyQuery &SQ) {
7567 ConstantRange CR1 =
7568 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7569 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7572 return CR1.intersectWith(CR2, RangeType);
7573}
7574
7576 const Value *RHS,
7577 const SimplifyQuery &SQ,
7578 bool IsNSW) {
7579 ConstantRange LHSRange =
7580 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7581 ConstantRange RHSRange =
7582 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7583
7584 // mul nsw of two non-negative numbers is also nuw.
7585 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7587
7588 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7589}
7590
7592 const Value *RHS,
7593 const SimplifyQuery &SQ) {
7594 // Multiplying n * m significant bits yields a result of n + m significant
7595 // bits. If the total number of significant bits does not exceed the
7596 // result bit width (minus 1), there is no overflow.
7597 // This means if we have enough leading sign bits in the operands
7598 // we can guarantee that the result does not overflow.
7599 // Ref: "Hacker's Delight" by Henry Warren
7600 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7601
7602 // Note that underestimating the number of sign bits gives a more
7603 // conservative answer.
7604 unsigned SignBits =
7605 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7606
7607 // First handle the easy case: if we have enough sign bits there's
7608 // definitely no overflow.
7609 if (SignBits > BitWidth + 1)
7611
7612 // There are two ambiguous cases where there can be no overflow:
7613 // SignBits == BitWidth + 1 and
7614 // SignBits == BitWidth
7615 // The second case is difficult to check, therefore we only handle the
7616 // first case.
7617 if (SignBits == BitWidth + 1) {
7618 // It overflows only when both arguments are negative and the true
7619 // product is exactly the minimum negative number.
7620 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7621 // For simplicity we just check if at least one side is not negative.
7622 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7623 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7624 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7626 }
7628}
7629
7632 const WithCache<const Value *> &RHS,
7633 const SimplifyQuery &SQ) {
7634 ConstantRange LHSRange =
7635 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7636 ConstantRange RHSRange =
7637 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7638 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7639}
7640
7641static OverflowResult
7644 const AddOperator *Add, const SimplifyQuery &SQ) {
7645 if (Add && Add->hasNoSignedWrap()) {
7647 }
7648
7649 // If LHS and RHS each have at least two sign bits, the addition will look
7650 // like
7651 //
7652 // XX..... +
7653 // YY.....
7654 //
7655 // If the carry into the most significant position is 0, X and Y can't both
7656 // be 1 and therefore the carry out of the addition is also 0.
7657 //
7658 // If the carry into the most significant position is 1, X and Y can't both
7659 // be 0 and therefore the carry out of the addition is also 1.
7660 //
7661 // Since the carry into the most significant position is always equal to
7662 // the carry out of the addition, there is no signed overflow.
7663 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7665
7666 ConstantRange LHSRange =
7667 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7668 ConstantRange RHSRange =
7669 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7670 OverflowResult OR =
7671 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7673 return OR;
7674
7675 // The remaining code needs Add to be available. Early returns if not so.
7676 if (!Add)
7678
7679 // If the sign of Add is the same as at least one of the operands, this add
7680 // CANNOT overflow. If this can be determined from the known bits of the
7681 // operands the above signedAddMayOverflow() check will have already done so.
7682 // The only other way to improve on the known bits is from an assumption, so
7683 // call computeKnownBitsFromContext() directly.
7684 bool LHSOrRHSKnownNonNegative =
7685 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7686 bool LHSOrRHSKnownNegative =
7687 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7688 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7689 KnownBits AddKnown(LHSRange.getBitWidth());
7690 computeKnownBitsFromContext(Add, AddKnown, SQ);
7691 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7692 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7694 }
7695
7697}
7698
7700 const Value *RHS,
7701 const SimplifyQuery &SQ) {
7702 // X - (X % ?)
7703 // The remainder of a value can't have greater magnitude than itself,
7704 // so the subtraction can't overflow.
7705
7706 // X - (X -nuw ?)
7707 // In the minimal case, this would simplify to "?", so there's no subtract
7708 // at all. But if this analysis is used to peek through casts, for example,
7709 // then determining no-overflow may allow other transforms.
7710
7711 // TODO: There are other patterns like this.
7712 // See simplifyICmpWithBinOpOnLHS() for candidates.
7713 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7714 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7715 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7717
7718 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7719 SQ.DL)) {
7720 if (*C)
7723 }
7724
7725 ConstantRange LHSRange =
7726 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7727 ConstantRange RHSRange =
7728 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7729 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7730}
7731
7733 const Value *RHS,
7734 const SimplifyQuery &SQ) {
7735 // X - (X % ?)
7736 // The remainder of a value can't have greater magnitude than itself,
7737 // so the subtraction can't overflow.
7738
7739 // X - (X -nsw ?)
7740 // In the minimal case, this would simplify to "?", so there's no subtract
7741 // at all. But if this analysis is used to peek through casts, for example,
7742 // then determining no-overflow may allow other transforms.
7743 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7744 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7745 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7747
7748 // If LHS and RHS each have at least two sign bits, the subtraction
7749 // cannot overflow.
7750 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7752
7753 ConstantRange LHSRange =
7754 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7755 ConstantRange RHSRange =
7756 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7757 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7758}
7759
7761 const DominatorTree &DT) {
7762 SmallVector<const CondBrInst *, 2> GuardingBranches;
7764
7765 for (const User *U : WO->users()) {
7766 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7767 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7768
7769 if (EVI->getIndices()[0] == 0)
7770 Results.push_back(EVI);
7771 else {
7772 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7773
7774 for (const auto *U : EVI->users())
7775 if (const auto *B = dyn_cast<CondBrInst>(U))
7776 GuardingBranches.push_back(B);
7777 }
7778 } else {
7779 // We are using the aggregate directly in a way we don't want to analyze
7780 // here (storing it to a global, say).
7781 return false;
7782 }
7783 }
7784
7785 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7786 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7787
7788 // Check if all users of the add are provably no-wrap.
7789 for (const auto *Result : Results) {
7790 // If the extractvalue itself is not executed on overflow, the we don't
7791 // need to check each use separately, since domination is transitive.
7792 if (DT.dominates(NoWrapEdge, Result->getParent()))
7793 continue;
7794
7795 for (const auto &RU : Result->uses())
7796 if (!DT.dominates(NoWrapEdge, RU))
7797 return false;
7798 }
7799
7800 return true;
7801 };
7802
7803 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7804}
7805
7806/// Shifts return poison if shiftwidth is larger than the bitwidth.
7807static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7808 auto *C = dyn_cast<Constant>(ShiftAmount);
7809 if (!C)
7810 return false;
7811
7812 // Shifts return poison if shiftwidth is larger than the bitwidth.
7814 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7815 unsigned NumElts = FVTy->getNumElements();
7816 for (unsigned i = 0; i < NumElts; ++i)
7817 ShiftAmounts.push_back(C->getAggregateElement(i));
7818 } else if (isa<ScalableVectorType>(C->getType()))
7819 return false; // Can't tell, just return false to be safe
7820 else
7821 ShiftAmounts.push_back(C);
7822
7823 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7824 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7825 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7826 });
7827
7828 return Safe;
7829}
7830
7832 bool ConsiderFlagsAndMetadata) {
7833
7834 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7835 Op->hasPoisonGeneratingAnnotations())
7836 return true;
7837
7838 unsigned Opcode = Op->getOpcode();
7839
7840 // Check whether opcode is a poison/undef-generating operation
7841 switch (Opcode) {
7842 case Instruction::Shl:
7843 case Instruction::AShr:
7844 case Instruction::LShr:
7845 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7846 case Instruction::FPToSI:
7847 case Instruction::FPToUI:
7848 // fptosi/ui yields poison if the resulting value does not fit in the
7849 // destination type.
7850 return true;
7851 case Instruction::Call:
7852 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7853 switch (II->getIntrinsicID()) {
7854 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7855 case Intrinsic::ctlz:
7856 case Intrinsic::cttz:
7857 case Intrinsic::abs:
7858 // We're not considering flags so it is safe to just return false.
7859 return false;
7860 case Intrinsic::sshl_sat:
7861 case Intrinsic::ushl_sat:
7862 if (!includesPoison(Kind) ||
7863 shiftAmountKnownInRange(II->getArgOperand(1)))
7864 return false;
7865 break;
7866 }
7867 }
7868 [[fallthrough]];
7869 case Instruction::CallBr:
7870 case Instruction::Invoke: {
7871 const auto *CB = cast<CallBase>(Op);
7872 return !CB->hasRetAttr(Attribute::NoUndef) &&
7873 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7874 }
7875 case Instruction::InsertElement:
7876 case Instruction::ExtractElement: {
7877 // If index exceeds the length of the vector, it returns poison
7878 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7879 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7880 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7881 if (includesPoison(Kind))
7882 return !Idx ||
7883 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7884 return false;
7885 }
7886 case Instruction::ShuffleVector: {
7888 ? cast<ConstantExpr>(Op)->getShuffleMask()
7889 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7890 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7891 }
7892 case Instruction::FNeg:
7893 case Instruction::PHI:
7894 case Instruction::Select:
7895 case Instruction::ExtractValue:
7896 case Instruction::InsertValue:
7897 case Instruction::Freeze:
7898 case Instruction::ICmp:
7899 case Instruction::FCmp:
7900 case Instruction::GetElementPtr:
7901 return false;
7902 case Instruction::AddrSpaceCast:
7903 return true;
7904 default: {
7905 const auto *CE = dyn_cast<ConstantExpr>(Op);
7906 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7907 return false;
7908 else if (Instruction::isBinaryOp(Opcode))
7909 return false;
7910 // Be conservative and return true.
7911 return true;
7912 }
7913 }
7914}
7915
7917 bool ConsiderFlagsAndMetadata) {
7918 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
7919 ConsiderFlagsAndMetadata);
7920}
7921
7922bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
7923 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
7924 ConsiderFlagsAndMetadata);
7925}
7926
7927static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
7928 unsigned Depth) {
7929 if (ValAssumedPoison == V)
7930 return true;
7931
7932 const unsigned MaxDepth = 2;
7933 if (Depth >= MaxDepth)
7934 return false;
7935
7936 if (const auto *I = dyn_cast<Instruction>(V)) {
7937 if (any_of(I->operands(), [=](const Use &Op) {
7938 return propagatesPoison(Op) &&
7939 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7940 }))
7941 return true;
7942
7943 // V = extractvalue V0, idx
7944 // V2 = extractvalue V0, idx2
7945 // V0's elements are all poison or not. (e.g., add_with_overflow)
7946 const WithOverflowInst *II;
7948 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
7949 llvm::is_contained(II->args(), ValAssumedPoison)))
7950 return true;
7951 }
7952 return false;
7953}
7954
7955static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
7956 unsigned Depth) {
7957 if (isGuaranteedNotToBePoison(ValAssumedPoison))
7958 return true;
7959
7960 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
7961 return true;
7962
7963 const unsigned MaxDepth = 2;
7964 if (Depth >= MaxDepth)
7965 return false;
7966
7967 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
7968 if (I && !canCreatePoison(cast<Operator>(I))) {
7969 return all_of(I->operands(), [=](const Value *Op) {
7970 return impliesPoison(Op, V, Depth + 1);
7971 });
7972 }
7973 return false;
7974}
7975
7976bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
7977 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
7978}
7979
7980static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
7981
7983 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
7984 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
7986 return false;
7987
7988 if (isa<MetadataAsValue>(V))
7989 return false;
7990
7991 if (const auto *A = dyn_cast<Argument>(V)) {
7992 if (A->hasAttribute(Attribute::NoUndef) ||
7993 A->hasAttribute(Attribute::Dereferenceable) ||
7994 A->hasAttribute(Attribute::DereferenceableOrNull))
7995 return true;
7996 }
7997
7998 if (auto *C = dyn_cast<Constant>(V)) {
7999 if (isa<PoisonValue>(C))
8000 return !includesPoison(Kind);
8001
8002 if (isa<UndefValue>(C))
8003 return !includesUndef(Kind);
8004
8007 return true;
8008
8009 if (C->getType()->isVectorTy()) {
8010 if (isa<ConstantExpr>(C)) {
8011 // Scalable vectors can use a ConstantExpr to build a splat.
8012 if (Constant *SplatC = C->getSplatValue())
8013 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8014 return true;
8015 } else {
8016 if (includesUndef(Kind) && C->containsUndefElement())
8017 return false;
8018 if (includesPoison(Kind) && C->containsPoisonElement())
8019 return false;
8020 return !C->containsConstantExpression();
8021 }
8022 }
8023 }
8024
8025 // Strip cast operations from a pointer value.
8026 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8027 // inbounds with zero offset. To guarantee that the result isn't poison, the
8028 // stripped pointer is checked as it has to be pointing into an allocated
8029 // object or be null `null` to ensure `inbounds` getelement pointers with a
8030 // zero offset could not produce poison.
8031 // It can strip off addrspacecast that do not change bit representation as
8032 // well. We believe that such addrspacecast is equivalent to no-op.
8033 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8034 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8035 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8036 return true;
8037
8038 auto OpCheck = [&](const Value *V) {
8039 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8040 };
8041
8042 if (auto *Opr = dyn_cast<Operator>(V)) {
8043 // If the value is a freeze instruction, then it can never
8044 // be undef or poison.
8045 if (isa<FreezeInst>(V))
8046 return true;
8047
8048 if (const auto *CB = dyn_cast<CallBase>(V)) {
8049 if (CB->hasRetAttr(Attribute::NoUndef) ||
8050 CB->hasRetAttr(Attribute::Dereferenceable) ||
8051 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8052 return true;
8053 }
8054
8055 if (!::canCreateUndefOrPoison(Opr, Kind,
8056 /*ConsiderFlagsAndMetadata=*/true)) {
8057 if (const auto *PN = dyn_cast<PHINode>(V)) {
8058 unsigned Num = PN->getNumIncomingValues();
8059 bool IsWellDefined = true;
8060 for (unsigned i = 0; i < Num; ++i) {
8061 if (PN == PN->getIncomingValue(i))
8062 continue;
8063 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8064 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8065 DT, Depth + 1, Kind)) {
8066 IsWellDefined = false;
8067 break;
8068 }
8069 }
8070 if (IsWellDefined)
8071 return true;
8072 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8073 : nullptr) {
8074 // For splats we only need to check the value being splatted.
8075 if (OpCheck(Splat))
8076 return true;
8077 } else if (all_of(Opr->operands(), OpCheck))
8078 return true;
8079 }
8080 }
8081
8082 if (auto *I = dyn_cast<LoadInst>(V))
8083 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8084 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8085 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8086 return true;
8087
8089 return true;
8090
8091 // CxtI may be null or a cloned instruction.
8092 if (!CtxI || !CtxI->getParent() || !DT)
8093 return false;
8094
8095 auto *DNode = DT->getNode(CtxI->getParent());
8096 if (!DNode)
8097 // Unreachable block
8098 return false;
8099
8100 // If V is used as a branch condition before reaching CtxI, V cannot be
8101 // undef or poison.
8102 // br V, BB1, BB2
8103 // BB1:
8104 // CtxI ; V cannot be undef or poison here
8105 auto *Dominator = DNode->getIDom();
8106 // This check is purely for compile time reasons: we can skip the IDom walk
8107 // if what we are checking for includes undef and the value is not an integer.
8108 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8109 while (Dominator) {
8110 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8111
8112 Value *Cond = nullptr;
8113 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8114 Cond = BI->getCondition();
8115 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8116 Cond = SI->getCondition();
8117 }
8118
8119 if (Cond) {
8120 if (Cond == V)
8121 return true;
8122 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8123 // For poison, we can analyze further
8124 auto *Opr = cast<Operator>(Cond);
8125 if (any_of(Opr->operands(), [V](const Use &U) {
8126 return V == U && propagatesPoison(U);
8127 }))
8128 return true;
8129 }
8130 }
8131
8132 Dominator = Dominator->getIDom();
8133 }
8134
8135 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8136 return true;
8137
8138 return false;
8139}
8140
8142 const Instruction *CtxI,
8143 const DominatorTree *DT,
8144 unsigned Depth) {
8145 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8147}
8148
8150 const Instruction *CtxI,
8151 const DominatorTree *DT, unsigned Depth) {
8152 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8154}
8155
8157 const Instruction *CtxI,
8158 const DominatorTree *DT, unsigned Depth) {
8159 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8161}
8162
8163/// Return true if undefined behavior would provably be executed on the path to
8164/// OnPathTo if Root produced a posion result. Note that this doesn't say
8165/// anything about whether OnPathTo is actually executed or whether Root is
8166/// actually poison. This can be used to assess whether a new use of Root can
8167/// be added at a location which is control equivalent with OnPathTo (such as
8168/// immediately before it) without introducing UB which didn't previously
8169/// exist. Note that a false result conveys no information.
8171 Instruction *OnPathTo,
8172 DominatorTree *DT) {
8173 // Basic approach is to assume Root is poison, propagate poison forward
8174 // through all users we can easily track, and then check whether any of those
8175 // users are provable UB and must execute before out exiting block might
8176 // exit.
8177
8178 // The set of all recursive users we've visited (which are assumed to all be
8179 // poison because of said visit)
8182 Worklist.push_back(Root);
8183 while (!Worklist.empty()) {
8184 const Instruction *I = Worklist.pop_back_val();
8185
8186 // If we know this must trigger UB on a path leading our target.
8187 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8188 return true;
8189
8190 // If we can't analyze propagation through this instruction, just skip it
8191 // and transitive users. Safe as false is a conservative result.
8192 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8193 return KnownPoison.contains(U) && propagatesPoison(U);
8194 }))
8195 continue;
8196
8197 if (KnownPoison.insert(I).second)
8198 for (const User *User : I->users())
8199 Worklist.push_back(cast<Instruction>(User));
8200 }
8201
8202 // Might be non-UB, or might have a path we couldn't prove must execute on
8203 // way to exiting bb.
8204 return false;
8205}
8206
8208 const SimplifyQuery &SQ) {
8209 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8210 Add, SQ);
8211}
8212
8215 const WithCache<const Value *> &RHS,
8216 const SimplifyQuery &SQ) {
8217 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8218}
8219
8221 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8222 // of time because it's possible for another thread to interfere with it for an
8223 // arbitrary length of time, but programs aren't allowed to rely on that.
8224
8225 // If there is no successor, then execution can't transfer to it.
8226 if (isa<ReturnInst>(I))
8227 return false;
8229 return false;
8230
8231 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8232 // Instruction::willReturn.
8233 //
8234 // FIXME: Move this check into Instruction::willReturn.
8235 if (isa<CatchPadInst>(I)) {
8236 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8237 default:
8238 // A catchpad may invoke exception object constructors and such, which
8239 // in some languages can be arbitrary code, so be conservative by default.
8240 return false;
8242 // For CoreCLR, it just involves a type test.
8243 return true;
8244 }
8245 }
8246
8247 // An instruction that returns without throwing must transfer control flow
8248 // to a successor.
8249 return !I->mayThrow() && I->willReturn();
8250}
8251
8253 // TODO: This is slightly conservative for invoke instruction since exiting
8254 // via an exception *is* normal control for them.
8255 for (const Instruction &I : *BB)
8257 return false;
8258 return true;
8259}
8260
8267
8270 assert(ScanLimit && "scan limit must be non-zero");
8271 for (const Instruction &I : Range) {
8272 if (--ScanLimit == 0)
8273 return false;
8275 return false;
8276 }
8277 return true;
8278}
8279
8281 const Loop *L) {
8282 // The loop header is guaranteed to be executed for every iteration.
8283 //
8284 // FIXME: Relax this constraint to cover all basic blocks that are
8285 // guaranteed to be executed at every iteration.
8286 if (I->getParent() != L->getHeader()) return false;
8287
8288 for (const Instruction &LI : *L->getHeader()) {
8289 if (&LI == I) return true;
8290 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8291 }
8292 llvm_unreachable("Instruction not contained in its own parent basic block.");
8293}
8294
8296 switch (IID) {
8297 // TODO: Add more intrinsics.
8298 case Intrinsic::sadd_with_overflow:
8299 case Intrinsic::ssub_with_overflow:
8300 case Intrinsic::smul_with_overflow:
8301 case Intrinsic::uadd_with_overflow:
8302 case Intrinsic::usub_with_overflow:
8303 case Intrinsic::umul_with_overflow:
8304 // If an input is a vector containing a poison element, the
8305 // two output vectors (calculated results, overflow bits)'
8306 // corresponding lanes are poison.
8307 return true;
8308 case Intrinsic::ctpop:
8309 case Intrinsic::ctlz:
8310 case Intrinsic::cttz:
8311 case Intrinsic::abs:
8312 case Intrinsic::smax:
8313 case Intrinsic::smin:
8314 case Intrinsic::umax:
8315 case Intrinsic::umin:
8316 case Intrinsic::scmp:
8317 case Intrinsic::is_fpclass:
8318 case Intrinsic::ptrmask:
8319 case Intrinsic::ucmp:
8320 case Intrinsic::bitreverse:
8321 case Intrinsic::bswap:
8322 case Intrinsic::sadd_sat:
8323 case Intrinsic::ssub_sat:
8324 case Intrinsic::sshl_sat:
8325 case Intrinsic::uadd_sat:
8326 case Intrinsic::usub_sat:
8327 case Intrinsic::ushl_sat:
8328 case Intrinsic::smul_fix:
8329 case Intrinsic::smul_fix_sat:
8330 case Intrinsic::umul_fix:
8331 case Intrinsic::umul_fix_sat:
8332 case Intrinsic::pow:
8333 case Intrinsic::powi:
8334 case Intrinsic::sin:
8335 case Intrinsic::sinh:
8336 case Intrinsic::cos:
8337 case Intrinsic::cosh:
8338 case Intrinsic::sincos:
8339 case Intrinsic::sincospi:
8340 case Intrinsic::tan:
8341 case Intrinsic::tanh:
8342 case Intrinsic::asin:
8343 case Intrinsic::acos:
8344 case Intrinsic::atan:
8345 case Intrinsic::atan2:
8346 case Intrinsic::canonicalize:
8347 case Intrinsic::sqrt:
8348 case Intrinsic::exp:
8349 case Intrinsic::exp2:
8350 case Intrinsic::exp10:
8351 case Intrinsic::log:
8352 case Intrinsic::log2:
8353 case Intrinsic::log10:
8354 case Intrinsic::modf:
8355 case Intrinsic::floor:
8356 case Intrinsic::ceil:
8357 case Intrinsic::trunc:
8358 case Intrinsic::rint:
8359 case Intrinsic::nearbyint:
8360 case Intrinsic::round:
8361 case Intrinsic::roundeven:
8362 case Intrinsic::lrint:
8363 case Intrinsic::llrint:
8364 case Intrinsic::fshl:
8365 case Intrinsic::fshr:
8366 case Intrinsic::frexp:
8367 case Intrinsic::get_active_lane_mask:
8368 return true;
8369 default:
8370 return false;
8371 }
8372}
8373
8374bool llvm::propagatesPoison(const Use &PoisonOp) {
8375 const Operator *I = cast<Operator>(PoisonOp.getUser());
8376 switch (I->getOpcode()) {
8377 case Instruction::Freeze:
8378 case Instruction::PHI:
8379 case Instruction::Invoke:
8380 return false;
8381 case Instruction::Select:
8382 return PoisonOp.getOperandNo() == 0;
8383 case Instruction::Call:
8384 if (auto *II = dyn_cast<IntrinsicInst>(I))
8385 return intrinsicPropagatesPoison(II->getIntrinsicID());
8386 return false;
8387 case Instruction::ICmp:
8388 case Instruction::FCmp:
8389 case Instruction::GetElementPtr:
8390 return true;
8391 default:
8393 return true;
8394
8395 // Be conservative and return false.
8396 return false;
8397 }
8398}
8399
8400/// Enumerates all operands of \p I that are guaranteed to not be undef or
8401/// poison. If the callback \p Handle returns true, stop processing and return
8402/// true. Otherwise, return false.
8403template <typename CallableT>
8405 const CallableT &Handle) {
8406 switch (I->getOpcode()) {
8407 case Instruction::Store:
8408 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8409 return true;
8410 break;
8411
8412 case Instruction::Load:
8413 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8414 return true;
8415 break;
8416
8417 // Since dereferenceable attribute imply noundef, atomic operations
8418 // also implicitly have noundef pointers too
8419 case Instruction::AtomicCmpXchg:
8421 return true;
8422 break;
8423
8424 case Instruction::AtomicRMW:
8425 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8426 return true;
8427 break;
8428
8429 case Instruction::Call:
8430 case Instruction::Invoke: {
8431 const CallBase *CB = cast<CallBase>(I);
8432 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8433 return true;
8434 for (unsigned i = 0; i < CB->arg_size(); ++i)
8435 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8436 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8437 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8438 Handle(CB->getArgOperand(i)))
8439 return true;
8440 break;
8441 }
8442 case Instruction::Ret:
8443 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8444 Handle(I->getOperand(0)))
8445 return true;
8446 break;
8447 case Instruction::Switch:
8448 if (Handle(cast<SwitchInst>(I)->getCondition()))
8449 return true;
8450 break;
8451 case Instruction::CondBr:
8452 if (Handle(cast<CondBrInst>(I)->getCondition()))
8453 return true;
8454 break;
8455 default:
8456 break;
8457 }
8458
8459 return false;
8460}
8461
8462/// Enumerates all operands of \p I that are guaranteed to not be poison.
8463template <typename CallableT>
8465 const CallableT &Handle) {
8466 if (handleGuaranteedWellDefinedOps(I, Handle))
8467 return true;
8468 switch (I->getOpcode()) {
8469 // Divisors of these operations are allowed to be partially undef.
8470 case Instruction::UDiv:
8471 case Instruction::SDiv:
8472 case Instruction::URem:
8473 case Instruction::SRem:
8474 return Handle(I->getOperand(1));
8475 default:
8476 return false;
8477 }
8478}
8479
8481 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8483 I, [&](const Value *V) { return KnownPoison.count(V); });
8484}
8485
8487 bool PoisonOnly) {
8488 // We currently only look for uses of values within the same basic
8489 // block, as that makes it easier to guarantee that the uses will be
8490 // executed given that Inst is executed.
8491 //
8492 // FIXME: Expand this to consider uses beyond the same basic block. To do
8493 // this, look out for the distinction between post-dominance and strong
8494 // post-dominance.
8495 const BasicBlock *BB = nullptr;
8497 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8498 BB = Inst->getParent();
8499 Begin = Inst->getIterator();
8500 Begin++;
8501 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8502 if (Arg->getParent()->isDeclaration())
8503 return false;
8504 BB = &Arg->getParent()->getEntryBlock();
8505 Begin = BB->begin();
8506 } else {
8507 return false;
8508 }
8509
8510 // Limit number of instructions we look at, to avoid scanning through large
8511 // blocks. The current limit is chosen arbitrarily.
8512 unsigned ScanLimit = 32;
8513 BasicBlock::const_iterator End = BB->end();
8514
8515 if (!PoisonOnly) {
8516 // Since undef does not propagate eagerly, be conservative & just check
8517 // whether a value is directly passed to an instruction that must take
8518 // well-defined operands.
8519
8520 for (const auto &I : make_range(Begin, End)) {
8521 if (--ScanLimit == 0)
8522 break;
8523
8524 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8525 return WellDefinedOp == V;
8526 }))
8527 return true;
8528
8530 break;
8531 }
8532 return false;
8533 }
8534
8535 // Set of instructions that we have proved will yield poison if Inst
8536 // does.
8537 SmallPtrSet<const Value *, 16> YieldsPoison;
8539
8540 YieldsPoison.insert(V);
8541 Visited.insert(BB);
8542
8543 while (true) {
8544 for (const auto &I : make_range(Begin, End)) {
8545 if (--ScanLimit == 0)
8546 return false;
8547 if (mustTriggerUB(&I, YieldsPoison))
8548 return true;
8550 return false;
8551
8552 // If an operand is poison and propagates it, mark I as yielding poison.
8553 for (const Use &Op : I.operands()) {
8554 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8555 YieldsPoison.insert(&I);
8556 break;
8557 }
8558 }
8559
8560 // Special handling for select, which returns poison if its operand 0 is
8561 // poison (handled in the loop above) *or* if both its true/false operands
8562 // are poison (handled here).
8563 if (I.getOpcode() == Instruction::Select &&
8564 YieldsPoison.count(I.getOperand(1)) &&
8565 YieldsPoison.count(I.getOperand(2))) {
8566 YieldsPoison.insert(&I);
8567 }
8568 }
8569
8570 BB = BB->getSingleSuccessor();
8571 if (!BB || !Visited.insert(BB).second)
8572 break;
8573
8574 Begin = BB->getFirstNonPHIIt();
8575 End = BB->end();
8576 }
8577 return false;
8578}
8579
8581 return ::programUndefinedIfUndefOrPoison(Inst, false);
8582}
8583
8585 return ::programUndefinedIfUndefOrPoison(Inst, true);
8586}
8587
8588static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8589 if (FMF.noNaNs())
8590 return true;
8591
8592 if (auto *C = dyn_cast<ConstantFP>(V))
8593 return !C->isNaN();
8594
8595 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8596 if (!C->getElementType()->isFloatingPointTy())
8597 return false;
8598 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8599 if (C->getElementAsAPFloat(I).isNaN())
8600 return false;
8601 }
8602 return true;
8603 }
8604
8606 return true;
8607
8608 return false;
8609}
8610
8611static bool isKnownNonZero(const Value *V) {
8612 if (auto *C = dyn_cast<ConstantFP>(V))
8613 return !C->isZero();
8614
8615 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8616 if (!C->getElementType()->isFloatingPointTy())
8617 return false;
8618 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8619 if (C->getElementAsAPFloat(I).isZero())
8620 return false;
8621 }
8622 return true;
8623 }
8624
8625 return false;
8626}
8627
8628/// Match clamp pattern for float types without care about NaNs or signed zeros.
8629/// Given non-min/max outer cmp/select from the clamp pattern this
8630/// function recognizes if it can be substitued by a "canonical" min/max
8631/// pattern.
8633 Value *CmpLHS, Value *CmpRHS,
8634 Value *TrueVal, Value *FalseVal,
8635 Value *&LHS, Value *&RHS) {
8636 // Try to match
8637 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8638 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8639 // and return description of the outer Max/Min.
8640
8641 // First, check if select has inverse order:
8642 if (CmpRHS == FalseVal) {
8643 std::swap(TrueVal, FalseVal);
8644 Pred = CmpInst::getInversePredicate(Pred);
8645 }
8646
8647 // Assume success now. If there's no match, callers should not use these anyway.
8648 LHS = TrueVal;
8649 RHS = FalseVal;
8650
8651 const APFloat *FC1;
8652 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8653 return {SPF_UNKNOWN, SPNB_NA, false};
8654
8655 const APFloat *FC2;
8656 switch (Pred) {
8657 case CmpInst::FCMP_OLT:
8658 case CmpInst::FCMP_OLE:
8659 case CmpInst::FCMP_ULT:
8660 case CmpInst::FCMP_ULE:
8661 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8662 *FC1 < *FC2)
8663 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8664 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8665 *FC1 < *FC2)
8666 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8667 break;
8668 case CmpInst::FCMP_OGT:
8669 case CmpInst::FCMP_OGE:
8670 case CmpInst::FCMP_UGT:
8671 case CmpInst::FCMP_UGE:
8672 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8673 *FC1 > *FC2)
8674 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8675 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8676 *FC1 > *FC2)
8677 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8678 break;
8679 default:
8680 break;
8681 }
8682
8683 return {SPF_UNKNOWN, SPNB_NA, false};
8684}
8685
8686/// Recognize variations of:
8687/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8689 Value *CmpLHS, Value *CmpRHS,
8690 Value *TrueVal, Value *FalseVal) {
8691 // Swap the select operands and predicate to match the patterns below.
8692 if (CmpRHS != TrueVal) {
8693 Pred = ICmpInst::getSwappedPredicate(Pred);
8694 std::swap(TrueVal, FalseVal);
8695 }
8696 const APInt *C1;
8697 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8698 const APInt *C2;
8699 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8700 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8701 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8702 return {SPF_SMAX, SPNB_NA, false};
8703
8704 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8705 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8706 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8707 return {SPF_SMIN, SPNB_NA, false};
8708
8709 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8710 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8711 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8712 return {SPF_UMAX, SPNB_NA, false};
8713
8714 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8715 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8716 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8717 return {SPF_UMIN, SPNB_NA, false};
8718 }
8719 return {SPF_UNKNOWN, SPNB_NA, false};
8720}
8721
8722/// Recognize variations of:
8723/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8725 Value *CmpLHS, Value *CmpRHS,
8726 Value *TVal, Value *FVal,
8727 unsigned Depth) {
8728 // TODO: Allow FP min/max with nnan/nsz.
8729 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8730
8731 Value *A = nullptr, *B = nullptr;
8732 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8733 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8734 return {SPF_UNKNOWN, SPNB_NA, false};
8735
8736 Value *C = nullptr, *D = nullptr;
8737 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8738 if (L.Flavor != R.Flavor)
8739 return {SPF_UNKNOWN, SPNB_NA, false};
8740
8741 // We have something like: x Pred y ? min(a, b) : min(c, d).
8742 // Try to match the compare to the min/max operations of the select operands.
8743 // First, make sure we have the right compare predicate.
8744 switch (L.Flavor) {
8745 case SPF_SMIN:
8746 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8747 Pred = ICmpInst::getSwappedPredicate(Pred);
8748 std::swap(CmpLHS, CmpRHS);
8749 }
8750 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8751 break;
8752 return {SPF_UNKNOWN, SPNB_NA, false};
8753 case SPF_SMAX:
8754 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8755 Pred = ICmpInst::getSwappedPredicate(Pred);
8756 std::swap(CmpLHS, CmpRHS);
8757 }
8758 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8759 break;
8760 return {SPF_UNKNOWN, SPNB_NA, false};
8761 case SPF_UMIN:
8762 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8763 Pred = ICmpInst::getSwappedPredicate(Pred);
8764 std::swap(CmpLHS, CmpRHS);
8765 }
8766 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8767 break;
8768 return {SPF_UNKNOWN, SPNB_NA, false};
8769 case SPF_UMAX:
8770 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8771 Pred = ICmpInst::getSwappedPredicate(Pred);
8772 std::swap(CmpLHS, CmpRHS);
8773 }
8774 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8775 break;
8776 return {SPF_UNKNOWN, SPNB_NA, false};
8777 default:
8778 return {SPF_UNKNOWN, SPNB_NA, false};
8779 }
8780
8781 // If there is a common operand in the already matched min/max and the other
8782 // min/max operands match the compare operands (either directly or inverted),
8783 // then this is min/max of the same flavor.
8784
8785 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8786 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8787 if (D == B) {
8788 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8789 match(A, m_Not(m_Specific(CmpRHS)))))
8790 return {L.Flavor, SPNB_NA, false};
8791 }
8792 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8793 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8794 if (C == B) {
8795 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8796 match(A, m_Not(m_Specific(CmpRHS)))))
8797 return {L.Flavor, SPNB_NA, false};
8798 }
8799 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8800 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8801 if (D == A) {
8802 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8803 match(B, m_Not(m_Specific(CmpRHS)))))
8804 return {L.Flavor, SPNB_NA, false};
8805 }
8806 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8807 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8808 if (C == A) {
8809 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8810 match(B, m_Not(m_Specific(CmpRHS)))))
8811 return {L.Flavor, SPNB_NA, false};
8812 }
8813
8814 return {SPF_UNKNOWN, SPNB_NA, false};
8815}
8816
8817/// If the input value is the result of a 'not' op, constant integer, or vector
8818/// splat of a constant integer, return the bitwise-not source value.
8819/// TODO: This could be extended to handle non-splat vector integer constants.
8821 Value *NotV;
8822 if (match(V, m_Not(m_Value(NotV))))
8823 return NotV;
8824
8825 const APInt *C;
8826 if (match(V, m_APInt(C)))
8827 return ConstantInt::get(V->getType(), ~(*C));
8828
8829 return nullptr;
8830}
8831
8832/// Match non-obvious integer minimum and maximum sequences.
8834 Value *CmpLHS, Value *CmpRHS,
8835 Value *TrueVal, Value *FalseVal,
8836 Value *&LHS, Value *&RHS,
8837 unsigned Depth) {
8838 // Assume success. If there's no match, callers should not use these anyway.
8839 LHS = TrueVal;
8840 RHS = FalseVal;
8841
8842 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8844 return SPR;
8845
8846 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8848 return SPR;
8849
8850 // Look through 'not' ops to find disguised min/max.
8851 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8852 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8853 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8854 switch (Pred) {
8855 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8856 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8857 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8858 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8859 default: break;
8860 }
8861 }
8862
8863 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8864 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8865 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8866 switch (Pred) {
8867 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8868 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8869 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8870 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8871 default: break;
8872 }
8873 }
8874
8875 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
8876 return {SPF_UNKNOWN, SPNB_NA, false};
8877
8878 const APInt *C1;
8879 if (!match(CmpRHS, m_APInt(C1)))
8880 return {SPF_UNKNOWN, SPNB_NA, false};
8881
8882 // An unsigned min/max can be written with a signed compare.
8883 const APInt *C2;
8884 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
8885 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
8886 // Is the sign bit set?
8887 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
8888 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
8889 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
8890 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8891
8892 // Is the sign bit clear?
8893 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
8894 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
8895 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
8896 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
8897 }
8898
8899 return {SPF_UNKNOWN, SPNB_NA, false};
8900}
8901
8902bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
8903 bool AllowPoison) {
8904 assert(X && Y && "Invalid operand");
8905
8906 auto IsNegationOf = [&](const Value *X, const Value *Y) {
8907 if (!match(X, m_Neg(m_Specific(Y))))
8908 return false;
8909
8910 auto *BO = cast<BinaryOperator>(X);
8911 if (NeedNSW && !BO->hasNoSignedWrap())
8912 return false;
8913
8914 auto *Zero = cast<Constant>(BO->getOperand(0));
8915 if (!AllowPoison && !Zero->isNullValue())
8916 return false;
8917
8918 return true;
8919 };
8920
8921 // X = -Y or Y = -X
8922 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
8923 return true;
8924
8925 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
8926 Value *A, *B;
8927 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
8928 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
8929 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
8931}
8932
8933bool llvm::isKnownInversion(const Value *X, const Value *Y) {
8934 // Handle X = icmp pred A, B, Y = icmp pred A, C.
8935 Value *A, *B, *C;
8936 CmpPredicate Pred1, Pred2;
8937 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
8938 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
8939 return false;
8940
8941 // They must both have samesign flag or not.
8942 if (Pred1.hasSameSign() != Pred2.hasSameSign())
8943 return false;
8944
8945 if (B == C)
8946 return Pred1 == ICmpInst::getInversePredicate(Pred2);
8947
8948 // Try to infer the relationship from constant ranges.
8949 const APInt *RHSC1, *RHSC2;
8950 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
8951 return false;
8952
8953 // Sign bits of two RHSCs should match.
8954 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
8955 return false;
8956
8957 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
8958 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
8959
8960 return CR1.inverse() == CR2;
8961}
8962
8964 SelectPatternNaNBehavior NaNBehavior,
8965 bool Ordered) {
8966 switch (Pred) {
8967 default:
8968 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
8969 case ICmpInst::ICMP_UGT:
8970 case ICmpInst::ICMP_UGE:
8971 return {SPF_UMAX, SPNB_NA, false};
8972 case ICmpInst::ICMP_SGT:
8973 case ICmpInst::ICMP_SGE:
8974 return {SPF_SMAX, SPNB_NA, false};
8975 case ICmpInst::ICMP_ULT:
8976 case ICmpInst::ICMP_ULE:
8977 return {SPF_UMIN, SPNB_NA, false};
8978 case ICmpInst::ICMP_SLT:
8979 case ICmpInst::ICMP_SLE:
8980 return {SPF_SMIN, SPNB_NA, false};
8981 case FCmpInst::FCMP_UGT:
8982 case FCmpInst::FCMP_UGE:
8983 case FCmpInst::FCMP_OGT:
8984 case FCmpInst::FCMP_OGE:
8985 return {SPF_FMAXNUM, NaNBehavior, Ordered};
8986 case FCmpInst::FCMP_ULT:
8987 case FCmpInst::FCMP_ULE:
8988 case FCmpInst::FCMP_OLT:
8989 case FCmpInst::FCMP_OLE:
8990 return {SPF_FMINNUM, NaNBehavior, Ordered};
8991 }
8992}
8993
8994std::optional<std::pair<CmpPredicate, Constant *>>
8997 "Only for relational integer predicates.");
8998 if (isa<UndefValue>(C))
8999 return std::nullopt;
9000
9001 Type *Type = C->getType();
9002 bool IsSigned = ICmpInst::isSigned(Pred);
9003
9005 bool WillIncrement =
9006 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9007
9008 // Check if the constant operand can be safely incremented/decremented
9009 // without overflowing/underflowing.
9010 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9011 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9012 return false;
9013
9014 if (!Pred.hasSameSign())
9015 return true;
9016
9017 // Crossing the corresponding boundary in the other ordering changes the
9018 // sign bit, and therefore changes the poison domain.
9019 return WillIncrement ? !C->isMaxValue(!IsSigned)
9020 : !C->isMinValue(!IsSigned);
9021 };
9022
9023 Constant *SafeReplacementConstant = nullptr;
9024 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9025 // Bail out if the constant can't be safely incremented/decremented.
9026 if (!ConstantIsOk(CI))
9027 return std::nullopt;
9028 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9029 unsigned NumElts = FVTy->getNumElements();
9030 for (unsigned i = 0; i != NumElts; ++i) {
9031 Constant *Elt = C->getAggregateElement(i);
9032 if (!Elt)
9033 return std::nullopt;
9034
9035 if (isa<UndefValue>(Elt))
9036 continue;
9037
9038 // Bail out if we can't determine if this constant is min/max or if we
9039 // know that this constant is min/max.
9040 auto *CI = dyn_cast<ConstantInt>(Elt);
9041 if (!CI || !ConstantIsOk(CI))
9042 return std::nullopt;
9043
9044 if (!SafeReplacementConstant)
9045 SafeReplacementConstant = CI;
9046 }
9047 } else if (isa<VectorType>(C->getType())) {
9048 // Handle scalable splat
9049 Value *SplatC = C->getSplatValue();
9050 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9051 // Bail out if the constant can't be safely incremented/decremented.
9052 if (!CI || !ConstantIsOk(CI))
9053 return std::nullopt;
9054 } else {
9055 // ConstantExpr?
9056 return std::nullopt;
9057 }
9058
9059 // It may not be safe to change a compare predicate in the presence of
9060 // undefined elements, so replace those elements with the first safe constant
9061 // that we found.
9062 // TODO: in case of poison, it is safe; let's replace undefs only.
9063 if (C->containsUndefOrPoisonElement()) {
9064 assert(SafeReplacementConstant && "Replacement constant not set");
9065 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9066 }
9067
9069 Pred.hasSameSign());
9070
9071 // Increment or decrement the constant.
9072 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9073 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9074
9075 return std::make_pair(NewPred, NewC);
9076}
9077
9079 FastMathFlags FMF,
9080 Value *CmpLHS, Value *CmpRHS,
9081 Value *TrueVal, Value *FalseVal,
9082 Value *&LHS, Value *&RHS,
9083 unsigned Depth) {
9084 if (CmpInst::isFPPredicate(Pred)) {
9085 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9086 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9087 // purpose of identifying min/max. Disregard vector constants with undefined
9088 // elements because those can not be back-propagated for analysis.
9089 Value *OutputZeroVal = nullptr;
9090 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9091 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9092 OutputZeroVal = TrueVal;
9093 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9094 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9095 OutputZeroVal = FalseVal;
9096
9097 if (OutputZeroVal) {
9098 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9099 CmpLHS = OutputZeroVal;
9100 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9101 CmpRHS = OutputZeroVal;
9102 }
9103 }
9104
9105 LHS = CmpLHS;
9106 RHS = CmpRHS;
9107
9108 // Signed zero may return inconsistent results between implementations.
9109 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9110 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9111 // Therefore, we behave conservatively and only proceed if at least one of the
9112 // operands is known to not be zero or if we don't care about signed zero.
9113 if (CmpInst::isFPPredicate(Pred)) {
9114 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9115 !isKnownNonZero(CmpRHS))
9116 return {SPF_UNKNOWN, SPNB_NA, false};
9117 }
9118
9119 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9120 bool Ordered = false;
9121
9122 // When given one NaN and one non-NaN input:
9123 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9124 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9125 // ordered comparison fails), which could be NaN or non-NaN.
9126 // so here we discover exactly what NaN behavior is required/accepted.
9127 if (CmpInst::isFPPredicate(Pred)) {
9128 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9129 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9130
9131 if (LHSSafe && RHSSafe) {
9132 // Both operands are known non-NaN.
9133 NaNBehavior = SPNB_RETURNS_ANY;
9134 Ordered = CmpInst::isOrdered(Pred);
9135 } else if (CmpInst::isOrdered(Pred)) {
9136 // An ordered comparison will return false when given a NaN, so it
9137 // returns the RHS.
9138 Ordered = true;
9139 if (LHSSafe)
9140 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9141 NaNBehavior = SPNB_RETURNS_NAN;
9142 else if (RHSSafe)
9143 NaNBehavior = SPNB_RETURNS_OTHER;
9144 else
9145 // Completely unsafe.
9146 return {SPF_UNKNOWN, SPNB_NA, false};
9147 } else {
9148 Ordered = false;
9149 // An unordered comparison will return true when given a NaN, so it
9150 // returns the LHS.
9151 if (LHSSafe)
9152 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9153 NaNBehavior = SPNB_RETURNS_OTHER;
9154 else if (RHSSafe)
9155 NaNBehavior = SPNB_RETURNS_NAN;
9156 else
9157 // Completely unsafe.
9158 return {SPF_UNKNOWN, SPNB_NA, false};
9159 }
9160 }
9161
9162 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9163 std::swap(CmpLHS, CmpRHS);
9164 Pred = CmpInst::getSwappedPredicate(Pred);
9165 if (NaNBehavior == SPNB_RETURNS_NAN)
9166 NaNBehavior = SPNB_RETURNS_OTHER;
9167 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9168 NaNBehavior = SPNB_RETURNS_NAN;
9169 Ordered = !Ordered;
9170 }
9171
9172 // ([if]cmp X, Y) ? X : Y
9173 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9174 return getSelectPattern(Pred, NaNBehavior, Ordered);
9175
9176 if (isKnownNegation(TrueVal, FalseVal)) {
9177 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9178 // match against either LHS or sign-preserving operations on LHS, like
9179 // sext(LHS), or binary ops that do not wrap in signed sense.
9180 auto CmpLHSOrSExt =
9181 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9182 auto MaybeSExtOrMulCmpLHS =
9183 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9184 m_NSWShl(CmpLHSOrSExt, m_Value()));
9185 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9186 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9187 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9188 // Set the return values. If the compare uses the negated value (-X >s 0),
9189 // swap the return values because the negated value is always 'RHS'.
9190 LHS = TrueVal;
9191 RHS = FalseVal;
9192 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9193 std::swap(LHS, RHS);
9194
9195 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9196 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9197 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9198 return {SPF_ABS, SPNB_NA, false};
9199
9200 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9201 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9202 return {SPF_ABS, SPNB_NA, false};
9203
9204 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9205 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9206 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9207 return {SPF_NABS, SPNB_NA, false};
9208 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9209 // Set the return values. If the compare uses the negated value (-X >s 0),
9210 // swap the return values because the negated value is always 'RHS'.
9211 LHS = FalseVal;
9212 RHS = TrueVal;
9213 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9214 std::swap(LHS, RHS);
9215
9216 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9217 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9218 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9219 return {SPF_NABS, SPNB_NA, false};
9220
9221 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9222 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9223 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9224 return {SPF_ABS, SPNB_NA, false};
9225 }
9226 }
9227
9228 if (CmpInst::isIntPredicate(Pred))
9229 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9230
9231 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9232 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9233 // semantics than minNum. Be conservative in such case.
9234 if (NaNBehavior != SPNB_RETURNS_ANY ||
9235 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9236 !isKnownNonZero(CmpRHS)))
9237 return {SPF_UNKNOWN, SPNB_NA, false};
9238
9239 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9240}
9241
9243 Instruction::CastOps *CastOp) {
9244 const DataLayout &DL = CmpI->getDataLayout();
9245
9246 Constant *CastedTo = nullptr;
9247 switch (*CastOp) {
9248 case Instruction::ZExt:
9249 if (CmpI->isUnsigned())
9250 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9251 break;
9252 case Instruction::SExt:
9253 if (CmpI->isSigned())
9254 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9255 break;
9256 case Instruction::Trunc:
9257 Constant *CmpConst;
9258 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9259 CmpConst->getType() == SrcTy) {
9260 // Here we have the following case:
9261 //
9262 // %cond = cmp iN %x, CmpConst
9263 // %tr = trunc iN %x to iK
9264 // %narrowsel = select i1 %cond, iK %t, iK C
9265 //
9266 // We can always move trunc after select operation:
9267 //
9268 // %cond = cmp iN %x, CmpConst
9269 // %widesel = select i1 %cond, iN %x, iN CmpConst
9270 // %tr = trunc iN %widesel to iK
9271 //
9272 // Note that C could be extended in any way because we don't care about
9273 // upper bits after truncation. It can't be abs pattern, because it would
9274 // look like:
9275 //
9276 // select i1 %cond, x, -x.
9277 //
9278 // So only min/max pattern could be matched. Such match requires widened C
9279 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9280 // CmpConst == C is checked below.
9281 CastedTo = CmpConst;
9282 } else {
9283 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9284 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9285 }
9286 break;
9287 case Instruction::FPTrunc:
9288 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9289 break;
9290 case Instruction::FPExt:
9291 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9292 break;
9293 case Instruction::FPToUI:
9294 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9295 break;
9296 case Instruction::FPToSI:
9297 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9298 break;
9299 case Instruction::UIToFP:
9300 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9301 break;
9302 case Instruction::SIToFP:
9303 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9304 break;
9305 default:
9306 break;
9307 }
9308
9309 if (!CastedTo)
9310 return nullptr;
9311
9312 // Make sure the cast doesn't lose any information.
9313 Constant *CastedBack =
9314 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9315 if (CastedBack && CastedBack != C)
9316 return nullptr;
9317
9318 return CastedTo;
9319}
9320
9321/// Helps to match a select pattern in case of a type mismatch.
9322///
9323/// The function processes the case when type of true and false values of a
9324/// select instruction differs from type of the cmp instruction operands because
9325/// of a cast instruction. The function checks if it is legal to move the cast
9326/// operation after "select". If yes, it returns the new second value of
9327/// "select" (with the assumption that cast is moved):
9328/// 1. As operand of cast instruction when both values of "select" are same cast
9329/// instructions.
9330/// 2. As restored constant (by applying reverse cast operation) when the first
9331/// value of the "select" is a cast operation and the second value is a
9332/// constant. It is implemented in lookThroughCastConst().
9333/// 3. As one operand is cast instruction and the other is not. The operands in
9334/// sel(cmp) are in different type integer.
9335/// NOTE: We return only the new second value because the first value could be
9336/// accessed as operand of cast instruction.
9338 Instruction::CastOps *CastOp) {
9339 auto *Cast1 = dyn_cast<CastInst>(V1);
9340 if (!Cast1)
9341 return nullptr;
9342
9343 *CastOp = Cast1->getOpcode();
9344 Type *SrcTy = Cast1->getSrcTy();
9345 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9346 // If V1 and V2 are both the same cast from the same type, look through V1.
9347 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9348 return Cast2->getOperand(0);
9349 return nullptr;
9350 }
9351
9352 auto *C = dyn_cast<Constant>(V2);
9353 if (C)
9354 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9355
9356 Value *CastedTo = nullptr;
9357 if (*CastOp == Instruction::Trunc) {
9358 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9359 // Here we have the following case:
9360 // %y_ext = sext iK %y to iN
9361 // %cond = cmp iN %x, %y_ext
9362 // %tr = trunc iN %x to iK
9363 // %narrowsel = select i1 %cond, iK %tr, iK %y
9364 //
9365 // We can always move trunc after select operation:
9366 // %y_ext = sext iK %y to iN
9367 // %cond = cmp iN %x, %y_ext
9368 // %widesel = select i1 %cond, iN %x, iN %y_ext
9369 // %tr = trunc iN %widesel to iK
9370 assert(V2->getType() == Cast1->getType() &&
9371 "V2 and Cast1 should be the same type.");
9372 CastedTo = CmpI->getOperand(1);
9373 }
9374 }
9375
9376 return CastedTo;
9377}
9379 Instruction::CastOps *CastOp,
9380 unsigned Depth) {
9382 return {SPF_UNKNOWN, SPNB_NA, false};
9383
9385 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9386
9387 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9388 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9389
9390 Value *TrueVal = SI->getTrueValue();
9391 Value *FalseVal = SI->getFalseValue();
9392
9393 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9394 SI->getFastMathFlagsOrNone(),
9395 CastOp, Depth);
9396}
9397
9399 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9400 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9401 CmpInst::Predicate Pred = CmpI->getPredicate();
9402 Value *CmpLHS = CmpI->getOperand(0);
9403 Value *CmpRHS = CmpI->getOperand(1);
9404 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9405 FMF.setNoNaNs();
9406
9407 // Bail out early.
9408 if (CmpI->isEquality())
9409 return {SPF_UNKNOWN, SPNB_NA, false};
9410
9411 // Deal with type mismatches.
9412 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9413 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9414 // If this is a potential fmin/fmax with a cast to integer, then ignore
9415 // -0.0 because there is no corresponding integer value.
9416 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9417 FMF.setNoSignedZeros();
9418 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9419 cast<CastInst>(TrueVal)->getOperand(0), C,
9420 LHS, RHS, Depth);
9421 }
9422 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9423 // If this is a potential fmin/fmax with a cast to integer, then ignore
9424 // -0.0 because there is no corresponding integer value.
9425 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9426 FMF.setNoSignedZeros();
9427 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9428 C, cast<CastInst>(FalseVal)->getOperand(0),
9429 LHS, RHS, Depth);
9430 }
9431 }
9432 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9433 LHS, RHS, Depth);
9434}
9435
9437 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9438 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9439 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9440 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9441 if (SPF == SPF_FMINNUM)
9442 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9443 if (SPF == SPF_FMAXNUM)
9444 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9445 llvm_unreachable("unhandled!");
9446}
9447
9449 switch (SPF) {
9451 return Intrinsic::umin;
9453 return Intrinsic::umax;
9455 return Intrinsic::smin;
9457 return Intrinsic::smax;
9458 default:
9459 llvm_unreachable("Unexpected SPF");
9460 }
9461}
9462
9464 if (SPF == SPF_SMIN) return SPF_SMAX;
9465 if (SPF == SPF_UMIN) return SPF_UMAX;
9466 if (SPF == SPF_SMAX) return SPF_SMIN;
9467 if (SPF == SPF_UMAX) return SPF_UMIN;
9468 llvm_unreachable("unhandled!");
9469}
9470
9472 switch (MinMaxID) {
9473 case Intrinsic::smax: return Intrinsic::smin;
9474 case Intrinsic::smin: return Intrinsic::smax;
9475 case Intrinsic::umax: return Intrinsic::umin;
9476 case Intrinsic::umin: return Intrinsic::umax;
9477 // Please note that next four intrinsics may produce the same result for
9478 // original and inverted case even if X != Y due to NaN is handled specially.
9479 case Intrinsic::maximum: return Intrinsic::minimum;
9480 case Intrinsic::minimum: return Intrinsic::maximum;
9481 case Intrinsic::maxnum: return Intrinsic::minnum;
9482 case Intrinsic::minnum: return Intrinsic::maxnum;
9483 case Intrinsic::maximumnum:
9484 return Intrinsic::minimumnum;
9485 case Intrinsic::minimumnum:
9486 return Intrinsic::maximumnum;
9487 default: llvm_unreachable("Unexpected intrinsic");
9488 }
9489}
9490
9492 switch (SPF) {
9495 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9496 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9497 default: llvm_unreachable("Unexpected flavor");
9498 }
9499}
9500
9501std::pair<Intrinsic::ID, bool>
9503 // Check if VL contains select instructions that can be folded into a min/max
9504 // vector intrinsic and return the intrinsic if it is possible.
9505 // TODO: Support floating point min/max.
9506 bool AllCmpSingleUse = true;
9507 SelectPatternResult SelectPattern;
9508 SelectPattern.Flavor = SPF_UNKNOWN;
9509 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9510 Value *LHS, *RHS;
9511 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9512 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9513 return false;
9514 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9515 SelectPattern.Flavor != CurrentPattern.Flavor)
9516 return false;
9517 SelectPattern = CurrentPattern;
9518 AllCmpSingleUse &=
9520 return true;
9521 })) {
9522 switch (SelectPattern.Flavor) {
9523 case SPF_SMIN:
9524 return {Intrinsic::smin, AllCmpSingleUse};
9525 case SPF_UMIN:
9526 return {Intrinsic::umin, AllCmpSingleUse};
9527 case SPF_SMAX:
9528 return {Intrinsic::smax, AllCmpSingleUse};
9529 case SPF_UMAX:
9530 return {Intrinsic::umax, AllCmpSingleUse};
9531 case SPF_FMAXNUM:
9532 return {Intrinsic::maxnum, AllCmpSingleUse};
9533 case SPF_FMINNUM:
9534 return {Intrinsic::minnum, AllCmpSingleUse};
9535 default:
9536 llvm_unreachable("unexpected select pattern flavor");
9537 }
9538 }
9539 return {Intrinsic::not_intrinsic, false};
9540}
9541
9542template <typename InstTy>
9543static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9544 Value *&Init, Value *&OtherOp) {
9545 // Handle the case of a simple two-predecessor recurrence PHI.
9546 // There's a lot more that could theoretically be done here, but
9547 // this is sufficient to catch some interesting cases.
9548 // TODO: Expand list -- gep, uadd.sat etc.
9549 if (PN->getNumIncomingValues() != 2)
9550 return false;
9551
9552 for (unsigned I = 0; I != 2; ++I) {
9553 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9554 Operation && Operation->getNumOperands() >= 2) {
9555 Value *LHS = Operation->getOperand(0);
9556 Value *RHS = Operation->getOperand(1);
9557 if (LHS != PN && RHS != PN)
9558 continue;
9559
9560 Inst = Operation;
9561 Init = PN->getIncomingValue(!I);
9562 OtherOp = (LHS == PN) ? RHS : LHS;
9563 return true;
9564 }
9565 }
9566 return false;
9567}
9568
9569template <typename InstTy>
9570static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9571 Value *&Init, Value *&OtherOp0,
9572 Value *&OtherOp1) {
9573 if (PN->getNumIncomingValues() != 2)
9574 return false;
9575
9576 for (unsigned I = 0; I != 2; ++I) {
9577 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9578 Operation && Operation->getNumOperands() >= 3) {
9579 Value *Op0 = Operation->getOperand(0);
9580 Value *Op1 = Operation->getOperand(1);
9581 Value *Op2 = Operation->getOperand(2);
9582
9583 if (Op0 != PN && Op1 != PN && Op2 != PN)
9584 continue;
9585
9586 Inst = Operation;
9587 Init = PN->getIncomingValue(!I);
9588 if (Op0 == PN) {
9589 OtherOp0 = Op1;
9590 OtherOp1 = Op2;
9591 } else if (Op1 == PN) {
9592 OtherOp0 = Op0;
9593 OtherOp1 = Op2;
9594 } else {
9595 OtherOp0 = Op0;
9596 OtherOp1 = Op1;
9597 }
9598 return true;
9599 }
9600 }
9601 return false;
9602}
9604 Value *&Start, Value *&Step) {
9605 // We try to match a recurrence of the form:
9606 // %iv = [Start, %entry], [%iv.next, %backedge]
9607 // %iv.next = binop %iv, Step
9608 // Or:
9609 // %iv = [Start, %entry], [%iv.next, %backedge]
9610 // %iv.next = binop Step, %iv
9611 return matchTwoInputRecurrence(P, BO, Start, Step);
9612}
9613
9615 Value *&Start, Value *&Step) {
9616 BinaryOperator *BO = nullptr;
9617 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9618 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9619}
9620
9622 PHINode *&P, Value *&Init,
9623 Value *&OtherOp) {
9624 // Binary intrinsics only supported for now.
9625 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9626 I->getType() != I->getArgOperand(1)->getType())
9627 return false;
9628
9629 IntrinsicInst *II = nullptr;
9630 P = dyn_cast<PHINode>(I->getArgOperand(0));
9631 if (!P)
9632 P = dyn_cast<PHINode>(I->getArgOperand(1));
9633
9634 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9635}
9636
9638 PHINode *&P, Value *&Init,
9639 Value *&OtherOp0,
9640 Value *&OtherOp1) {
9641 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9642 I->getType() != I->getArgOperand(1)->getType() ||
9643 I->getType() != I->getArgOperand(2)->getType())
9644 return false;
9645 IntrinsicInst *II = nullptr;
9646 P = dyn_cast<PHINode>(I->getArgOperand(0));
9647 if (!P) {
9648 P = dyn_cast<PHINode>(I->getArgOperand(1));
9649 if (!P)
9650 P = dyn_cast<PHINode>(I->getArgOperand(2));
9651 }
9652 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9653 II == I;
9654}
9655
9656/// Return true if "icmp Pred LHS RHS" is always true.
9658 const Value *RHS) {
9659 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9660 return true;
9661
9662 switch (Pred) {
9663 default:
9664 return false;
9665
9666 case CmpInst::ICMP_SLE: {
9667 const APInt *C;
9668
9669 // LHS s<= LHS +_{nsw} C if C >= 0
9670 // LHS s<= LHS | C if C >= 0
9671 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9673 return !C->isNegative();
9674
9675 // LHS s<= smax(LHS, V) for any V
9677 return true;
9678
9679 // smin(RHS, V) s<= RHS for any V
9681 return true;
9682
9683 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9684 const Value *X;
9685 const APInt *CLHS, *CRHS;
9686 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9688 return CLHS->sle(*CRHS);
9689
9690 return false;
9691 }
9692
9693 case CmpInst::ICMP_ULE: {
9694 // LHS u<= LHS +_{nuw} V for any V
9695 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9697 return true;
9698
9699 // LHS u<= LHS | V for any V
9700 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9701 return true;
9702
9703 // LHS u<= umax(LHS, V) for any V
9705 return true;
9706
9707 // RHS >> V u<= RHS for any V
9708 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9709 return true;
9710
9711 // RHS u/ C_ugt_1 u<= RHS
9712 const APInt *C;
9713 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9714 return true;
9715
9716 // RHS & V u<= RHS for any V
9718 return true;
9719
9720 // umin(RHS, V) u<= RHS for any V
9722 return true;
9723
9724 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9725 const Value *X;
9726 const APInt *CLHS, *CRHS;
9727 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9729 return CLHS->ule(*CRHS);
9730
9731 return false;
9732 }
9733 }
9734}
9735
9736/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9737/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9738static std::optional<bool>
9740 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9741 switch (Pred) {
9742 default:
9743 return std::nullopt;
9744
9745 case CmpInst::ICMP_SLT:
9746 case CmpInst::ICMP_SLE:
9747 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9749 return true;
9750 return std::nullopt;
9751
9752 case CmpInst::ICMP_SGT:
9753 case CmpInst::ICMP_SGE:
9754 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9756 return true;
9757 return std::nullopt;
9758
9759 case CmpInst::ICMP_ULT:
9760 case CmpInst::ICMP_ULE:
9761 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9763 return true;
9764 return std::nullopt;
9765
9766 case CmpInst::ICMP_UGT:
9767 case CmpInst::ICMP_UGE:
9768 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9770 return true;
9771 return std::nullopt;
9772 }
9773}
9774
9775/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9776/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9777/// Otherwise, return std::nullopt if we can't infer anything.
9778static std::optional<bool>
9780 CmpPredicate RPred, const ConstantRange &RCR) {
9781 auto CRImpliesPred = [&](ConstantRange CR,
9782 CmpInst::Predicate Pred) -> std::optional<bool> {
9783 // If all true values for lhs and true for rhs, lhs implies rhs
9784 if (CR.icmp(Pred, RCR))
9785 return true;
9786
9787 // If there is no overlap, lhs implies not rhs
9788 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9789 return false;
9790
9791 return std::nullopt;
9792 };
9793 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9794 RPred))
9795 return Res;
9796 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9798 : LPred.dropSameSign();
9800 : RPred.dropSameSign();
9801 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9802 RPred);
9803 }
9804 return std::nullopt;
9805}
9806
9807/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9808/// is true. Return false if LHS implies RHS is false. Otherwise, return
9809/// std::nullopt if we can't infer anything.
9810static std::optional<bool>
9811isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9812 CmpPredicate RPred, const Value *R0, const Value *R1,
9813 const DataLayout &DL, bool LHSIsTrue) {
9814 // The rest of the logic assumes the LHS condition is true. If that's not the
9815 // case, invert the predicate to make it so.
9816 if (!LHSIsTrue)
9817 LPred = ICmpInst::getInverseCmpPredicate(LPred);
9818
9819 // We can have non-canonical operands, so try to normalize any common operand
9820 // to L0/R0.
9821 if (L0 == R1) {
9822 std::swap(R0, R1);
9823 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9824 }
9825 if (R0 == L1) {
9826 std::swap(L0, L1);
9827 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9828 }
9829 if (L1 == R1) {
9830 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9831 if (L0 != R0 || match(L0, m_ImmConstant())) {
9832 std::swap(L0, L1);
9833 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9834 std::swap(R0, R1);
9835 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9836 }
9837 }
9838
9839 // See if we can infer anything if operand-0 matches and we have at least one
9840 // constant.
9841 const APInt *Unused;
9842 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
9843 // Potential TODO: We could also further use the constant range of L0/R0 to
9844 // further constraint the constant ranges. At the moment this leads to
9845 // several regressions related to not transforming `multi_use(A + C0) eq/ne
9846 // C1` (see discussion: D58633).
9847 SimplifyQuery SQ(DL);
9852
9853 // Even if L1/R1 are not both constant, we can still sometimes deduce
9854 // relationship from a single constant. For example X u> Y implies X != 0.
9855 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
9856 return R;
9857 // If both L1/R1 were exact constant ranges and we didn't get anything
9858 // here, we won't be able to deduce this.
9859 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
9860 return std::nullopt;
9861 }
9862
9863 // Can we infer anything when the two compares have matching operands?
9864 if (L0 == R0 && L1 == R1)
9865 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
9866
9867 // It only really makes sense in the context of signed comparison for "X - Y
9868 // must be positive if X >= Y and no overflow".
9869 // Take SGT as an example: L0:x > L1:y and C >= 0
9870 // ==> R0:(x -nsw y) < R1:(-C) is false
9871 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
9872 if ((SignedLPred == ICmpInst::ICMP_SGT ||
9873 SignedLPred == ICmpInst::ICMP_SGE) &&
9874 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9875 if (match(R1, m_NonPositive()) &&
9876 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
9877 return false;
9878 }
9879
9880 // Take SLT as an example: L0:x < L1:y and C <= 0
9881 // ==> R0:(x -nsw y) < R1:(-C) is true
9882 if ((SignedLPred == ICmpInst::ICMP_SLT ||
9883 SignedLPred == ICmpInst::ICMP_SLE) &&
9884 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
9885 if (match(R1, m_NonNegative()) &&
9886 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
9887 return true;
9888 }
9889
9890 // a - b == NonZero -> a != b
9891 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
9892 const APInt *L1C;
9893 Value *A, *B;
9894 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
9895 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
9896 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
9897 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
9902 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
9903 }
9904
9905 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
9906 if (L0 == R0 &&
9907 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
9908 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
9909 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
9910 return CmpPredicate::getMatching(LPred, RPred).has_value();
9911
9912 if (auto P = CmpPredicate::getMatching(LPred, RPred))
9913 return isImpliedCondOperands(*P, L0, L1, R0, R1);
9914
9915 return std::nullopt;
9916}
9917
9918/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9919/// is true. Return false if LHS implies RHS is false. Otherwise, return
9920/// std::nullopt if we can't infer anything.
9921static std::optional<bool>
9923 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
9924 const DataLayout &DL, bool LHSIsTrue) {
9925 // The rest of the logic assumes the LHS condition is true. If that's not the
9926 // case, invert the predicate to make it so.
9927 if (!LHSIsTrue)
9928 LPred = FCmpInst::getInversePredicate(LPred);
9929
9930 // We can have non-canonical operands, so try to normalize any common operand
9931 // to L0/R0.
9932 if (L0 == R1) {
9933 std::swap(R0, R1);
9934 RPred = FCmpInst::getSwappedPredicate(RPred);
9935 }
9936 if (R0 == L1) {
9937 std::swap(L0, L1);
9938 LPred = FCmpInst::getSwappedPredicate(LPred);
9939 }
9940 if (L1 == R1) {
9941 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
9942 if (L0 != R0 || match(L0, m_ImmConstant())) {
9943 std::swap(L0, L1);
9944 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
9945 std::swap(R0, R1);
9946 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
9947 }
9948 }
9949
9950 // Can we infer anything when the two compares have matching operands?
9951 if (L0 == R0 && L1 == R1) {
9952 if ((LPred & RPred) == LPred)
9953 return true;
9954 if ((LPred & ~RPred) == LPred)
9955 return false;
9956 }
9957
9958 // See if we can infer anything if operand-0 matches and we have at least one
9959 // constant.
9960 const APFloat *L1C, *R1C;
9961 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
9962 if (std::optional<ConstantFPRange> DomCR =
9964 if (std::optional<ConstantFPRange> ImpliedCR =
9966 if (ImpliedCR->contains(*DomCR))
9967 return true;
9968 }
9969 if (std::optional<ConstantFPRange> ImpliedCR =
9971 FCmpInst::getInversePredicate(RPred), *R1C)) {
9972 if (ImpliedCR->contains(*DomCR))
9973 return false;
9974 }
9975 }
9976 }
9977
9978 return std::nullopt;
9979}
9980
9981/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
9982/// false. Otherwise, return std::nullopt if we can't infer anything. We
9983/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
9984/// instruction.
9985static std::optional<bool>
9987 const Value *RHSOp0, const Value *RHSOp1,
9988 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
9989 // The LHS must be an 'or', 'and', or a 'select' instruction.
9990 assert((LHS->getOpcode() == Instruction::And ||
9991 LHS->getOpcode() == Instruction::Or ||
9992 LHS->getOpcode() == Instruction::Select) &&
9993 "Expected LHS to be 'and', 'or', or 'select'.");
9994
9995 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
9996
9997 // If the result of an 'or' is false, then we know both legs of the 'or' are
9998 // false. Similarly, if the result of an 'and' is true, then we know both
9999 // legs of the 'and' are true.
10000 const Value *ALHS, *ARHS;
10001 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10002 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10003 // FIXME: Make this non-recursion.
10004 if (std::optional<bool> Implication = isImpliedCondition(
10005 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10006 return Implication;
10007 if (std::optional<bool> Implication = isImpliedCondition(
10008 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10009 return Implication;
10010 return std::nullopt;
10011 }
10012 return std::nullopt;
10013}
10014
10015std::optional<bool>
10017 const Value *RHSOp0, const Value *RHSOp1,
10018 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10019 // Bail out when we hit the limit.
10021 return std::nullopt;
10022
10023 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10024 // example.
10025 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10026 return std::nullopt;
10027
10028 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10029 "Expected integer type only!");
10030
10031 // Match not
10032 if (match(LHS, m_Not(m_Value(LHS))))
10033 LHSIsTrue = !LHSIsTrue;
10034
10035 // Both LHS and RHS are icmps.
10036 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10037 CmpPredicate LHSPred;
10038 Value *LHSOp0, *LHSOp1;
10039 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10040 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10041 RHSOp1, DL, LHSIsTrue);
10042 } else {
10043 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10044 "Expected floating point type only!");
10045 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10046 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10047 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10048 DL, LHSIsTrue);
10049 }
10050
10051 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10052 /// the RHS to be an icmp.
10053 /// FIXME: Add support for and/or/select on the RHS.
10054 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10055 if ((LHSI->getOpcode() == Instruction::And ||
10056 LHSI->getOpcode() == Instruction::Or ||
10057 LHSI->getOpcode() == Instruction::Select))
10058 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10059 Depth);
10060 }
10061 return std::nullopt;
10062}
10063
10064std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10065 const DataLayout &DL,
10066 bool LHSIsTrue, unsigned Depth) {
10067 // LHS ==> RHS by definition
10068 if (LHS == RHS)
10069 return LHSIsTrue;
10070
10071 // Match not
10072 bool InvertRHS = false;
10073 if (match(RHS, m_Not(m_Value(RHS)))) {
10074 if (LHS == RHS)
10075 return !LHSIsTrue;
10076 InvertRHS = true;
10077 }
10078
10079 CmpPredicate RHSPred;
10080 Value *RHSOp0, *RHSOp1;
10081 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10082 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10083 LHSIsTrue, Depth))
10084 return InvertRHS ? !*Implied : *Implied;
10085 return std::nullopt;
10086 }
10087 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10088 if (auto Implied = isImpliedCondition(
10089 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10090 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10091 return InvertRHS ? !*Implied : *Implied;
10092 return std::nullopt;
10093 }
10094
10096 return std::nullopt;
10097
10098 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10099 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10100 const Value *RHS1, *RHS2;
10101 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10102 if (std::optional<bool> Imp =
10103 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10104 if (*Imp == true)
10105 return !InvertRHS;
10106 if (std::optional<bool> Imp =
10107 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10108 if (*Imp == true)
10109 return !InvertRHS;
10110 }
10111 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10112 if (std::optional<bool> Imp =
10113 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10114 if (*Imp == false)
10115 return InvertRHS;
10116 if (std::optional<bool> Imp =
10117 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10118 if (*Imp == false)
10119 return InvertRHS;
10120 }
10121
10122 return std::nullopt;
10123}
10124
10125// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10126// condition dominating ContextI or nullptr, if no condition is found.
10127static std::pair<Value *, bool>
10129 if (!ContextI || !ContextI->getParent())
10130 return {nullptr, false};
10131
10132 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10133 // dominator tree (eg, from a SimplifyQuery) instead?
10134 const BasicBlock *ContextBB = ContextI->getParent();
10135 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10136 if (!PredBB)
10137 return {nullptr, false};
10138
10139 // We need a conditional branch in the predecessor.
10140 Value *PredCond;
10141 BasicBlock *TrueBB, *FalseBB;
10142 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10143 return {nullptr, false};
10144
10145 // The branch should get simplified. Don't bother simplifying this condition.
10146 if (TrueBB == FalseBB)
10147 return {nullptr, false};
10148
10149 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10150 "Predecessor block does not point to successor?");
10151
10152 // Is this condition implied by the predecessor condition?
10153 return {PredCond, TrueBB == ContextBB};
10154}
10155
10156std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10157 const Instruction *ContextI,
10158 const DataLayout &DL) {
10159 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10160 auto PredCond = getDomPredecessorCondition(ContextI);
10161 if (PredCond.first)
10162 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10163 return std::nullopt;
10164}
10165
10167 const Value *LHS,
10168 const Value *RHS,
10169 const Instruction *ContextI,
10170 const DataLayout &DL) {
10171 auto PredCond = getDomPredecessorCondition(ContextI);
10172 if (PredCond.first)
10173 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10174 PredCond.second);
10175 return std::nullopt;
10176}
10177
10179 APInt &Upper, const InstrInfoQuery &IIQ,
10180 bool PreferSignedRange) {
10181 unsigned Width = Lower.getBitWidth();
10182 const APInt *C;
10183 switch (BO.getOpcode()) {
10184 case Instruction::Sub:
10185 if (match(BO.getOperand(0), m_APInt(C))) {
10186 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10187 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10188
10189 // If the caller expects a signed compare, then try to use a signed range.
10190 // Otherwise if both no-wraps are set, use the unsigned range because it
10191 // is never larger than the signed range. Example:
10192 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10193 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10194 if (PreferSignedRange && HasNSW && HasNUW)
10195 HasNUW = false;
10196
10197 if (HasNUW) {
10198 // 'sub nuw c, x' produces [0, C].
10199 Upper = *C + 1;
10200 } else if (HasNSW) {
10201 if (C->isNegative()) {
10202 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10204 Upper = *C - APInt::getSignedMaxValue(Width);
10205 } else {
10206 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10207 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10208 Lower = *C - APInt::getSignedMaxValue(Width);
10210 }
10211 }
10212 }
10213 break;
10214 case Instruction::Add:
10215 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10216 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10217 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10218
10219 // If the caller expects a signed compare, then try to use a signed
10220 // range. Otherwise if both no-wraps are set, use the unsigned range
10221 // because it is never larger than the signed range. Example: "add nuw
10222 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10223 if (PreferSignedRange && HasNSW && HasNUW)
10224 HasNUW = false;
10225
10226 if (HasNUW) {
10227 // 'add nuw x, C' produces [C, UINT_MAX].
10228 Lower = *C;
10229 } else if (HasNSW) {
10230 if (C->isNegative()) {
10231 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10233 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10234 } else {
10235 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10236 Lower = APInt::getSignedMinValue(Width) + *C;
10237 Upper = APInt::getSignedMaxValue(Width) + 1;
10238 }
10239 }
10240 }
10241 break;
10242
10243 case Instruction::And:
10244 if (match(BO.getOperand(1), m_APInt(C)))
10245 // 'and x, C' produces [0, C].
10246 Upper = *C + 1;
10247 // X & -X is a power of two or zero. So we can cap the value at max power of
10248 // two.
10249 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10250 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10251 Upper = APInt::getSignedMinValue(Width) + 1;
10252 break;
10253
10254 case Instruction::Or:
10255 if (match(BO.getOperand(1), m_APInt(C)))
10256 // 'or x, C' produces [C, UINT_MAX].
10257 Lower = *C;
10258 break;
10259
10260 case Instruction::AShr:
10261 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10262 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10264 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10265 } else if (match(BO.getOperand(0), m_APInt(C))) {
10266 unsigned ShiftAmount = Width - 1;
10267 if (!C->isZero() && IIQ.isExact(&BO))
10268 ShiftAmount = C->countr_zero();
10269 if (C->isNegative()) {
10270 // 'ashr C, x' produces [C, C >> (Width-1)]
10271 Lower = *C;
10272 Upper = C->ashr(ShiftAmount) + 1;
10273 } else {
10274 // 'ashr C, x' produces [C >> (Width-1), C]
10275 Lower = C->ashr(ShiftAmount);
10276 Upper = *C + 1;
10277 }
10278 }
10279 break;
10280
10281 case Instruction::LShr:
10282 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10283 // 'lshr x, C' produces [0, UINT_MAX >> C].
10284 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10285 } else if (match(BO.getOperand(0), m_APInt(C))) {
10286 // 'lshr C, x' produces [C >> (Width-1), C].
10287 unsigned ShiftAmount = Width - 1;
10288 if (!C->isZero() && IIQ.isExact(&BO))
10289 ShiftAmount = C->countr_zero();
10290 Lower = C->lshr(ShiftAmount);
10291 Upper = *C + 1;
10292 }
10293 break;
10294
10295 case Instruction::Shl:
10296 if (match(BO.getOperand(0), m_APInt(C))) {
10297 if (IIQ.hasNoUnsignedWrap(&BO)) {
10298 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10299 Lower = *C;
10300 Upper = Lower.shl(Lower.countl_zero()) + 1;
10301 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10302 if (C->isNegative()) {
10303 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10304 unsigned ShiftAmount = C->countl_one() - 1;
10305 Lower = C->shl(ShiftAmount);
10306 Upper = *C + 1;
10307 } else {
10308 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10309 unsigned ShiftAmount = C->countl_zero() - 1;
10310 Lower = *C;
10311 Upper = C->shl(ShiftAmount) + 1;
10312 }
10313 } else {
10314 // If lowbit is set, value can never be zero.
10315 if ((*C)[0])
10316 Lower = APInt::getOneBitSet(Width, 0);
10317 // If we are shifting a constant the largest it can be is if the longest
10318 // sequence of consecutive ones is shifted to the highbits (breaking
10319 // ties for which sequence is higher). At the moment we take a liberal
10320 // upper bound on this by just popcounting the constant.
10321 // TODO: There may be a bitwise trick for it longest/highest
10322 // consecutative sequence of ones (naive method is O(Width) loop).
10323 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10324 }
10325 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10326 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10327 }
10328 break;
10329
10330 case Instruction::SDiv:
10331 if (match(BO.getOperand(1), m_APInt(C))) {
10332 APInt IntMin = APInt::getSignedMinValue(Width);
10333 APInt IntMax = APInt::getSignedMaxValue(Width);
10334 if (C->isAllOnes()) {
10335 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10336 // where C != -1 and C != 0 and C != 1
10337 Lower = IntMin + 1;
10338 Upper = IntMax + 1;
10339 } else if (C->countl_zero() < Width - 1) {
10340 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10341 // where C != -1 and C != 0 and C != 1
10342 Lower = IntMin.sdiv(*C);
10343 Upper = IntMax.sdiv(*C);
10344 if (Lower.sgt(Upper))
10346 Upper = Upper + 1;
10347 assert(Upper != Lower && "Upper part of range has wrapped!");
10348 }
10349 } else if (match(BO.getOperand(0), m_APInt(C))) {
10350 if (C->isMinSignedValue()) {
10351 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10352 Lower = *C;
10353 Upper = Lower.lshr(1) + 1;
10354 } else {
10355 // 'sdiv C, x' produces [-|C|, |C|].
10356 Upper = C->abs() + 1;
10357 Lower = (-Upper) + 1;
10358 }
10359 }
10360 break;
10361
10362 case Instruction::UDiv:
10363 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10364 // 'udiv x, C' produces [0, UINT_MAX / C].
10365 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10366 } else if (match(BO.getOperand(0), m_APInt(C))) {
10367 // 'udiv C, x' produces [0, C].
10368 Upper = *C + 1;
10369 }
10370 break;
10371
10372 case Instruction::SRem:
10373 if (match(BO.getOperand(1), m_APInt(C))) {
10374 // 'srem x, C' produces (-|C|, |C|).
10375 Upper = C->abs();
10376 Lower = (-Upper) + 1;
10377 } else if (match(BO.getOperand(0), m_APInt(C))) {
10378 if (C->isNegative()) {
10379 // 'srem -|C|, x' produces [-|C|, 0].
10380 Upper = 1;
10381 Lower = *C;
10382 } else {
10383 // 'srem |C|, x' produces [0, |C|].
10384 Upper = *C + 1;
10385 }
10386 }
10387 break;
10388
10389 case Instruction::URem:
10390 if (match(BO.getOperand(1), m_APInt(C)))
10391 // 'urem x, C' produces [0, C).
10392 Upper = *C;
10393 else if (match(BO.getOperand(0), m_APInt(C)))
10394 // 'urem C, x' produces [0, C].
10395 Upper = *C + 1;
10396 break;
10397
10398 default:
10399 break;
10400 }
10401}
10402
10404 bool UseInstrInfo) {
10405 unsigned Width = II.getType()->getScalarSizeInBits();
10406 const APInt *C;
10407 switch (II.getIntrinsicID()) {
10408 case Intrinsic::ctlz:
10409 case Intrinsic::cttz: {
10410 APInt Upper(Width, Width);
10411 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10412 Upper += 1;
10413 // Maximum of set/clear bits is the bit width.
10415 }
10416 case Intrinsic::ctpop:
10417 // Maximum of set/clear bits is the bit width.
10419 APInt(Width, Width) + 1);
10420 case Intrinsic::uadd_sat:
10421 // uadd.sat(x, C) produces [C, UINT_MAX].
10422 if (match(II.getOperand(0), m_APInt(C)) ||
10423 match(II.getOperand(1), m_APInt(C)))
10425 break;
10426 case Intrinsic::sadd_sat:
10427 if (match(II.getOperand(0), m_APInt(C)) ||
10428 match(II.getOperand(1), m_APInt(C))) {
10429 if (C->isNegative())
10430 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10432 APInt::getSignedMaxValue(Width) + *C +
10433 1);
10434
10435 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10437 APInt::getSignedMaxValue(Width) + 1);
10438 }
10439 break;
10440 case Intrinsic::usub_sat:
10441 // usub.sat(C, x) produces [0, C].
10442 if (match(II.getOperand(0), m_APInt(C)))
10443 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10444
10445 // usub.sat(x, C) produces [0, UINT_MAX - C].
10446 if (match(II.getOperand(1), m_APInt(C)))
10448 APInt::getMaxValue(Width) - *C + 1);
10449 break;
10450 case Intrinsic::ssub_sat:
10451 if (match(II.getOperand(0), m_APInt(C))) {
10452 if (C->isNegative())
10453 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10455 *C - APInt::getSignedMinValue(Width) +
10456 1);
10457
10458 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10460 APInt::getSignedMaxValue(Width) + 1);
10461 } else if (match(II.getOperand(1), m_APInt(C))) {
10462 if (C->isNegative())
10463 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10465 APInt::getSignedMaxValue(Width) + 1);
10466
10467 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10469 APInt::getSignedMaxValue(Width) - *C +
10470 1);
10471 }
10472 break;
10473 case Intrinsic::umin:
10474 case Intrinsic::umax:
10475 case Intrinsic::smin:
10476 case Intrinsic::smax:
10477 if (!match(II.getOperand(0), m_APInt(C)) &&
10478 !match(II.getOperand(1), m_APInt(C)))
10479 break;
10480
10481 switch (II.getIntrinsicID()) {
10482 case Intrinsic::umin:
10483 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10484 case Intrinsic::umax:
10486 case Intrinsic::smin:
10488 *C + 1);
10489 case Intrinsic::smax:
10491 APInt::getSignedMaxValue(Width) + 1);
10492 default:
10493 llvm_unreachable("Must be min/max intrinsic");
10494 }
10495 break;
10496 case Intrinsic::abs:
10497 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10498 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10499 if (match(II.getOperand(1), m_One()))
10501 APInt::getSignedMaxValue(Width) + 1);
10502
10504 APInt::getSignedMinValue(Width) + 1);
10505 case Intrinsic::vscale:
10506 if (!II.getParent() || !II.getFunction())
10507 break;
10508 return getVScaleRange(II.getFunction(), Width);
10509 default:
10510 break;
10511 }
10512
10513 return ConstantRange::getFull(Width);
10514}
10515
10517 const InstrInfoQuery &IIQ) {
10518 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10519 const Value *LHS = nullptr, *RHS = nullptr;
10521 if (R.Flavor == SPF_UNKNOWN)
10522 return ConstantRange::getFull(BitWidth);
10523
10524 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10525 // If the negation part of the abs (in RHS) has the NSW flag,
10526 // then the result of abs(X) is [0..SIGNED_MAX],
10527 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10528 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10532
10535 }
10536
10537 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10538 // The result of -abs(X) is <= 0.
10540 APInt(BitWidth, 1));
10541 }
10542
10543 const APInt *C;
10544 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10545 return ConstantRange::getFull(BitWidth);
10546
10547 switch (R.Flavor) {
10548 case SPF_UMIN:
10550 case SPF_UMAX:
10552 case SPF_SMIN:
10554 *C + 1);
10555 case SPF_SMAX:
10558 default:
10559 return ConstantRange::getFull(BitWidth);
10560 }
10561}
10562
10564 // The maximum representable value of a half is 65504. For floats the maximum
10565 // value is 3.4e38 which requires roughly 129 bits.
10566 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10567 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10568 return;
10569 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10570 Lower = APInt(BitWidth, -65504, true);
10571 Upper = APInt(BitWidth, 65505);
10572 }
10573
10574 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10575 // For a fptoui the lower limit is left as 0.
10576 Upper = APInt(BitWidth, 65505);
10577 }
10578}
10579
10581 const SimplifyQuery &SQ,
10582 unsigned Depth) {
10583 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10584
10586 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10587
10588 if (auto *C = dyn_cast<Constant>(V))
10589 return C->toConstantRange();
10590
10591 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10592 ConstantRange CR = ConstantRange::getFull(BitWidth);
10593 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10594 APInt Lower = APInt(BitWidth, 0);
10595 APInt Upper = APInt(BitWidth, 0);
10596 // TODO: Return ConstantRange.
10597 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10599 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10601 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10602 ConstantRange CRTrue =
10603 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10604 ConstantRange CRFalse =
10605 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10606 CR = CRTrue.unionWith(CRFalse);
10608 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10609 ConstantRange SrcCR =
10610 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10611 CR = SrcCR.truncate(BitWidth);
10612 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10613 APInt Lower = APInt(BitWidth, 0);
10614 APInt Upper = APInt(BitWidth, 0);
10615 // TODO: Return ConstantRange.
10618 } else if (const auto *A = dyn_cast<Argument>(V))
10619 if (std::optional<ConstantRange> Range = A->getRange())
10620 CR = *Range;
10621
10622 if (auto *I = dyn_cast<Instruction>(V)) {
10623 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10625
10626 Value *FrexpSrc;
10627 if (const auto *CB = dyn_cast<CallBase>(V)) {
10628 if (std::optional<ConstantRange> Range = CB->getRange())
10629 CR = CR.intersectWith(*Range);
10631 m_Value(FrexpSrc))))) {
10632 const fltSemantics &FltSem =
10633 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10634 // It should be possible to implement this for any type, but this logic
10635 // only computes the range assuming standard subnormal handling.
10636 if (APFloat::isIEEELikeFP(FltSem)) {
10638 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10639
10640 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10641 // constrain its range when the source can be neither.
10642 if (KnownSrc.isKnownNeverInfOrNaN()) {
10643 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10644
10645 // Offset to find the true minimum exponent value for a denormal.
10646 if (!KnownSrc.isKnownNeverSubnormal())
10647 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10648
10649 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10650
10651 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10653
10654 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10655 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10656
10657 MinExp = std::max(AdjustedMin, MinExp);
10658 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10659 MaxExp);
10660
10662 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10663 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10664 /*isSigned=*/true));
10665 }
10666 }
10667 }
10668 }
10669
10670 if (SQ.CxtI && SQ.AC) {
10671 // Try to restrict the range based on information from assumptions.
10672 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10673 if (!AssumeVH)
10674 continue;
10675 CallInst *I = cast<CallInst>(AssumeVH);
10676 assert(I->getParent()->getParent() == SQ.CxtI->getParent()->getParent() &&
10677 "Got assumption for the wrong function!");
10678 assert(I->getIntrinsicID() == Intrinsic::assume &&
10679 "must be an assume intrinsic");
10680
10681 if (!isValidAssumeForContext(I, SQ))
10682 continue;
10683 Value *Arg = I->getArgOperand(0);
10684 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10685 // Currently we just use information from comparisons.
10686 if (!Cmp || Cmp->getOperand(0) != V)
10687 continue;
10688 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10689 ConstantRange RHS =
10690 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10691 SQ.getWithInstruction(I), Depth + 1);
10692 CR = CR.intersectWith(
10693 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10694 }
10695 }
10696
10697 return CR;
10698}
10699
10700static void
10702 function_ref<void(Value *)> InsertAffected) {
10703 assert(V != nullptr);
10704 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10705 InsertAffected(V);
10706 } else if (auto *I = dyn_cast<Instruction>(V)) {
10707 InsertAffected(V);
10708
10709 // Peek through unary operators to find the source of the condition.
10710 Value *Op;
10712 m_Trunc(m_Value(Op))))) {
10714 InsertAffected(Op);
10715 }
10716 }
10717}
10718
10720 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10721 auto AddAffected = [&InsertAffected](Value *V) {
10722 addValueAffectedByCondition(V, InsertAffected);
10723 };
10724
10725 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10726 if (IsAssume) {
10727 AddAffected(LHS);
10728 AddAffected(RHS);
10729 } else if (match(RHS, m_Constant()))
10730 AddAffected(LHS);
10731 };
10732
10733 SmallVector<Value *, 8> Worklist;
10735 Worklist.push_back(Cond);
10736 while (!Worklist.empty()) {
10737 Value *V = Worklist.pop_back_val();
10738 if (!Visited.insert(V).second)
10739 continue;
10740
10741 CmpPredicate Pred;
10742 Value *A, *B, *X;
10743
10744 if (IsAssume) {
10745 AddAffected(V);
10746 if (match(V, m_Not(m_Value(X))))
10747 AddAffected(X);
10748 }
10749
10750 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10751 // assume(A && B) is split to -> assume(A); assume(B);
10752 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10753 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10754 // enough information to be worth handling (intersection of information as
10755 // opposed to union).
10756 if (!IsAssume) {
10757 Worklist.push_back(A);
10758 Worklist.push_back(B);
10759 }
10760 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10761 bool HasRHSC = match(B, m_ConstantInt());
10762 if (ICmpInst::isEquality(Pred)) {
10763 AddAffected(A);
10764 if (IsAssume)
10765 AddAffected(B);
10766 if (HasRHSC) {
10767 Value *Y;
10768 // (X << C) or (X >>_s C) or (X >>_u C).
10769 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10770 AddAffected(X);
10771 // (X & C) or (X | C).
10772 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10773 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10774 AddAffected(X);
10775 AddAffected(Y);
10776 }
10777 // X - Y
10778 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10779 AddAffected(X);
10780 AddAffected(Y);
10781 }
10782 }
10783 } else {
10784 AddCmpOperands(A, B);
10785 if (HasRHSC) {
10786 // Handle (A + C1) u< C2, which is the canonical form of
10787 // A > C3 && A < C4.
10789 AddAffected(X);
10790
10791 if (ICmpInst::isUnsigned(Pred)) {
10792 Value *Y;
10793 // X & Y u> C -> X >u C && Y >u C
10794 // X | Y u< C -> X u< C && Y u< C
10795 // X nuw+ Y u< C -> X u< C && Y u< C
10796 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10797 match(A, m_Or(m_Value(X), m_Value(Y))) ||
10798 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
10799 AddAffected(X);
10800 AddAffected(Y);
10801 }
10802 // X nuw- Y u> C -> X u> C
10803 if (match(A, m_NUWSub(m_Value(X), m_Value())))
10804 AddAffected(X);
10805 }
10806 }
10807
10808 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
10809 // by computeKnownFPClass().
10811 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
10812 InsertAffected(X);
10813 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
10814 InsertAffected(X);
10815 }
10816 }
10817
10818 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
10819 Value *SquareOp = nullptr;
10820 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
10821 AddAffected(SquareOp);
10822 };
10823 AddNuwSquareOperand(A);
10824 AddNuwSquareOperand(B);
10825
10826 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
10827 AddAffected(X);
10828 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
10829 AddCmpOperands(A, B);
10830
10831 // fcmp fneg(x), y
10832 // fcmp fabs(x), y
10833 // fcmp fneg(fabs(x)), y
10834 if (match(A, m_FNeg(m_Value(A))))
10835 AddAffected(A);
10836 if (match(A, m_FAbs(m_Value(A))))
10837 AddAffected(A);
10838
10840 m_Value()))) {
10841 // Handle patterns that computeKnownFPClass() support.
10842 AddAffected(A);
10843 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
10844 // Assume is checked here as X is already added above for assumes in
10845 // addValueAffectedByCondition
10846 AddAffected(X);
10847 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
10848 // Assume is checked here to avoid issues with ephemeral values
10849 Worklist.push_back(X);
10850 }
10851 }
10852}
10853
10855 // (X >> C) or/add (X & mask(C) != 0)
10856 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
10857 if (BO->getOpcode() == Instruction::Add ||
10858 BO->getOpcode() == Instruction::Or) {
10859 const Value *X;
10860 const APInt *C1, *C2;
10861 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
10865 m_Zero())))) &&
10866 C2->popcount() == C1->getZExtValue())
10867 return X;
10868 }
10869 }
10870 return nullptr;
10871}
10872
10874 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
10875}
10876
10879 unsigned MaxCount, bool AllowUndefOrPoison) {
10882 auto Push = [&](const Value *V) -> bool {
10883 Constant *C;
10884 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
10885 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
10886 return false;
10887 // Check existence first to avoid unnecessary allocations.
10888 if (Constants.contains(C))
10889 return true;
10890 if (Constants.size() == MaxCount)
10891 return false;
10892 Constants.insert(C);
10893 return true;
10894 }
10895
10896 if (auto *Inst = dyn_cast<Instruction>(V)) {
10897 if (Visited.insert(Inst).second)
10898 Worklist.push_back(Inst);
10899 return true;
10900 }
10901 return false;
10902 };
10903 if (!Push(V))
10904 return false;
10905 while (!Worklist.empty()) {
10906 const Instruction *CurInst = Worklist.pop_back_val();
10907 switch (CurInst->getOpcode()) {
10908 case Instruction::Select:
10909 if (!Push(CurInst->getOperand(1)))
10910 return false;
10911 if (!Push(CurInst->getOperand(2)))
10912 return false;
10913 break;
10914 case Instruction::PHI:
10915 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
10916 // Fast path for recurrence PHI.
10917 if (IncomingValue == CurInst)
10918 continue;
10919 if (!Push(IncomingValue))
10920 return false;
10921 }
10922 break;
10923 default:
10924 return false;
10925 }
10926 }
10927 return true;
10928}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define 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 bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp: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:6067
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
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:2007
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1600
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:231
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1427
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:420
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1561
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1412
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1691
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:203
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1351
unsigned ceilLogBase2() const
Definition APInt.h:1785
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1206
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:368
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1187
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:377
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1509
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1116
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:206
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:213
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:326
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1254
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1671
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:785
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1171
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1649
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1619
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:216
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1085
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:353
unsigned logBase2() const
Definition APInt.h:1782
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:830
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:468
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:402
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:331
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1155
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:876
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1262
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1135
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:293
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:197
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1409
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1242
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:283
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:236
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:854
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1226
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:105
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:261
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange 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.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:282
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:307
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition Type.h:326
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:285
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:270
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:227
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:106
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp: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:3041
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2290
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
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:452
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h: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:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
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 pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const Instruction * CxtI
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1033