LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98template <typename InstTy>
99static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
100 Value *&Init, Value *&OtherOp);
101
102/// Returns the bitwidth of the given scalar or pointer type. For vector types,
103/// returns the element type's bitwidth.
104static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
105 if (unsigned BitWidth = Ty->getScalarSizeInBits())
106 return BitWidth;
107
108 return DL.getPointerTypeSizeInBits(Ty);
109}
110
111// Given the provided Value and, potentially, a context instruction, return
112// the preferred context instruction (if any).
113static const Instruction *safeCtxI(const Value *V, const Instruction *CtxI) {
114 // If we've been provided with a context instruction, then use that (provided
115 // it has been inserted).
116 if (CtxI && CtxI->getParent())
117 return CtxI;
118
119 // If the value is really an already-inserted instruction, then use that.
120 CtxI = dyn_cast<Instruction>(V);
121 if (CtxI && CtxI->getParent())
122 return CtxI;
123
124 return nullptr;
125}
126
128 const APInt &DemandedElts,
129 APInt &DemandedLHS, APInt &DemandedRHS) {
130 if (isa<ScalableVectorType>(Shuf->getType())) {
131 assert(DemandedElts == APInt(1,1));
132 DemandedLHS = DemandedRHS = DemandedElts;
133 return true;
134 }
135
136 int NumElts =
137 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
138 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
139 DemandedElts, DemandedLHS, DemandedRHS);
140}
141
142static void computeKnownBits(const Value *V, const APInt &DemandedElts,
143 KnownBits &Known, const SimplifyQuery &Q,
144 unsigned Depth);
145
147 const SimplifyQuery &Q, unsigned Depth) {
148 // Since the number of lanes in a scalable vector is unknown at compile time,
149 // we track one bit which is implicitly broadcast to all lanes. This means
150 // that all lanes in a scalable vector are considered demanded.
151 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
152 APInt DemandedElts =
153 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
154 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
155}
156
158 const DataLayout &DL, AssumptionCache *AC,
159 const Instruction *CtxI, const DominatorTree *DT,
160 bool UseInstrInfo, unsigned Depth) {
162 SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
163 Depth);
164}
165
167 AssumptionCache *AC, const Instruction *CtxI,
168 const DominatorTree *DT, bool UseInstrInfo,
169 unsigned Depth) {
170 return computeKnownBits(
171 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
172}
173
176 const SimplifyQuery &SQ) {
177 // Look for an inverted mask: (X & ~M) op (Y & M).
178 {
179 Value *M;
180 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
182 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CtxI, SQ.DT)
185 }
186
187 // X op (Y & ~X)
189 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT)
192
193 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
194 // for constant Y.
195 Value *Y;
196 if (match(RHS,
198 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT) &&
199 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT);
200 return IsNoUndef ? NoCommonBitsSetResult::Known
202 }
203
204 // Peek through extends to find a 'not' of the other side:
205 // (ext Y) op ext(~Y)
206 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
208 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CtxI, SQ.DT)
211
212 // Look for: (A & B) op ~(A | B)
213 {
214 Value *A, *B;
215 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
217 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CtxI, SQ.DT) &&
218 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CtxI, SQ.DT);
219 return IsNoUndef ? NoCommonBitsSetResult::Known
221 }
222 }
223
224 // Look for: (X << V) op (Y >> (BitWidth - V))
225 // or (X >> V) op (Y << (BitWidth - V))
226 {
227 const Value *V;
228 const APInt *R;
229 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
230 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
231 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
232 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
233 R->uge(LHS->getType()->getScalarSizeInBits()))
235 }
236
238}
239
242 const WithCache<const Value *> &RHSCache,
243 const SimplifyQuery &SQ) {
244 const Value *LHS = LHSCache.getValue();
245 const Value *RHS = RHSCache.getValue();
246
247 assert(LHS->getType() == RHS->getType() &&
248 "LHS and RHS should have the same type");
249 assert(LHS->getType()->isIntOrIntVectorTy() &&
250 "LHS and RHS should be integers");
251
253 if (Result == NoCommonBitsSetResult::Known)
255
256 NoCommonBitsSetResult CommuteResult =
258 if (CommuteResult == NoCommonBitsSetResult::Known)
260
262 RHSCache.getKnownBits(SQ)))
264
268
270}
271
273 const WithCache<const Value *> &RHSCache,
274 const SimplifyQuery &SQ) {
275 NoCommonBitsSetResult Result =
276 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
277 return Result == NoCommonBitsSetResult::Known;
278}
279
281 return !I->user_empty() &&
282 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
283}
284
286 return !I->user_empty() && all_of(I->users(), [](const User *U) {
287 CmpPredicate P;
288 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
289 });
290}
291
293 bool OrZero, AssumptionCache *AC,
294 const Instruction *CtxI,
295 const DominatorTree *DT, bool UseInstrInfo,
296 unsigned Depth) {
297 return ::isKnownToBeAPowerOfTwo(
298 V, OrZero, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo),
299 Depth);
300}
301
302static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
303 const SimplifyQuery &Q, unsigned Depth);
304
306 unsigned Depth) {
307 return computeKnownBits(V, SQ, Depth).isNonNegative();
308}
309
311 unsigned Depth) {
312 if (auto *CI = dyn_cast<ConstantInt>(V))
313 return CI->getValue().isStrictlyPositive();
314
315 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
316 // this updated.
318 return Known.isNonNegative() &&
319 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
320}
321
323 unsigned Depth) {
324 return computeKnownBits(V, SQ, Depth).isNegative();
325}
326
327static bool isKnownNonEqual(const Value *V1, const Value *V2,
328 const APInt &DemandedElts, const SimplifyQuery &Q,
329 unsigned Depth);
330
331static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
332 const Value *RHS);
333
334bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
335 const SimplifyQuery &Q, unsigned Depth) {
336 // We don't support looking through casts.
337 if (V1 == V2 || V1->getType() != V2->getType())
338 return false;
339 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
340 APInt DemandedElts =
341 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
342 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
343}
344
345bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
346 const SimplifyQuery &SQ, unsigned Depth) {
347 KnownBits Known(Mask.getBitWidth());
349 return Mask.isSubsetOf(Known.Zero);
350}
351
352static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
353 const SimplifyQuery &Q, unsigned Depth);
354
355static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
356 unsigned Depth = 0) {
357 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
358 APInt DemandedElts =
359 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
360 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
361}
362
363unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
364 AssumptionCache *AC, const Instruction *CtxI,
365 const DominatorTree *DT, bool UseInstrInfo,
366 unsigned Depth) {
367 return ::ComputeNumSignBits(
368 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
369}
370
372 AssumptionCache *AC,
373 const Instruction *CtxI,
374 const DominatorTree *DT,
375 unsigned Depth) {
376 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CtxI, DT, Depth);
377 return V->getType()->getScalarSizeInBits() - SignBits + 1;
378}
379
380/// Try to detect the lerp pattern: a * (b - c) + c * d
381/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
382///
383/// In that particular case, we can use the following chain of reasoning:
384///
385/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
386///
387/// Since that is true for arbitrary a, b, c and d within our constraints, we
388/// can conclude that:
389///
390/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
391///
392/// Considering that any result of the lerp would be less or equal to U, it
393/// would have at least the number of leading 0s as in U.
394///
395/// While being quite a specific situation, it is fairly common in computer
396/// graphics in the shape of alpha blending.
397///
398/// Modifies given KnownOut in-place with the inferred information.
399static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
400 const APInt &DemandedElts,
401 KnownBits &KnownOut,
402 const SimplifyQuery &Q,
403 unsigned Depth) {
404
405 Type *Ty = Op0->getType();
406 const unsigned BitWidth = Ty->getScalarSizeInBits();
407
408 // Only handle scalar types for now
409 if (Ty->isVectorTy())
410 return;
411
412 // Try to match: a * (b - c) + c * d.
413 // When a == 1 => A == nullptr, the same applies to d/D as well.
414 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
415 const Instruction *SubBC = nullptr;
416
417 const auto MatchSubBC = [&]() {
418 // (b - c) can have two forms that interest us:
419 //
420 // 1. sub nuw %b, %c
421 // 2. xor %c, %b
422 //
423 // For the first case, nuw flag guarantees our requirement b >= c.
424 //
425 // The second case might happen when the analysis can infer that b is a mask
426 // for c and we can transform sub operation into xor (that is usually true
427 // for constant b's). Even though xor is symmetrical, canonicalization
428 // ensures that the constant will be the RHS. We have additional checks
429 // later on to ensure that this xor operation is equivalent to subtraction.
431 m_Xor(m_Value(C), m_Value(B))));
432 };
433
434 const auto MatchASubBC = [&]() {
435 // Cases:
436 // - a * (b - c)
437 // - (b - c) * a
438 // - (b - c) <- a implicitly equals 1
439 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
440 };
441
442 const auto MatchCD = [&]() {
443 // Cases:
444 // - d * c
445 // - c * d
446 // - c <- d implicitly equals 1
448 };
449
450 const auto Match = [&](const Value *LHS, const Value *RHS) {
451 // We do use m_Specific(C) in MatchCD, so we have to make sure that
452 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
453 // has to evaluate first and return true.
454 //
455 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
456 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
457 };
458
459 if (!Match(Op0, Op1) && !Match(Op1, Op0))
460 return;
461
462 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
463 // For some of the values we use the convention of leaving
464 // it nullptr to signify an implicit constant 1.
465 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
467 };
468
469 // Check that all operands are non-negative
470 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
471 if (!KnownA.isNonNegative())
472 return;
473
474 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
475 if (!KnownD.isNonNegative())
476 return;
477
478 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
479 if (!KnownB.isNonNegative())
480 return;
481
482 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
483 if (!KnownC.isNonNegative())
484 return;
485
486 // If we matched subtraction as xor, we need to actually check that xor
487 // is semantically equivalent to subtraction.
488 //
489 // For that to be true, b has to be a mask for c or that b's known
490 // ones cover all known and possible ones of c.
491 if (SubBC->getOpcode() == Instruction::Xor &&
492 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
493 return;
494
495 const APInt MaxA = KnownA.getMaxValue();
496 const APInt MaxD = KnownD.getMaxValue();
497 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
498 const APInt MaxB = KnownB.getMaxValue();
499
500 // We can't infer leading zeros info if the upper-bound estimate wraps.
501 bool Overflow;
502 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
503
504 if (Overflow)
505 return;
506
507 // If we know that x <= y and both are positive than x has at least the same
508 // number of leading zeros as y.
509 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
510 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
511}
512
513static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
514 bool NSW, bool NUW,
515 const APInt &DemandedElts,
516 KnownBits &KnownOut, KnownBits &Known2,
517 const SimplifyQuery &Q, unsigned Depth) {
518 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
519
520 // If one operand is unknown and we have no nowrap information,
521 // the result will be unknown independently of the second operand.
522 if (KnownOut.isUnknown() && !NSW && !NUW)
523 return;
524
525 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
526 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
527
528 if (!Add && NSW && !KnownOut.isNonNegative() &&
530 .value_or(false) ||
531 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
532 KnownOut.makeNonNegative();
533
534 if (Add)
535 // Try to match lerp pattern and combine results
536 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
537}
538
539static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
540 bool NUW, const APInt &DemandedElts,
541 KnownBits &Known, KnownBits &Known2,
542 const SimplifyQuery &Q, unsigned Depth) {
543 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
544 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
545
546 bool isKnownNegative = false;
547 bool isKnownNonNegative = false;
548 // If the multiplication is known not to overflow, compute the sign bit.
549 if (NSW) {
550 if (Op0 == Op1) {
551 // The product of a number with itself is non-negative.
552 isKnownNonNegative = true;
553 } else {
554 bool isKnownNonNegativeOp1 = Known.isNonNegative();
555 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
556 bool isKnownNegativeOp1 = Known.isNegative();
557 bool isKnownNegativeOp0 = Known2.isNegative();
558 // The product of two numbers with the same sign is non-negative.
559 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
560 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
561 if (!isKnownNonNegative && NUW) {
562 // mul nuw nsw with a factor > 1 is non-negative.
563 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
564 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
565 KnownBits::sgt(Known2, One).value_or(false);
566 }
567
568 // The product of a negative number and a non-negative number is either
569 // negative or zero.
572 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
573 Known2.isNonZero()) ||
574 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
575 }
576 }
577
578 bool SelfMultiply = Op0 == Op1;
579 if (SelfMultiply)
580 SelfMultiply &=
581 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
582 Known = KnownBits::mul(Known, Known2, SelfMultiply);
583
584 if (SelfMultiply) {
585 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
586 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
587 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
588
589 if (OutValidBits < TyBits) {
590 APInt KnownZeroMask =
591 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
592 Known.Zero |= KnownZeroMask;
593 }
594 }
595
596 // Only make use of no-wrap flags if we failed to compute the sign bit
597 // directly. This matters if the multiplication always overflows, in
598 // which case we prefer to follow the result of the direct computation,
599 // though as the program is invoking undefined behaviour we can choose
600 // whatever we like here.
601 if (isKnownNonNegative && !Known.isNegative())
602 Known.makeNonNegative();
603 else if (isKnownNegative && !Known.isNonNegative())
604 Known.makeNegative();
605}
606
608 KnownBits &Known) {
609 unsigned BitWidth = Known.getBitWidth();
610 unsigned NumRanges = Ranges.getNumOperands() / 2;
611 assert(NumRanges >= 1);
612
613 Known.setAllConflict();
614
615 for (unsigned i = 0; i < NumRanges; ++i) {
617 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
619 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
620 ConstantRange Range(Lower->getValue(), Upper->getValue());
621 // BitWidth must equal the Ranges BitWidth for the correct number of high
622 // bits to be set.
623 assert(BitWidth == Range.getBitWidth() &&
624 "Known bit width must match range bit width!");
625
626 // The first CommonPrefixBits of all values in Range are equal.
627 unsigned CommonPrefixBits =
628 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
629 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
630 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
631 Known.One &= UnsignedMax & Mask;
632 Known.Zero &= ~UnsignedMax & Mask;
633 }
634}
635
636static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
637 // The instruction defining an assumption's condition itself is always
638 // considered ephemeral to that assumption (even if it has other
639 // non-ephemeral users). See r246696's test case for an example.
640 if (is_contained(I->operands(), E))
641 return true;
642
643 const auto *EI = dyn_cast<Instruction>(E);
644 if (!EI)
645 return false;
646
647 if (EI == I)
648 return true;
649
652 Visited.insert(EI);
653 WorkList.push_back(EI);
654 bool ReachesI = false;
655 while (!WorkList.empty()) {
656 const Instruction *V = WorkList.pop_back_val();
657 for (const User *U : V->users()) {
658 const auto *UI = cast<Instruction>(U);
659 if (UI == I) {
660 ReachesI = true;
661 continue;
662 }
663 if (UI->mayHaveSideEffects() || UI->isTerminator())
664 return false;
665 if (Visited.insert(UI).second)
666 WorkList.push_back(UI);
667 }
668 }
669 return ReachesI;
670}
671
672// Is this an intrinsic that cannot be speculated but also cannot trap?
674 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
675 return CI->isAssumeLikeIntrinsic();
676
677 return false;
678}
679
681 const Instruction *CtxI,
682 const DominatorTree *DT,
683 bool AllowEphemerals) {
684 // There are two restrictions on the use of an assume:
685 // 1. The assume must dominate the context (or the control flow must
686 // reach the assume whenever it reaches the context).
687 // 2. The context must not be in the assume's set of ephemeral values
688 // (otherwise we will use the assume to prove that the condition
689 // feeding the assume is trivially true, thus causing the removal of
690 // the assume).
691
692 if (Inv->getParent() == CtxI->getParent()) {
693 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
694 // in the BB.
695 if (Inv->comesBefore(CtxI))
696 return true;
697
698 // Don't let an assume affect itself - this would cause the problems
699 // `isEphemeralValueOf` is trying to prevent, and it would also make
700 // the loop below go out of bounds.
701 if (!AllowEphemerals && Inv == CtxI)
702 return false;
703
704 // The context comes first, but they're both in the same block.
705 // Make sure there is nothing in between that might interrupt
706 // the control flow, not even CtxI itself.
707 // We limit the scan distance between the assume and its context instruction
708 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
709 // it can be adjusted if needed (could be turned into a cl::opt).
710 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
712 return false;
713
714 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
715 }
716
717 // Inv and CtxI are in different blocks.
718 if (DT) {
719 if (DT->dominates(Inv, CtxI))
720 return true;
721 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
722 Inv->getParent()->isEntryBlock()) {
723 // We don't have a DT, but this trivially dominates.
724 return true;
725 }
726
727 return false;
728}
729
732 unsigned &NumChecked) {
733 for (const Instruction &I : make_range(Begin, End)) {
734 if (NumChecked++ > MaxInstrsToCheckForFree)
735 return false;
736 if (auto *CB = dyn_cast<CallBase>(&I)) {
737 if (!CB->hasFnAttr(Attribute::NoFree))
738 return false;
739 } else if (I.maySynchronize()) {
740 return false;
741 }
742 }
743 return true;
744}
745
747 const Instruction *CtxI,
748 const DominatorTree *DT) {
749 const BasicBlock *CtxBB = CtxI->getParent();
750 const BasicBlock *AssumeBB = Assume->getParent();
751 unsigned NumChecked = 0;
752 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
753 if (CtxBB == AssumeBB) {
754 if (Assume != CtxI && !Assume->comesBefore(CtxI))
755 return false;
756 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
757 }
758 if (DT && !DT->dominates(Assume, CtxI))
759 return false;
760 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
761 return false;
762 if (pred_empty(CtxBB))
763 return false;
764
765 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
766 // backedges returning to CtxBB are enqueued and checked correctly.
769 while (!Worklist.empty()) {
770 const BasicBlock *CurBB = Worklist.pop_back_val();
771 if (!Visited.insert(CurBB).second)
772 continue;
773
774 if (CurBB == AssumeBB) {
775 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
776 return false;
777 continue;
778 }
779 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
780 "Blocks between Assume and CtxI must be dominated by AssumeBB");
781
782 if (pred_empty(CurBB))
783 return false;
784
785 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
786 // instructions from CtxIter to the end of CtxBB (instructions before
787 // CtxIter were checked above). Otherwise, check the entire block.
788 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
789 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
790 return false;
791 append_range(Worklist, predecessors(CurBB));
792 }
793 return true;
794}
795
796// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
797// we still have enough information about `RHS` to conclude non-zero. For
798// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
799// so the extra compile time may not be worth it, but possibly a second API
800// should be created for use outside of loops.
801static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
802 // v u> y implies v != 0.
803 if (Pred == ICmpInst::ICMP_UGT)
804 return true;
805
806 // Special-case v != 0 to also handle v != null.
807 if (Pred == ICmpInst::ICMP_NE)
808 return match(RHS, m_Zero());
809
810 // All other predicates - rely on generic ConstantRange handling.
811 const APInt *C;
812 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
813 if (match(RHS, m_APInt(C))) {
815 return !TrueValues.contains(Zero);
816 }
817
819 if (VC == nullptr)
820 return false;
821
822 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
823 ++ElemIdx) {
825 Pred, VC->getElementAsAPInt(ElemIdx));
826 if (TrueValues.contains(Zero))
827 return false;
828 }
829 return true;
830}
831
832static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
833 Value *&ValOut, Instruction *&CtxIOut,
834 const PHINode **PhiOut = nullptr) {
835 ValOut = U->get();
836 if (ValOut == PHI)
837 return;
838 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
839 if (PhiOut)
840 *PhiOut = PHI;
841 Value *V;
842 // If the Use is a select of this phi, compute analysis on other arm to break
843 // recursion.
844 // TODO: Min/Max
845 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
846 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
847 ValOut = V;
848
849 // Same for select, if this phi is 2-operand phi, compute analysis on other
850 // incoming value to break recursion.
851 // TODO: We could handle any number of incoming edges as long as we only have
852 // two unique values.
853 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
854 IncPhi && IncPhi->getNumIncomingValues() == 2) {
855 for (int Idx = 0; Idx < 2; ++Idx) {
856 if (IncPhi->getIncomingValue(Idx) == PHI) {
857 ValOut = IncPhi->getIncomingValue(1 - Idx);
858 if (PhiOut)
859 *PhiOut = IncPhi;
860 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
861 break;
862 }
863 }
864 }
865}
866
867static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
868 // Use of assumptions is context-sensitive. If we don't have a context, we
869 // cannot use them!
870 if (!Q.AC || !Q.CtxI)
871 return false;
872
873 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
874 if (!Elem.Assume)
875 continue;
876
877 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
878 assert(I->getFunction() == Q.CtxI->getFunction() &&
879 "Got assumption for the wrong function!");
880
881 if (Elem.Index != AssumptionCache::ExprResultIdx) {
883 I->getOperandBundleAt(Elem.Index)) &&
885 return true;
886 continue;
887 }
888
889 // Warning: This loop can end up being somewhat performance sensitive.
890 // We're running this loop for once for each value queried resulting in a
891 // runtime of ~O(#assumes * #values).
892
893 if (match(I->getArgOperand(0), m_Trunc(m_Specific(V))) &&
895 return true;
896
897 Value *RHS;
898 CmpPredicate Pred;
899 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
900 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
901 continue;
902
904 return true;
905 }
906
907 return false;
908}
909
912 const SimplifyQuery &Q) {
913 if (RHS->getType()->isPointerTy()) {
914 // Handle comparison of pointer to null explicitly, as it will not be
915 // covered by the m_APInt() logic below.
916 if (LHS == V && match(RHS, m_Zero())) {
917 switch (Pred) {
919 Known.setAllZero();
920 break;
923 Known.makeNonNegative();
924 break;
926 Known.makeNegative();
927 break;
928 default:
929 break;
930 }
931 }
932 return;
933 }
934
935 unsigned BitWidth = Known.getBitWidth();
936 auto m_V =
938
939 Value *Y;
940 const APInt *Mask, *C;
941 if (!match(RHS, m_APInt(C)))
942 return;
943
944 uint64_t ShAmt;
945 switch (Pred) {
947 // assume(V = C)
948 if (match(LHS, m_V)) {
949 Known = Known.unionWith(KnownBits::makeConstant(*C));
950 // assume(V & Mask = C)
951 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
952 // For one bits in Mask, we can propagate bits from C to V.
953 Known.One |= *C;
954 if (match(Y, m_APInt(Mask)))
955 Known.Zero |= ~*C & *Mask;
956 // assume(V | Mask = C)
957 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
958 // For zero bits in Mask, we can propagate bits from C to V.
959 Known.Zero |= ~*C;
960 if (match(Y, m_APInt(Mask)))
961 Known.One |= *C & ~*Mask;
962 // assume(V << ShAmt = C)
963 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
964 ShAmt < BitWidth) {
965 // For those bits in C that are known, we can propagate them to known
966 // bits in V shifted to the right by ShAmt.
968 RHSKnown >>= ShAmt;
969 Known = Known.unionWith(RHSKnown);
970 // assume(V >> ShAmt = C)
971 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
972 ShAmt < BitWidth) {
973 // For those bits in RHS that are known, we can propagate them to known
974 // bits in V shifted to the right by C.
976 RHSKnown <<= ShAmt;
977 Known = Known.unionWith(RHSKnown);
978 }
979 break;
980 case ICmpInst::ICMP_NE: {
981 // assume (V & B != 0) where B is a power of 2
982 const APInt *BPow2;
983 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
984 Known.One |= *BPow2;
985 break;
986 }
987 default: {
988 const APInt *Offset = nullptr;
989 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
991 if (Offset)
992 LHSRange = LHSRange.sub(*Offset);
993 Known = Known.unionWith(LHSRange.toKnownBits());
994 }
995 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
996 // X & Y u> C -> X u> C && Y u> C
997 // X nuw- Y u> C -> X u> C
998 if (match(LHS, m_c_And(m_V, m_Value())) ||
999 match(LHS, m_NUWSub(m_V, m_Value())))
1000 Known.One.setHighBits(
1001 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
1002 }
1003 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1004 // X | Y u< C -> X u< C && Y u< C
1005 // X nuw+ Y u< C -> X u< C && Y u< C
1006 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1007 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1008 Known.Zero.setHighBits(
1009 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1010 }
1011 }
1012 } break;
1013 }
1014}
1015
1018 const SimplifyQuery &SQ, bool Invert) {
1019 ICmpInst::Predicate Pred =
1020 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1021 Value *LHS = Cmp->getOperand(0);
1022 Value *RHS = Cmp->getOperand(1);
1023
1024 // Handle icmp pred (trunc V), C
1025 if (match(LHS, m_Trunc(m_Specific(V)))) {
1026 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1027 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1029 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1030 else
1031 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1032 return;
1033 }
1034
1035 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1036}
1037
1039 KnownBits &Known, const SimplifyQuery &SQ,
1040 bool Invert, unsigned Depth) {
1041 Value *A, *B;
1044 KnownBits Known2(Known.getBitWidth());
1045 KnownBits Known3(Known.getBitWidth());
1046 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1047 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1048 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1050 Known2 = Known2.unionWith(Known3);
1051 else
1052 Known2 = Known2.intersectWith(Known3);
1053 Known = Known.unionWith(Known2);
1054 return;
1055 }
1056
1057 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1058 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1059 return;
1060 }
1061
1062 if (match(Cond, m_Trunc(m_Specific(V)))) {
1063 KnownBits DstKnown(1);
1064 if (Invert) {
1065 DstKnown.setAllZero();
1066 } else {
1067 DstKnown.setAllOnes();
1068 }
1070 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1071 return;
1072 }
1073 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1074 return;
1075 }
1076
1078 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1079}
1080
1082 const SimplifyQuery &Q, unsigned Depth) {
1083 // Handle injected condition.
1084 if (Q.CC && Q.CC->AffectedValues.contains(V))
1086
1087 if (!Q.CtxI)
1088 return;
1089
1090 if (Q.DC && Q.DT) {
1091 // Handle dominating conditions.
1092 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1093 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1094 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1095 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1096 /*Invert*/ false, Depth);
1097
1098 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1099 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1100 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1101 /*Invert*/ true, Depth);
1102 }
1103
1104 if (Known.hasConflict())
1105 Known.resetAll();
1106 }
1107
1108 if (!Q.AC)
1109 return;
1110
1111 unsigned BitWidth = Known.getBitWidth();
1112
1113 // Note that the patterns below need to be kept in sync with the code
1114 // in AssumptionCache::updateAffectedValues.
1115
1116 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1117 if (!Elem.Assume)
1118 continue;
1119
1120 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1121 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1122 "Got assumption for the wrong function!");
1123
1124 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1125 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1126 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1127 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1128 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1130 Known.Zero |= (*Alignment - 1) & ~*Offset;
1131 Known.One |= (*Alignment - 1) & *Offset;
1132 }
1133 }
1134 continue;
1135 }
1136
1137 // Warning: This loop can end up being somewhat performance sensitive.
1138 // We're running this loop for once for each value queried resulting in a
1139 // runtime of ~O(#assumes * #values).
1140
1141 Value *Arg = I->getArgOperand(0);
1142
1143 if (Arg == V && isValidAssumeForContext(I, Q)) {
1144 assert(BitWidth == 1 && "assume operand is not i1?");
1145 (void)BitWidth;
1146 Known.setAllOnes();
1147 return;
1148 }
1149 if (match(Arg, m_Not(m_Specific(V))) &&
1151 assert(BitWidth == 1 && "assume operand is not i1?");
1152 (void)BitWidth;
1153 Known.setAllZero();
1154 return;
1155 }
1156 auto *Trunc = dyn_cast<TruncInst>(Arg);
1157 if (Trunc && Trunc->getOperand(0) == V &&
1159 if (Trunc->hasNoUnsignedWrap()) {
1161 return;
1162 }
1163 Known.One.setBit(0);
1164 return;
1165 }
1166
1167 // The remaining tests are all recursive, so bail out if we hit the limit.
1169 continue;
1170
1171 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1172 if (!Cmp)
1173 continue;
1174
1175 if (!isValidAssumeForContext(I, Q))
1176 continue;
1177
1178 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1179 }
1180
1181 // Conflicting assumption: Undefined behavior will occur on this execution
1182 // path.
1183 if (Known.hasConflict())
1184 Known.resetAll();
1185}
1186
1187/// Compute known bits from a shift operator, including those with a
1188/// non-constant shift amount. Known is the output of this function. Known2 is a
1189/// pre-allocated temporary with the same bit width as Known and on return
1190/// contains the known bit of the shift value source. KF is an
1191/// operator-specific function that, given the known-bits and a shift amount,
1192/// compute the implied known-bits of the shift operator's result respectively
1193/// for that shift amount. The results from calling KF are conservatively
1194/// combined for all permitted shift amounts.
1196 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1197 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1198 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1199 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1200 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1201 // To limit compile-time impact, only query isKnownNonZero() if we know at
1202 // least something about the shift amount.
1203 bool ShAmtNonZero =
1204 Known.isNonZero() ||
1205 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1206 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1207 Known = KF(Known2, Known, ShAmtNonZero);
1208}
1209
1210static KnownBits
1211getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1212 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1213 const SimplifyQuery &Q, unsigned Depth) {
1214 unsigned BitWidth = KnownLHS.getBitWidth();
1215 KnownBits KnownOut(BitWidth);
1216 bool IsAnd = false;
1217 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1218 Value *X = nullptr, *Y = nullptr;
1219
1220 switch (I->getOpcode()) {
1221 case Instruction::And:
1222 KnownOut = KnownLHS & KnownRHS;
1223 IsAnd = true;
1224 // and(x, -x) 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: instcombine often reassociates independent `and` which can hide
1228 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1229 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1230 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1231 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1232 KnownOut = KnownLHS.blsi();
1233 else
1234 KnownOut = KnownRHS.blsi();
1235 }
1236 break;
1237 case Instruction::Or:
1238 KnownOut = KnownLHS | KnownRHS;
1239 break;
1240 case Instruction::Xor:
1241 KnownOut = KnownLHS ^ KnownRHS;
1242 // xor(x, x-1) is common idioms that will clear all but lowest set
1243 // bit. If we have a single known bit in x, we can clear all bits
1244 // above it.
1245 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1246 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1247 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1248 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1249 if (HasKnownOne &&
1251 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1252 KnownOut = XBits.blsmsk();
1253 }
1254 break;
1255 default:
1256 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1257 }
1258
1259 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1260 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1261 // here we handle the more general case of adding any odd number by
1262 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1263 // TODO: This could be generalized to clearing any bit set in y where the
1264 // following bit is known to be unset in y.
1265 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1269 KnownBits KnownY(BitWidth);
1270 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1271 if (KnownY.countMinTrailingOnes() > 0) {
1272 if (IsAnd)
1273 KnownOut.Zero.setBit(0);
1274 else
1275 KnownOut.One.setBit(0);
1276 }
1277 }
1278 return KnownOut;
1279}
1280
1282 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1283 unsigned Depth,
1284 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1285 KnownBitsFunc) {
1286 APInt DemandedEltsLHS, DemandedEltsRHS;
1288 DemandedElts, DemandedEltsLHS,
1289 DemandedEltsRHS);
1290
1291 const auto ComputeForSingleOpFunc =
1292 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1293 return KnownBitsFunc(
1294 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1295 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1296 };
1297
1298 if (DemandedEltsRHS.isZero())
1299 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1300 if (DemandedEltsLHS.isZero())
1301 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1302
1303 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1304 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1305}
1306
1307// Public so this can be used in `SimplifyDemandedUseBits`.
1309 const KnownBits &KnownLHS,
1310 const KnownBits &KnownRHS,
1311 const SimplifyQuery &SQ,
1312 unsigned Depth) {
1313 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1314 APInt DemandedElts =
1315 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1316
1317 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1318 Depth);
1319}
1320
1322 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1323 // Without vscale_range, we only know that vscale is non-zero.
1324 if (!Attr.isValid())
1326
1327 unsigned AttrMin = Attr.getVScaleRangeMin();
1328 // Minimum is larger than vscale width, result is always poison.
1329 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1330 return ConstantRange::getEmpty(BitWidth);
1331
1332 APInt Min(BitWidth, AttrMin);
1333 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1334 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1336
1337 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1338}
1339
1340/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1341/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1342/// target's VLEN range. Callers must ensure the target is RISC-V.
1343static bool isReadVLENB(const IntrinsicInst &II) {
1344 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1345 if (!MAV)
1346 return false;
1347 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1348 if (!MD || MD->getNumOperands() != 1)
1349 return false;
1350 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1351 return RegName && RegName->getString() == "vlenb";
1352}
1353
1354/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1355/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1356/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1357/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1358/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1359/// attribute, when present, pins the subtarget's VLEN in units of
1360/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1361/// RVVBytesPerBlock.
1363 unsigned Width) {
1364 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1365 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1366
1367 const Function *F = II.getFunction();
1368 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1369 ConstantRange VScale = getVScaleRange(F, Width);
1370 Range = Range.intersectWith(
1372 }
1373 return Range;
1374}
1375
1377 Value *Arm, bool Invert,
1378 const SimplifyQuery &Q, unsigned Depth) {
1379 // If we have a constant arm, we are done.
1380 if (Known.isConstant())
1381 return;
1382
1383 // See what condition implies about the bits of the select arm.
1384 KnownBits CondRes(Known.getBitWidth());
1385 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1386 // If we don't get any information from the condition, no reason to
1387 // proceed.
1388 if (CondRes.isUnknown())
1389 return;
1390
1391 // We can have conflict if the condition is dead. I.e if we have
1392 // (x | 64) < 32 ? (x | 64) : y
1393 // we will have conflict at bit 6 from the condition/the `or`.
1394 // In that case just return. Its not particularly important
1395 // what we do, as this select is going to be simplified soon.
1396 CondRes = CondRes.unionWith(Known);
1397 if (CondRes.hasConflict())
1398 return;
1399
1400 // Finally make sure the information we found is valid. This is relatively
1401 // expensive so it's left for the very end.
1402 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1403 return;
1404
1405 // Finally, we know we get information from the condition and its valid,
1406 // so return it.
1407 Known = std::move(CondRes);
1408}
1409
1410// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1411// Returns the input and lower/upper bounds.
1412static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1413 const APInt *&CLow, const APInt *&CHigh) {
1415 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1416 "Input should be a Select!");
1417
1418 const Value *LHS = nullptr, *RHS = nullptr;
1420 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1421 return false;
1422
1423 if (!match(RHS, m_APInt(CLow)))
1424 return false;
1425
1426 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1428 if (getInverseMinMaxFlavor(SPF) != SPF2)
1429 return false;
1430
1431 if (!match(RHS2, m_APInt(CHigh)))
1432 return false;
1433
1434 if (SPF == SPF_SMIN)
1435 std::swap(CLow, CHigh);
1436
1437 In = LHS2;
1438 return CLow->sle(*CHigh);
1439}
1440
1442 const APInt *&CLow,
1443 const APInt *&CHigh) {
1444 assert((II->getIntrinsicID() == Intrinsic::smin ||
1445 II->getIntrinsicID() == Intrinsic::smax) &&
1446 "Must be smin/smax");
1447
1448 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1449 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1450 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1451 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1452 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1453 return false;
1454
1455 if (II->getIntrinsicID() == Intrinsic::smin)
1456 std::swap(CLow, CHigh);
1457 return CLow->sle(*CHigh);
1458}
1459
1461 KnownBits &Known) {
1462 const APInt *CLow, *CHigh;
1463 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1464 Known = Known.unionWith(
1465 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1466}
1467
1469 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1470 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1471 unsigned Depth) {
1472 // Change the context instruction to the "edge" that flows into the phi. This
1473 // is important because that is where the value is actually "evaluated" even
1474 // though it is used later somewhere else. (see also D69571).
1476 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1477
1478 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1479 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1480
1481 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1482 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1483}
1484
1486 const APInt &DemandedElts,
1488 const SimplifyQuery &Q,
1489 unsigned Depth) {
1490 unsigned BitWidth = Known.getBitWidth();
1491
1492 KnownBits Known2(BitWidth);
1493 switch (I->getOpcode()) {
1494 default: break;
1495 case Instruction::Load:
1496 if (MDNode *MD =
1497 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1499 break;
1500 case Instruction::And:
1501 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1502 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1503
1504 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1505 break;
1506 case Instruction::Or:
1507 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1508 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1509
1510 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1511 break;
1512 case Instruction::Xor:
1513 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1514 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1515
1516 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1517 break;
1518 case Instruction::Mul: {
1521 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1522 DemandedElts, Known, Known2, Q, Depth);
1523 break;
1524 }
1525 case Instruction::UDiv: {
1526 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1527 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1528 Known =
1530 break;
1531 }
1532 case Instruction::SDiv: {
1533 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1534 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1535 Known =
1537 break;
1538 }
1539 case Instruction::Select: {
1540 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1541 KnownBits Res(Known.getBitWidth());
1542 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1543 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1544 return Res;
1545 };
1546 // Only known if known in both the LHS and RHS.
1547 Known =
1548 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1549 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1550 break;
1551 }
1552 case Instruction::FPToSI: {
1553 // fptosi is poison if the rounded value doesn't fit in the result type,
1554 // so we can assume the conversion is well-defined and rounds towards
1555 // zero. +-Inf can never fit in an integer type, so it is always poison,
1556 // like NaN. Negative subnormals and negative zero round to 0. That
1557 // leaves negative normals as the only class that can produce a defined
1558 // negative result.
1559 KnownFPClass SrcFPClass = computeKnownFPClass(
1560 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1561 if (SrcFPClass.isKnownNever(fcNegNormal))
1562 Known.makeNonNegative();
1563 break;
1564 }
1565 case Instruction::FPTrunc:
1566 case Instruction::FPExt:
1567 case Instruction::FPToUI:
1568 case Instruction::SIToFP:
1569 case Instruction::UIToFP:
1570 break; // Can't work with floating point.
1571 case Instruction::PtrToInt:
1572 case Instruction::PtrToAddr:
1573 case Instruction::IntToPtr:
1574 // Fall through and handle them the same as zext/trunc.
1575 [[fallthrough]];
1576 case Instruction::ZExt:
1577 case Instruction::Trunc: {
1578 Type *SrcTy = I->getOperand(0)->getType();
1579
1580 unsigned SrcBitWidth;
1581 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1582 // which fall through here.
1583 Type *ScalarTy = SrcTy->getScalarType();
1584 SrcBitWidth = ScalarTy->isPointerTy() ?
1585 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1586 Q.DL.getTypeSizeInBits(ScalarTy);
1587
1588 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1589 Known = Known.anyextOrTrunc(SrcBitWidth);
1590 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1591 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1592 Inst && Inst->hasNonNeg() && !Known.isNegative())
1593 Known.makeNonNegative();
1594 Known = Known.zextOrTrunc(BitWidth);
1595 break;
1596 }
1597 case Instruction::BitCast: {
1598 Type *SrcTy = I->getOperand(0)->getType();
1599 if (SrcTy->isIntOrPtrTy() &&
1600 // TODO: For now, not handling conversions like:
1601 // (bitcast i64 %x to <2 x i32>)
1602 !I->getType()->isVectorTy()) {
1603 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1604 break;
1605 }
1606
1607 const Value *V;
1608 // Handle bitcast from floating point to integer.
1609 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1610 V->getType()->isFPOrFPVectorTy()) {
1611 Type *FPType = V->getType()->getScalarType();
1612 KnownFPClass Result =
1613 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1614
1615 Known = Result.toKnownBits(FPType->getFltSemantics());
1616
1617 break;
1618 }
1619
1620 // Handle cast from vector integer type to scalar or vector integer.
1621 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1622 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1623 !I->getType()->isIntOrIntVectorTy() ||
1624 isa<ScalableVectorType>(I->getType()))
1625 break;
1626
1627 unsigned NumElts = DemandedElts.getBitWidth();
1628 bool IsLE = Q.DL.isLittleEndian();
1629 // Look through a cast from narrow vector elements to wider type.
1630 // Examples: v4i32 -> v2i64, v3i8 -> v24
1631 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1632 if (BitWidth % SubBitWidth == 0) {
1633 // Known bits are automatically intersected across demanded elements of a
1634 // vector. So for example, if a bit is computed as known zero, it must be
1635 // zero across all demanded elements of the vector.
1636 //
1637 // For this bitcast, each demanded element of the output is sub-divided
1638 // across a set of smaller vector elements in the source vector. To get
1639 // the known bits for an entire element of the output, compute the known
1640 // bits for each sub-element sequentially. This is done by shifting the
1641 // one-set-bit demanded elements parameter across the sub-elements for
1642 // consecutive calls to computeKnownBits. We are using the demanded
1643 // elements parameter as a mask operator.
1644 //
1645 // The known bits of each sub-element are then inserted into place
1646 // (dependent on endian) to form the full result of known bits.
1647 unsigned SubScale = BitWidth / SubBitWidth;
1648 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1649 for (unsigned i = 0; i != NumElts; ++i) {
1650 if (DemandedElts[i])
1651 SubDemandedElts.setBit(i * SubScale);
1652 }
1653
1654 KnownBits KnownSrc(SubBitWidth);
1655 for (unsigned i = 0; i != SubScale; ++i) {
1656 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1657 Depth + 1);
1658 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1659 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1660 }
1661 }
1662 // Look through a cast from wider vector elements to narrow type.
1663 // Examples: v2i64 -> v4i32
1664 if (SubBitWidth % BitWidth == 0) {
1665 unsigned SubScale = SubBitWidth / BitWidth;
1666 KnownBits KnownSrc(SubBitWidth);
1667 APInt SubDemandedElts =
1668 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1669 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1670 Depth + 1);
1671
1672 Known.setAllConflict();
1673 for (unsigned i = 0; i != NumElts; ++i) {
1674 if (DemandedElts[i]) {
1675 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1676 unsigned Offset = (Shifts % SubScale) * BitWidth;
1677 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1678 if (Known.isUnknown())
1679 break;
1680 }
1681 }
1682 }
1683 break;
1684 }
1685 case Instruction::SExt: {
1686 // Compute the bits in the result that are not present in the input.
1687 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1688
1689 Known = Known.trunc(SrcBitWidth);
1690 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1691 // If the sign bit of the input is known set or clear, then we know the
1692 // top bits of the result.
1693 Known = Known.sext(BitWidth);
1694 break;
1695 }
1696 case Instruction::Shl: {
1699 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1700 bool ShAmtNonZero) {
1701 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1702 };
1703 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1704 KF);
1705 // Trailing zeros of a right-shifted constant never decrease.
1706 const APInt *C;
1707 if (match(I->getOperand(0), m_APInt(C)))
1708 Known.Zero.setLowBits(C->countr_zero());
1709
1710 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1711 // lands at bit Y, when BitWidth is a power of 2.
1712 const APInt *YC;
1713 Value *X = I->getOperand(0);
1714 if (isPowerOf2_32(BitWidth) &&
1715 match(I->getOperand(1),
1717 m_SpecificInt(BitWidth - 1)))) &&
1718 YC->ult(BitWidth - 1)) {
1719 unsigned Y = YC->getZExtValue();
1720 Known.One.setBit(Y);
1721 Known.Zero.setBitsFrom(Y + 1);
1722 }
1723 break;
1724 }
1725 case Instruction::LShr: {
1726 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1727 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1728 bool ShAmtNonZero) {
1729 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1730 };
1731 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1732 KF);
1733 // Leading zeros of a left-shifted constant never decrease.
1734 const APInt *C;
1735 if (match(I->getOperand(0), m_APInt(C)))
1736 Known.Zero.setHighBits(C->countl_zero());
1737 break;
1738 }
1739 case Instruction::AShr: {
1740 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1741 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1742 bool ShAmtNonZero) {
1743 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1744 };
1745 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1746 KF);
1747 break;
1748 }
1749 case Instruction::Sub: {
1752 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1753 DemandedElts, Known, Known2, Q, Depth);
1754 break;
1755 }
1756 case Instruction::Add: {
1759 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1760 DemandedElts, Known, Known2, Q, Depth);
1761 break;
1762 }
1763 case Instruction::SRem:
1764 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1765 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1766 Known = KnownBits::srem(Known, Known2);
1767 break;
1768
1769 case Instruction::URem:
1770 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1771 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1772 Known = KnownBits::urem(Known, Known2);
1773 break;
1774 case Instruction::Alloca:
1775 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1776 break;
1777 case Instruction::GetElementPtr: {
1778 // Analyze all of the subscripts of this getelementptr instruction
1779 // to determine if we can prove known low zero bits.
1780 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1781 // Accumulate the constant indices in a separate variable
1782 // to minimize the number of calls to computeForAddSub.
1783 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1784 APInt AccConstIndices(IndexWidth, 0);
1785
1786 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1787 if (IndexWidth == BitWidth) {
1788 // Note that inbounds does *not* guarantee nsw for the addition, as only
1789 // the offset is signed, while the base address is unsigned.
1790 Known = KnownBits::add(Known, IndexBits);
1791 } else {
1792 // If the index width is smaller than the pointer width, only add the
1793 // value to the low bits.
1794 assert(IndexWidth < BitWidth &&
1795 "Index width can't be larger than pointer width");
1796 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1797 }
1798 };
1799
1801 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1802 // TrailZ can only become smaller, short-circuit if we hit zero.
1803 if (Known.isUnknown())
1804 break;
1805
1806 Value *Index = I->getOperand(i);
1807
1808 // Handle case when index is zero.
1809 Constant *CIndex = dyn_cast<Constant>(Index);
1810 if (CIndex && CIndex->isNullValue())
1811 continue;
1812
1813 if (StructType *STy = GTI.getStructTypeOrNull()) {
1814 // Handle struct member offset arithmetic.
1815
1816 assert(CIndex &&
1817 "Access to structure field must be known at compile time");
1818
1819 if (CIndex->getType()->isVectorTy())
1820 Index = CIndex->getSplatValue();
1821
1822 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1823 const StructLayout *SL = Q.DL.getStructLayout(STy);
1824 uint64_t Offset = SL->getElementOffset(Idx);
1825 AccConstIndices += Offset;
1826 continue;
1827 }
1828
1829 // Handle array index arithmetic.
1830 Type *IndexedTy = GTI.getIndexedType();
1831 if (!IndexedTy->isSized()) {
1832 Known.resetAll();
1833 break;
1834 }
1835
1836 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1837 uint64_t StrideInBytes = Stride.getKnownMinValue();
1838 if (!Stride.isScalable()) {
1839 // Fast path for constant offset.
1840 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1841 AccConstIndices +=
1842 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1843 continue;
1844 }
1845 }
1846
1847 KnownBits IndexBits =
1848 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1849 KnownBits ScalingFactor(IndexWidth);
1850 // Multiply by current sizeof type.
1851 // &A[i] == A + i * sizeof(*A[i]).
1852 if (Stride.isScalable()) {
1853 // For scalable types the only thing we know about sizeof is
1854 // that this is a multiple of the minimum size.
1855 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1856 } else {
1857 ScalingFactor =
1858 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1859 }
1860 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1861 }
1862 if (!Known.isUnknown() && !AccConstIndices.isZero())
1863 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1864 break;
1865 }
1866 case Instruction::PHI: {
1867 const PHINode *P = cast<PHINode>(I);
1868 BinaryOperator *BO = nullptr;
1869 Value *Start = nullptr, *Step = nullptr;
1870 KnownBits &KnownStart = Known2;
1871 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1872 // Handle the case of a simple two-predecessor recurrence PHI.
1873 // There's a lot more that could theoretically be done here, but
1874 // this is sufficient to catch some interesting cases.
1875 unsigned Opcode = BO->getOpcode();
1876
1877 switch (Opcode) {
1878 // If this is a shift recurrence, we know the bits being shifted in. We
1879 // can combine that with information about the start value of the
1880 // recurrence to conclude facts about the result. If this is a udiv
1881 // recurrence, we know that the result can never exceed either the
1882 // numerator or the start value, whichever is greater.
1883 case Instruction::LShr:
1884 case Instruction::AShr:
1885 case Instruction::Shl:
1886 case Instruction::UDiv:
1887 if (BO->getOperand(0) != I)
1888 break;
1889 [[fallthrough]];
1890
1891 // For a urem recurrence, the result can never exceed the start value. The
1892 // phi could either be the numerator or the denominator.
1893 case Instruction::URem: {
1894 // We have matched a recurrence of the form:
1895 // %iv = [R, %entry], [%iv.next, %backedge]
1896 // %iv.next = shift_op %iv, L
1897
1898 // Recurse with the phi context to avoid concern about whether facts
1899 // inferred hold at original context instruction. TODO: It may be
1900 // correct to use the original context. IF warranted, explore and
1901 // add sufficient tests to cover.
1903 RecQ.CtxI = P;
1904 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1905 switch (Opcode) {
1906 case Instruction::Shl:
1907 // A shl recurrence will only increase the tailing zeros
1908 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1909 break;
1910 case Instruction::LShr:
1911 case Instruction::UDiv:
1912 case Instruction::URem:
1913 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1914 // the start value.
1915 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1916 break;
1917 case Instruction::AShr:
1918 // An ashr recurrence will extend the initial sign bit
1919 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1920 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1921 break;
1922 }
1923 break;
1924 }
1925
1926 case Instruction::And: {
1927 // Bits that are zero in the start value stay zero, and bits that are
1928 // one in both the start value and the step stay one.
1929 KnownBits KnownStep(BitWidth);
1930 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1931 KnownStart, KnownStep, Q, Depth);
1932 Known.Zero |= KnownStart.Zero;
1933 Known.One |= KnownStart.One & KnownStep.One;
1934 break;
1935 }
1936
1937 case Instruction::Or: {
1938 // Bits that are zero in both the start value and the step stay zero,
1939 // and bits that are one in the start value stay one.
1940 KnownBits KnownStep(BitWidth);
1941 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1942 KnownStart, KnownStep, Q, Depth);
1943 Known.Zero |= KnownStart.Zero & KnownStep.Zero;
1944 Known.One |= KnownStart.One;
1945 break;
1946 }
1947
1948 // Check for operations that have the property that if
1949 // both their operands have low zero bits, the result
1950 // will have low zero bits.
1951 case Instruction::Add:
1952 case Instruction::Sub:
1953 case Instruction::Mul: {
1954 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1955 // zero bits.
1956 KnownBits KnownStep(BitWidth);
1957 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1958 KnownStart, KnownStep, Q, Depth);
1959
1960 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1961 KnownStep.countMinTrailingZeros()));
1962
1963 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1964 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1965 break;
1966
1967 switch (Opcode) {
1968 // If initial value of recurrence is nonnegative, and we are adding
1969 // a nonnegative number with nsw, the result can only be nonnegative
1970 // or poison value regardless of the number of times we execute the
1971 // add in phi recurrence. If initial value is negative and we are
1972 // adding a negative number with nsw, the result can only be
1973 // negative or poison value. Similar arguments apply to sub and mul.
1974 //
1975 // (add non-negative, non-negative) --> non-negative
1976 // (add negative, negative) --> negative
1977 case Instruction::Add: {
1978 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1979 Known.makeNonNegative();
1980 else if (KnownStart.isNegative() && KnownStep.isNegative())
1981 Known.makeNegative();
1982 break;
1983 }
1984
1985 // (sub nsw non-negative, negative) --> non-negative
1986 // (sub nsw negative, non-negative) --> negative
1987 case Instruction::Sub: {
1988 if (BO->getOperand(0) != I)
1989 break;
1990 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1991 Known.makeNonNegative();
1992 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1993 Known.makeNegative();
1994 break;
1995 }
1996
1997 // (mul nsw non-negative, non-negative) --> non-negative
1998 case Instruction::Mul:
1999 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2000 Known.makeNonNegative();
2001 break;
2002
2003 default:
2004 break;
2005 }
2006 break;
2007 }
2008
2009 default:
2010 break;
2011 }
2012 } else {
2013 IntrinsicInst *II = nullptr;
2014 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
2015 // %iv = [<Start>, %entry], [%iv.next, %backedge]
2016 //
2017 // %iv.next = <II>(%iv, <Step>)
2018 // or
2019 // %iv.next = <II>(<Step>, %iv)
2020 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
2021 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
2022 KnownBits KnownStep(BitWidth);
2024 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2025
2026 if (IntrinsicID == Intrinsic::umin) {
2027 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2028 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2029 KnownStep.countMinLeadingOnes()));
2030 } else {
2031 // umax
2032 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2033 KnownStep.countMinLeadingZeros()));
2034 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2035 }
2036 }
2037 }
2038 }
2039
2040 // Unreachable blocks may have zero-operand PHI nodes.
2041 if (P->getNumIncomingValues() == 0)
2042 break;
2043
2044 // Otherwise take the unions of the known bit sets of the operands,
2045 // taking conservative care to avoid excessive recursion.
2046 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2047 // Skip if every incoming value references to ourself.
2048 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2049 break;
2050
2051 Known.setAllConflict();
2052 for (const Use &U : P->operands()) {
2053 Value *IncValue;
2054 const PHINode *CtxPhi;
2055 Instruction *CtxI;
2056 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2057 // Skip direct self references.
2058 if (IncValue == P)
2059 continue;
2060
2061 // Change the context instruction to the "edge" that flows into the
2062 // phi. This is important because that is where the value is actually
2063 // "evaluated" even though it is used later somewhere else. (see also
2064 // D69571).
2066
2067 Known2 = KnownBits(BitWidth);
2068
2069 // Recurse, but cap the recursion to one level, because we don't
2070 // want to waste time spinning around in loops.
2071 // TODO: See if we can base recursion limiter on number of incoming phi
2072 // edges so we don't overly clamp analysis.
2073 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2075
2076 // See if we can further use a conditional branch into the phi
2077 // to help us determine the range of the value.
2078 if (!Known2.isConstant()) {
2079 CmpPredicate Pred;
2080 const APInt *RHSC;
2081 BasicBlock *TrueSucc, *FalseSucc;
2082 // TODO: Use RHS Value and compute range from its known bits.
2083 if (match(RecQ.CtxI,
2084 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2085 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2086 // Check for cases of duplicate successors.
2087 if ((TrueSucc == CtxPhi->getParent()) !=
2088 (FalseSucc == CtxPhi->getParent())) {
2089 // If we're using the false successor, invert the predicate.
2090 if (FalseSucc == CtxPhi->getParent())
2091 Pred = CmpInst::getInversePredicate(Pred);
2092 // Get the knownbits implied by the incoming phi condition.
2093 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2094 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2095 // We can have conflicts here if we are analyzing deadcode (its
2096 // impossible for us reach this BB based the icmp).
2097 if (KnownUnion.hasConflict()) {
2098 // No reason to continue analyzing in a known dead region, so
2099 // just resetAll and break. This will cause us to also exit the
2100 // outer loop.
2101 Known.resetAll();
2102 break;
2103 }
2104 Known2 = KnownUnion;
2105 }
2106 }
2107 }
2108
2109 Known = Known.intersectWith(Known2);
2110 // If all bits have been ruled out, there's no need to check
2111 // more operands.
2112 if (Known.isUnknown())
2113 break;
2114 }
2115 }
2116 break;
2117 }
2118 case Instruction::Call:
2119 case Instruction::Invoke: {
2120 // If range metadata is attached to this call, set known bits from that,
2121 // and then intersect with known bits based on other properties of the
2122 // function.
2123 if (MDNode *MD =
2124 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2126
2127 const auto *CB = cast<CallBase>(I);
2128
2129 if (std::optional<ConstantRange> Range = CB->getRange())
2130 Known = Known.unionWith(Range->toKnownBits());
2131
2132 if (const Value *RV = CB->getReturnedArgOperand()) {
2133 if (RV->getType() == I->getType()) {
2134 computeKnownBits(RV, Known2, Q, Depth + 1);
2135 Known = Known.unionWith(Known2);
2136 // If the function doesn't return properly for all input values
2137 // (e.g. unreachable exits) then there might be conflicts between the
2138 // argument value and the range metadata. Simply discard the known bits
2139 // in case of conflicts.
2140 if (Known.hasConflict())
2141 Known.resetAll();
2142 }
2143 }
2144 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2145 switch (II->getIntrinsicID()) {
2146 default:
2147 break;
2148 case Intrinsic::abs: {
2149 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2150 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2151 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2152 break;
2153 }
2154 case Intrinsic::bitreverse:
2155 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2156 Known = Known.unionWith(Known2.reverseBits());
2157 break;
2158 case Intrinsic::bswap:
2159 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2160 Known = Known.unionWith(Known2.byteSwap());
2161 break;
2162 case Intrinsic::ctlz: {
2163 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2164 // If we have a known 1, its position is our upper bound.
2165 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2166 // If this call is poison for 0 input, the result will be less than 2^n.
2167 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2168 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2169 unsigned LowBits = llvm::bit_width(PossibleLZ);
2170 Known.Zero.setBitsFrom(LowBits);
2171 break;
2172 }
2173 case Intrinsic::cttz: {
2174 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2175 // If we have a known 1, its position is our upper bound.
2176 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2177 // If this call is poison for 0 input, the result will be less than 2^n.
2178 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2179 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2180 unsigned LowBits = llvm::bit_width(PossibleTZ);
2181 Known.Zero.setBitsFrom(LowBits);
2182 break;
2183 }
2184 case Intrinsic::ctpop: {
2185 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2186 // We can bound the space the count needs. Also, bits known to be zero
2187 // can't contribute to the population.
2188 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2189 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2190 Known.Zero.setBitsFrom(LowBits);
2191 // TODO: we could bound KnownOne using the lower bound on the number
2192 // of bits which might be set provided by popcnt KnownOne2.
2193 break;
2194 }
2195 case Intrinsic::fshr:
2196 case Intrinsic::fshl: {
2197 const APInt *SA;
2198 if (!match(I->getOperand(2), m_APInt(SA)))
2199 break;
2200
2201 KnownBits Known3(BitWidth);
2202 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2203 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2204 Known = II->getIntrinsicID() == Intrinsic::fshl
2205 ? KnownBits::fshl(Known2, Known3, *SA)
2206 : KnownBits::fshr(Known2, Known3, *SA);
2207 break;
2208 }
2209 case Intrinsic::clmul:
2210 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2211 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2212 Known = KnownBits::clmul(Known, Known2);
2213 break;
2214 case Intrinsic::pext:
2215 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2216 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2217 Known = KnownBits::pext(Known, Known2);
2218 break;
2219 case Intrinsic::pdep:
2220 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2221 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2222 Known = KnownBits::pdep(Known, Known2);
2223 break;
2224 case Intrinsic::smulh:
2225 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2226 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2227 Known = KnownBits::mulhs(Known, Known2);
2228 break;
2229 case Intrinsic::umulh:
2230 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2231 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2232 Known = KnownBits::mulhu(Known, Known2);
2233 break;
2234 case Intrinsic::uadd_sat:
2235 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2236 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2237 Known = KnownBits::uadd_sat(Known, Known2);
2238 break;
2239 case Intrinsic::usub_sat:
2240 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2241 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2242 Known = KnownBits::usub_sat(Known, Known2);
2243 break;
2244 case Intrinsic::sadd_sat:
2245 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2246 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2247 Known = KnownBits::sadd_sat(Known, Known2);
2248 break;
2249 case Intrinsic::ssub_sat:
2250 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2251 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2252 Known = KnownBits::ssub_sat(Known, Known2);
2253 break;
2254 // Vec reverse preserves bits from input vec.
2255 case Intrinsic::vector_reverse:
2256 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2257 Depth + 1);
2258 break;
2259 // for min/max/and/or reduce, any bit common to each element in the
2260 // input vec is set in the output.
2261 case Intrinsic::vector_reduce_and:
2262 case Intrinsic::vector_reduce_or:
2263 case Intrinsic::vector_reduce_umax:
2264 case Intrinsic::vector_reduce_umin:
2265 case Intrinsic::vector_reduce_smax:
2266 case Intrinsic::vector_reduce_smin:
2267 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2268 break;
2269 case Intrinsic::vector_reduce_xor: {
2270 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2271 // The zeros common to all vecs are zero in the output.
2272 // If the number of elements is odd, then the common ones remain. If the
2273 // number of elements is even, then the common ones becomes zeros.
2274 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2275 // Even, so the ones become zeros.
2276 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2277 if (EvenCnt)
2278 Known.Zero |= Known.One;
2279 // Maybe even element count so need to clear ones.
2280 if (VecTy->isScalableTy() || EvenCnt)
2281 Known.One.clearAllBits();
2282 break;
2283 }
2284 case Intrinsic::vector_reduce_add: {
2285 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2286 if (!VecTy)
2287 break;
2288 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2289 Known = Known.reduceAdd(VecTy->getNumElements());
2290 break;
2291 }
2292 case Intrinsic::umin:
2293 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2294 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2295 Known = KnownBits::umin(Known, Known2);
2296 break;
2297 case Intrinsic::umax:
2298 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2299 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2300 Known = KnownBits::umax(Known, Known2);
2301 break;
2302 case Intrinsic::smin:
2303 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2304 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2305 Known = KnownBits::smin(Known, Known2);
2307 break;
2308 case Intrinsic::smax:
2309 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2310 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2311 Known = KnownBits::smax(Known, Known2);
2313 break;
2314 case Intrinsic::ptrmask: {
2315 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2316
2317 const Value *Mask = I->getOperand(1);
2318 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2319 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2320 // TODO: 1-extend would be more precise.
2321 Known &= Known2.anyextOrTrunc(BitWidth);
2322 break;
2323 }
2324 case Intrinsic::x86_sse42_crc32_64_64:
2325 Known.Zero.setBitsFrom(32);
2326 break;
2327 case Intrinsic::x86_ssse3_phadd_d_128:
2328 case Intrinsic::x86_ssse3_phadd_w_128:
2329 case Intrinsic::x86_avx2_phadd_d:
2330 case Intrinsic::x86_avx2_phadd_w: {
2332 I, DemandedElts, Q, Depth,
2333 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2334 return KnownBits::add(KnownLHS, KnownRHS);
2335 });
2336 break;
2337 }
2338 case Intrinsic::x86_ssse3_phadd_sw_128:
2339 case Intrinsic::x86_avx2_phadd_sw: {
2341 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2342 break;
2343 }
2344 case Intrinsic::x86_ssse3_phsub_d_128:
2345 case Intrinsic::x86_ssse3_phsub_w_128:
2346 case Intrinsic::x86_avx2_phsub_d:
2347 case Intrinsic::x86_avx2_phsub_w: {
2349 I, DemandedElts, Q, Depth,
2350 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2351 return KnownBits::sub(KnownLHS, KnownRHS);
2352 });
2353 break;
2354 }
2355 case Intrinsic::x86_ssse3_phsub_sw_128:
2356 case Intrinsic::x86_avx2_phsub_sw: {
2358 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2359 break;
2360 }
2361 case Intrinsic::riscv_vsetvli:
2362 case Intrinsic::riscv_vsetvlimax: {
2363 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2364 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2366 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2367 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2368 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2369 uint64_t MaxVLEN =
2370 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2371 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2372
2373 // Result of vsetvli must be not larger than AVL.
2374 if (HasAVL)
2375 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2376 MaxVL = std::min(MaxVL, CI->getZExtValue());
2377
2378 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2379 if (BitWidth > KnownZeroFirstBit)
2380 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2381 break;
2382 }
2383 case Intrinsic::amdgcn_mbcnt_hi:
2384 case Intrinsic::amdgcn_mbcnt_lo: {
2385 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2386 // most 31 + src1.
2387 KnownBits MbcntKnown(BitWidth);
2388 MbcntKnown.Zero.setBitsFrom(
2389 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2390 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2391 Known = Known.unionWith(KnownBits::add(MbcntKnown, Known2));
2392 break;
2393 }
2394 case Intrinsic::vscale: {
2395 if (!II->getParent() || !II->getFunction())
2396 break;
2397
2398 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2399 break;
2400 }
2401 case Intrinsic::stepvector: {
2402 auto *VecTy = cast<VectorType>(II->getType());
2403 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2404 if (!isUIntN(BitWidth, MinNumElts))
2405 break;
2406
2407 bool Overflow = false;
2408 APInt MaxNumElts(BitWidth, MinNumElts);
2409 if (VecTy->isScalableTy()) {
2410 if (!II->getParent() || !II->getFunction())
2411 break;
2412 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2414 .umul_ov(MaxNumElts, Overflow);
2415 }
2416
2417 // Give up if the lane count could wrap. Stepvector truncates lane
2418 // indices that do not fit in the element type.
2419 if (Overflow)
2420 break;
2421
2422 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2423 break;
2424 }
2425 }
2426 }
2427 break;
2428 }
2429 case Instruction::ShuffleVector: {
2430 if (auto *Splat = getSplatValue(I)) {
2432 break;
2433 }
2434
2435 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2436 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2437 if (!Shuf) {
2438 Known.resetAll();
2439 return;
2440 }
2441 // For undef elements, we don't know anything about the common state of
2442 // the shuffle result.
2443 APInt DemandedLHS, DemandedRHS;
2444 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2445 Known.resetAll();
2446 return;
2447 }
2448 Known.setAllConflict();
2449 if (!!DemandedLHS) {
2450 const Value *LHS = Shuf->getOperand(0);
2451 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2452 // If we don't know any bits, early out.
2453 if (Known.isUnknown())
2454 break;
2455 }
2456 if (!!DemandedRHS) {
2457 const Value *RHS = Shuf->getOperand(1);
2458 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2459 Known = Known.intersectWith(Known2);
2460 }
2461 break;
2462 }
2463 case Instruction::InsertElement: {
2464 if (isa<ScalableVectorType>(I->getType())) {
2465 Known.resetAll();
2466 return;
2467 }
2468 const Value *Vec = I->getOperand(0);
2469 const Value *Elt = I->getOperand(1);
2470 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2471 unsigned NumElts = DemandedElts.getBitWidth();
2472 APInt DemandedVecElts = DemandedElts;
2473 bool NeedsElt = true;
2474 // If we know the index we are inserting too, clear it from Vec check.
2475 if (CIdx && CIdx->getValue().ult(NumElts)) {
2476 DemandedVecElts.clearBit(CIdx->getZExtValue());
2477 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2478 }
2479
2480 Known.setAllConflict();
2481 if (NeedsElt) {
2482 computeKnownBits(Elt, Known, Q, Depth + 1);
2483 // If we don't know any bits, early out.
2484 if (Known.isUnknown())
2485 break;
2486 }
2487
2488 if (!DemandedVecElts.isZero()) {
2489 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2490 Known = Known.intersectWith(Known2);
2491 }
2492 break;
2493 }
2494 case Instruction::ExtractElement: {
2495 // Look through extract element. If the index is non-constant or
2496 // out-of-range demand all elements, otherwise just the extracted element.
2497 const Value *Vec = I->getOperand(0);
2498 const Value *Idx = I->getOperand(1);
2499 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2500 if (isa<ScalableVectorType>(Vec->getType())) {
2501 // FIXME: there's probably *something* we can do with scalable vectors
2502 Known.resetAll();
2503 break;
2504 }
2505 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2506 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2507 if (CIdx && CIdx->getValue().ult(NumElts))
2508 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2509 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2510 break;
2511 }
2512 case Instruction::ExtractValue:
2513 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2515 if (EVI->getNumIndices() != 1) break;
2516 if (EVI->getIndices()[0] == 0) {
2517 switch (II->getIntrinsicID()) {
2518 default: break;
2519 case Intrinsic::uadd_with_overflow:
2520 case Intrinsic::sadd_with_overflow:
2522 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2523 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2524 break;
2525 case Intrinsic::usub_with_overflow:
2526 case Intrinsic::ssub_with_overflow:
2528 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2529 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2530 break;
2531 case Intrinsic::umul_with_overflow:
2532 case Intrinsic::smul_with_overflow:
2533 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2534 false, DemandedElts, Known, Known2, Q, Depth);
2535 break;
2536 }
2537 }
2538 }
2539 break;
2540 case Instruction::Freeze:
2541 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2542 Depth + 1))
2543 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2544 break;
2545 }
2546}
2547
2548/// Determine which bits of V are known to be either zero or one and return
2549/// them.
2550KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2551 const SimplifyQuery &Q, unsigned Depth) {
2552 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2553 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2554 return Known;
2555}
2556
2557/// Determine which bits of V are known to be either zero or one and return
2558/// them.
2560 unsigned Depth) {
2561 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2563 return Known;
2564}
2565
2566/// Determine which bits of V are known to be either zero or one and return
2567/// them in the Known bit set.
2568///
2569/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2570/// we cannot optimize based on the assumption that it is zero without changing
2571/// it to be an explicit zero. If we don't change it to zero, other code could
2572/// optimized based on the contradictory assumption that it is non-zero.
2573/// Because instcombine aggressively folds operations with undef args anyway,
2574/// this won't lose us code quality.
2575///
2576/// This function is defined on values with integer type, values with pointer
2577/// type, and vectors of integers. In the case
2578/// where V is a vector, known zero, and known one values are the
2579/// same width as the vector element, and the bit is set only if it is true
2580/// for all of the demanded elements in the vector specified by DemandedElts.
2581void computeKnownBits(const Value *V, const APInt &DemandedElts,
2582 KnownBits &Known, const SimplifyQuery &Q,
2583 unsigned Depth) {
2584 if (!DemandedElts) {
2585 // No demanded elts, better to assume we don't know anything.
2586 Known.resetAll();
2587 return;
2588 }
2589
2590 assert(V && "No Value?");
2591 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2592
2593#ifndef NDEBUG
2594 Type *Ty = V->getType();
2595 unsigned BitWidth = Known.getBitWidth();
2596
2597 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2598 "Not integer or pointer type!");
2599
2600 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2601 assert(
2602 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2603 "DemandedElt width should equal the fixed vector number of elements");
2604 } else {
2605 assert(DemandedElts == APInt(1, 1) &&
2606 "DemandedElt width should be 1 for scalars or scalable vectors");
2607 }
2608
2609 Type *ScalarTy = Ty->getScalarType();
2610 if (ScalarTy->isPointerTy()) {
2611 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2612 "V and Known should have same BitWidth");
2613 } else {
2614 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2615 "V and Known should have same BitWidth");
2616 }
2617#endif
2618
2619 const APInt *C;
2620 if (match(V, m_APInt(C))) {
2621 // We know all of the bits for a scalar constant or a splat vector constant!
2623 return;
2624 }
2625 // Null and aggregate-zero are all-zeros.
2627 Known.setAllZero();
2628 return;
2629 }
2630 // Handle a constant vector by taking the intersection of the known bits of
2631 // each element.
2633 assert(!isa<ScalableVectorType>(V->getType()));
2634 // We know that CDV must be a vector of integers. Take the intersection of
2635 // each element.
2636 Known.setAllConflict();
2637 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2638 if (!DemandedElts[i])
2639 continue;
2640 APInt Elt = CDV->getElementAsAPInt(i);
2641 Known.Zero &= ~Elt;
2642 Known.One &= Elt;
2643 }
2644 if (Known.hasConflict())
2645 Known.resetAll();
2646 return;
2647 }
2648
2649 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2650 assert(!isa<ScalableVectorType>(V->getType()));
2651 // We know that CV must be a vector of integers. Take the intersection of
2652 // each element.
2653 Known.setAllConflict();
2654 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2655 if (!DemandedElts[i])
2656 continue;
2657 Constant *Element = CV->getAggregateElement(i);
2658 if (isa<PoisonValue>(Element))
2659 continue;
2660 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2661 if (!ElementCI) {
2662 Known.resetAll();
2663 return;
2664 }
2665 const APInt &Elt = ElementCI->getValue();
2666 Known.Zero &= ~Elt;
2667 Known.One &= Elt;
2668 }
2669 if (Known.hasConflict())
2670 Known.resetAll();
2671 return;
2672 }
2673
2674 // Start out not knowing anything.
2675 Known.resetAll();
2676
2677 // We can't imply anything about undefs.
2678 if (isa<UndefValue>(V))
2679 return;
2680
2681 // There's no point in looking through other users of ConstantData for
2682 // assumptions. Confirm that we've handled them all.
2683 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2684
2685 if (const auto *A = dyn_cast<Argument>(V))
2686 if (std::optional<ConstantRange> Range = A->getRange())
2687 Known = Range->toKnownBits();
2688
2689 // All recursive calls that increase depth must come after this.
2691 return;
2692
2693 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2694 // the bits of its aliasee.
2695 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2696 if (!GA->isInterposable())
2697 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2698 return;
2699 }
2700
2701 if (const Operator *I = dyn_cast<Operator>(V))
2702 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2703 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2704 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2705 Known = CR->toKnownBits();
2706 }
2707
2708 // Aligned pointers have trailing zeros - refine Known.Zero set
2709 if (isa<PointerType>(V->getType())) {
2710 Align Alignment = V->getPointerAlignment(Q.DL);
2711 Known.Zero.setLowBits(Log2(Alignment));
2712 }
2713
2714 // computeKnownBitsFromContext strictly refines Known.
2715 // Therefore, we run them after computeKnownBitsFromOperator.
2716
2717 // Check whether we can determine known bits from context such as assumes.
2719}
2720
2721/// Try to detect a recurrence that the value of the induction variable is
2722/// always a power of two (or zero).
2723static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2724 SimplifyQuery &Q, unsigned Depth) {
2725 BinaryOperator *BO = nullptr;
2726 Value *Start = nullptr, *Step = nullptr;
2727 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2728 return false;
2729
2730 // Initial value must be a power of two.
2731 for (const Use &U : PN->operands()) {
2732 if (U.get() == Start) {
2733 // Initial value comes from a different BB, need to adjust context
2734 // instruction for analysis.
2735 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2736 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2737 return false;
2738 }
2739 }
2740
2741 // Except for Mul, the induction variable must be on the left side of the
2742 // increment expression, otherwise its value can be arbitrary.
2743 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2744 return false;
2745
2746 Q.CtxI = BO->getParent()->getTerminator();
2747 switch (BO->getOpcode()) {
2748 case Instruction::Mul:
2749 // Power of two is closed under multiplication.
2750 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2751 Q.IIQ.hasNoSignedWrap(BO)) &&
2752 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2753 case Instruction::SDiv:
2754 // Start value must not be signmask for signed division, so simply being a
2755 // power of two is not sufficient, and it has to be a constant.
2756 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2757 return false;
2758 [[fallthrough]];
2759 case Instruction::UDiv:
2760 // Divisor must be a power of two.
2761 // If OrZero is false, cannot guarantee induction variable is non-zero after
2762 // division, same for Shr, unless it is exact division.
2763 return (OrZero || Q.IIQ.isExact(BO)) &&
2764 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2765 case Instruction::Shl:
2766 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2767 case Instruction::AShr:
2768 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2769 return false;
2770 [[fallthrough]];
2771 case Instruction::LShr:
2772 return OrZero || Q.IIQ.isExact(BO);
2773 default:
2774 return false;
2775 }
2776}
2777
2778/// Return true if we can infer that \p V is known to be a power of 2 from
2779/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2780static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2781 const Value *Cond,
2782 bool CondIsTrue) {
2783 CmpPredicate Pred;
2784 const APInt *RHSC;
2785 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2786 return false;
2787 if (!CondIsTrue)
2788 Pred = ICmpInst::getInversePredicate(Pred);
2789 // ctpop(V) u< 2
2790 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2791 return true;
2792 // ctpop(V) == 1
2793 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2794}
2795
2796/// Return true if the given value is known to have exactly one
2797/// bit set when defined. For vectors return true if every element is known to
2798/// be a power of two when defined. Supports values with integer or pointer
2799/// types and vectors of integers.
2800bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2801 const SimplifyQuery &Q, unsigned Depth) {
2802 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2803
2804 if (isa<Constant>(V))
2805 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2806
2807 // i1 is by definition a power of 2 or zero.
2808 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2809 return true;
2810
2811 // Try to infer from assumptions.
2812 if (Q.AC && Q.CtxI) {
2813 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2814 if (!AssumeVH)
2815 continue;
2816 CallInst *I = cast<CallInst>(AssumeVH);
2817 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2818 /*CondIsTrue=*/true) &&
2820 return true;
2821 }
2822 }
2823
2824 // Handle dominating conditions.
2825 if (Q.DC && Q.CtxI && Q.DT) {
2826 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2827 Value *Cond = BI->getCondition();
2828
2829 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2831 /*CondIsTrue=*/true) &&
2832 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2833 return true;
2834
2835 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2837 /*CondIsTrue=*/false) &&
2838 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2839 return true;
2840 }
2841 }
2842
2843 auto *I = dyn_cast<Instruction>(V);
2844 if (!I)
2845 return false;
2846
2847 if (Q.CtxI && match(V, m_VScale())) {
2848 const Function *F = Q.CtxI->getFunction();
2849 // The vscale_range indicates vscale is a power-of-two.
2850 return F->hasFnAttribute(Attribute::VScaleRange);
2851 }
2852
2853 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2854 // it is shifted off the end then the result is undefined.
2855 if (match(I, m_Shl(m_One(), m_Value())))
2856 return true;
2857
2858 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2859 // the bottom. If it is shifted off the bottom then the result is undefined.
2860 if (match(I, m_LShr(m_SignMask(), m_Value())))
2861 return true;
2862
2863 // The remaining tests are all recursive, so bail out if we hit the limit.
2865 return false;
2866
2867 switch (I->getOpcode()) {
2868 case Instruction::ZExt:
2869 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2870 case Instruction::Trunc:
2871 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2872 case Instruction::Shl:
2873 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2874 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2875 return false;
2876 case Instruction::LShr:
2877 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2878 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2879 return false;
2880 case Instruction::UDiv:
2882 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2883 return false;
2884 case Instruction::Mul:
2885 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2886 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2887 (OrZero || isKnownNonZero(I, Q, Depth));
2888 case Instruction::And:
2889 // A power of two and'd with anything is a power of two or zero.
2890 if (OrZero &&
2891 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2892 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2893 return true;
2894 // X & (-X) is always a power of two or zero.
2895 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2896 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2897 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2898 return false;
2899 case Instruction::Add: {
2900 // Adding a power-of-two or zero to the same power-of-two or zero yields
2901 // either the original power-of-two, a larger power-of-two or zero.
2903 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2904 Q.IIQ.hasNoSignedWrap(VOBO)) {
2905 if (match(I->getOperand(0),
2906 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2907 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2908 return true;
2909 if (match(I->getOperand(1),
2910 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2911 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2912 return true;
2913
2914 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2915 KnownBits LHSBits(BitWidth);
2916 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2917
2918 KnownBits RHSBits(BitWidth);
2919 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2920 // If i8 V is a power of two or zero:
2921 // ZeroBits: 1 1 1 0 1 1 1 1
2922 // ~ZeroBits: 0 0 0 1 0 0 0 0
2923 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2924 // If OrZero isn't set, we cannot give back a zero result.
2925 // Make sure either the LHS or RHS has a bit set.
2926 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2927 return true;
2928 }
2929
2930 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2931 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2932 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2933 return true;
2934 return false;
2935 }
2936 case Instruction::Select:
2937 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2938 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2939 case Instruction::PHI: {
2940 // A PHI node is power of two if all incoming values are power of two, or if
2941 // it is an induction variable where in each step its value is a power of
2942 // two.
2943 auto *PN = cast<PHINode>(I);
2945
2946 // Check if it is an induction variable and always power of two.
2947 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2948 return true;
2949
2950 // Recursively check all incoming values. Limit recursion to 2 levels, so
2951 // that search complexity is limited to number of operands^2.
2952 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2953 return llvm::all_of(PN->operands(), [&](const Use &U) {
2954 // Value is power of 2 if it is coming from PHI node itself by induction.
2955 if (U.get() == PN)
2956 return true;
2957
2958 // Change the context instruction to the incoming block where it is
2959 // evaluated.
2960 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
2961 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2962 });
2963 }
2964 case Instruction::Invoke:
2965 case Instruction::Call: {
2966 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2967 switch (II->getIntrinsicID()) {
2968 case Intrinsic::umax:
2969 case Intrinsic::smax:
2970 case Intrinsic::umin:
2971 case Intrinsic::smin:
2972 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2973 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2974 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2975 // thus dont change pow2/non-pow2 status.
2976 case Intrinsic::bitreverse:
2977 case Intrinsic::bswap:
2978 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2979 case Intrinsic::fshr:
2980 case Intrinsic::fshl:
2981 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2982 if (II->getArgOperand(0) == II->getArgOperand(1))
2983 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2984 break;
2985 case Intrinsic::riscv_vsetvlimax:
2986 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2987 // for any valid vtype, so it is a power of two regardless of OrZero.
2988 return true;
2989 case Intrinsic::read_register:
2990 case Intrinsic::read_volatile_register: {
2991 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2992 // of two, so it is a power of two regardless of OrZero.
2993 const Module *M = II->getModule();
2994 if (!M || !M->getTargetTriple().isRISCV())
2995 break;
2996 return isReadVLENB(*II);
2997 }
2998 default:
2999 break;
3000 }
3001 }
3002 return false;
3003 }
3004 default:
3005 return false;
3006 }
3007}
3008
3009/// Test whether a GEP's result is known to be non-null.
3010///
3011/// Uses properties inherent in a GEP to try to determine whether it is known
3012/// to be non-null.
3013///
3014/// Currently this routine does not support vector GEPs.
3015static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
3016 unsigned Depth) {
3017 const Function *F = nullptr;
3018 if (const Instruction *I = dyn_cast<Instruction>(GEP))
3019 F = I->getFunction();
3020
3021 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
3022 // may be null iff the base pointer is null and the offset is zero.
3023 if (!GEP->hasNoUnsignedWrap() &&
3024 !(GEP->isInBounds() &&
3025 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3026 return false;
3027
3028 // FIXME: Support vector-GEPs.
3029 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3030
3031 // If the base pointer is non-null, we cannot walk to a null address with an
3032 // inbounds GEP in address space zero.
3033 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3034 return true;
3035
3036 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3037 // If so, then the GEP cannot produce a null pointer, as doing so would
3038 // inherently violate the inbounds contract within address space zero.
3040 GTI != GTE; ++GTI) {
3041 // Struct types are easy -- they must always be indexed by a constant.
3042 if (StructType *STy = GTI.getStructTypeOrNull()) {
3043 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3044 unsigned ElementIdx = OpC->getZExtValue();
3045 const StructLayout *SL = Q.DL.getStructLayout(STy);
3046 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3047 if (ElementOffset > 0)
3048 return true;
3049 continue;
3050 }
3051
3052 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3053 if (GTI.getSequentialElementStride(Q.DL).isZero())
3054 continue;
3055
3056 // Fast path the constant operand case both for efficiency and so we don't
3057 // increment Depth when just zipping down an all-constant GEP.
3058 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3059 if (!OpC->isZero())
3060 return true;
3061 continue;
3062 }
3063
3064 // We post-increment Depth here because while isKnownNonZero increments it
3065 // as well, when we pop back up that increment won't persist. We don't want
3066 // to recurse 10k times just because we have 10k GEP operands. We don't
3067 // bail completely out because we want to handle constant GEPs regardless
3068 // of depth.
3070 continue;
3071
3072 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3073 return true;
3074 }
3075
3076 return false;
3077}
3078
3080 const Instruction *CtxI,
3081 const DominatorTree *DT) {
3082 assert(!isa<Constant>(V) && "Called for constant?");
3083
3084 if (!CtxI || !DT)
3085 return false;
3086
3087 unsigned NumUsesExplored = 0;
3088 for (auto &U : V->uses()) {
3089 // Avoid massive lists
3090 if (NumUsesExplored >= DomConditionsMaxUses)
3091 break;
3092 NumUsesExplored++;
3093
3094 const Instruction *UI = cast<Instruction>(U.getUser());
3095 // If the value is used as an argument to a call or invoke, then argument
3096 // attributes may provide an answer about null-ness.
3097 if (V->getType()->isPointerTy()) {
3098 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3099 if (CB->isArgOperand(&U) &&
3100 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3101 /*AllowUndefOrPoison=*/false) &&
3102 DT->dominates(CB, CtxI))
3103 return true;
3104 }
3105 }
3106
3107 // If the value is used as a load/store, then the pointer must be non null.
3108 if (V == getLoadStorePointerOperand(UI)) {
3111 DT->dominates(UI, CtxI))
3112 return true;
3113 }
3114
3115 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3116 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3117 isValidAssumeForContext(UI, CtxI, DT))
3118 return true;
3119
3120 // Consider only compare instructions uniquely controlling a branch
3121 Value *RHS;
3122 CmpPredicate Pred;
3123 bool NonNullIfTrue;
3124 if (match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) {
3125 if (cmpExcludesZero(Pred, RHS))
3126 NonNullIfTrue = true;
3128 NonNullIfTrue = false;
3129 else
3130 continue;
3131 } else if (UI->getType()->isIntegerTy(1) &&
3132 match(UI, m_Trunc(m_Specific(V)))) {
3133 NonNullIfTrue = true;
3134 } else
3135 continue;
3136
3139 for (const auto *CmpU : UI->users()) {
3140 assert(WorkList.empty() && "Should be!");
3141 if (Visited.insert(CmpU).second)
3142 WorkList.push_back(CmpU);
3143
3144 while (!WorkList.empty()) {
3145 auto *Curr = WorkList.pop_back_val();
3146
3147 // If a user is an AND, add all its users to the work list. We only
3148 // propagate "pred != null" condition through AND because it is only
3149 // correct to assume that all conditions of AND are met in true branch.
3150 // TODO: Support similar logic of OR and EQ predicate?
3151 if (NonNullIfTrue)
3152 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3153 for (const auto *CurrU : Curr->users())
3154 if (Visited.insert(CurrU).second)
3155 WorkList.push_back(CurrU);
3156 continue;
3157 }
3158
3159 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3160 BasicBlock *NonNullSuccessor =
3161 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3162 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3163 if (DT->dominates(Edge, CtxI->getParent()))
3164 return true;
3165 } else if (NonNullIfTrue && isGuard(Curr) &&
3166 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3167 return true;
3168 }
3169 }
3170 }
3171 }
3172
3173 return false;
3174}
3175
3176/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3177/// ensure that the value it's attached to is never Value? 'RangeType' is
3178/// is the type of the value described by the range.
3179static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3180 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3181 assert(NumRanges >= 1);
3182 for (unsigned i = 0; i < NumRanges; ++i) {
3184 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3186 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3187 ConstantRange Range(Lower->getValue(), Upper->getValue());
3188 if (Range.contains(Value))
3189 return false;
3190 }
3191 return true;
3192}
3193
3194/// Try to detect a recurrence that monotonically increases/decreases from a
3195/// non-zero starting value. These are common as induction variables.
3196static bool isNonZeroRecurrence(const PHINode *PN) {
3197 BinaryOperator *BO = nullptr;
3198 Value *Start = nullptr, *Step = nullptr;
3199 const APInt *StartC, *StepC;
3200 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3201 !match(Start, m_APInt(StartC)) || StartC->isZero())
3202 return false;
3203
3204 switch (BO->getOpcode()) {
3205 case Instruction::Add:
3206 // Starting from non-zero and stepping away from zero can never wrap back
3207 // to zero.
3208 return BO->hasNoUnsignedWrap() ||
3209 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3210 StartC->isNegative() == StepC->isNegative());
3211 case Instruction::Mul:
3212 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3213 match(Step, m_APInt(StepC)) && !StepC->isZero();
3214 case Instruction::Shl:
3215 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3216 case Instruction::AShr:
3217 case Instruction::LShr:
3218 return BO->isExact();
3219 case Instruction::Or:
3220 return true;
3221 default:
3222 return false;
3223 }
3224}
3225
3226static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3228 m_Specific(Op1), m_Zero()))) ||
3230 m_Specific(Op0), m_Zero())));
3231}
3232
3233/// Return true if "addr(P) + Off" cannot be zero. The object P points to
3234/// cannot cross the unsigned address space boundary, including the address one
3235/// past its end, so an offset that stays within the object cannot wrap around
3236/// to zero. This holds even if the object starts at the zero address, which is
3237/// all that null_pointer_is_valid permits, so a non-zero offset is enough.
3239 Value *Y) {
3240 const APInt *Off;
3241 if (!match(Y, m_APInt(Off)) || Off->isZero())
3242 return false;
3243
3244 // ptrtoaddr always produces the address. ptrtoint only does so when its
3245 // result is at least as wide as the address: a narrower result is truncated
3246 // and may wrap to zero, while bits above the address can only make the
3247 // result more non-zero.
3248 Value *P;
3249 if (!match(X, m_PtrToAddr(m_Value(P))) &&
3250 !(match(X, m_PtrToInt(m_Value(P))) &&
3251 X->getType()->getScalarSizeInBits() >=
3252 Q.DL.getAddressSizeInBits(P->getType())))
3253 return false;
3254
3255 // A vector of pointers has no single object whose size can be taken, and
3256 // getPointerDereferenceableBytes() requires a plain pointer.
3257 if (!P->getType()->isPointerTy())
3258 return false;
3259
3260 bool CanBeNull;
3261 uint64_t DerefBytes = P->getPointerDereferenceableBytes(
3262 Q.DL, CanBeNull, /*CanBeFreed=*/nullptr);
3263 if (CanBeNull || DerefBytes == 0 || !Off->ule(DerefBytes))
3264 return false;
3265
3266 return true;
3267}
3268
3269static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3270 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3271 bool NUW, unsigned Depth) {
3273 return true;
3274
3275 // (X + (X != 0)) is non zero
3276 if (matchOpWithOpEqZero(X, Y))
3277 return true;
3278
3279 if (NUW)
3280 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3281 isKnownNonZero(X, DemandedElts, Q, Depth);
3282
3283 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3284 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3285
3286 // If X and Y are both non-negative (as signed values) then their sum is not
3287 // zero unless both X and Y are zero.
3288 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3289 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3290 isKnownNonZero(X, DemandedElts, Q, Depth))
3291 return true;
3292
3293 // If X and Y are both negative (as signed values) then their sum is not
3294 // zero unless both X and Y equal INT_MIN.
3295 if (XKnown.isNegative() && YKnown.isNegative()) {
3297 // The sign bit of X is set. If some other bit is set then X is not equal
3298 // to INT_MIN.
3299 if (XKnown.One.intersects(Mask))
3300 return true;
3301 // The sign bit of Y is set. If some other bit is set then Y is not equal
3302 // to INT_MIN.
3303 if (YKnown.One.intersects(Mask))
3304 return true;
3305 }
3306
3307 // The sum of a non-negative number and a power of two is not zero.
3308 if (XKnown.isNonNegative() &&
3309 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3310 return true;
3311 if (YKnown.isNonNegative() &&
3312 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3313 return true;
3314
3315 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3316}
3317
3318static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3319 unsigned BitWidth, Value *X, Value *Y,
3320 unsigned Depth) {
3321 // (X - (X != 0)) is non zero
3322 // ((X != 0) - X) is non zero
3323 if (matchOpWithOpEqZero(X, Y))
3324 return true;
3325
3326 // TODO: Move this case into isKnownNonEqual().
3327 if (auto *C = dyn_cast<Constant>(X))
3328 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3329 return true;
3330
3331 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3332}
3333
3334static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3335 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3336 bool NUW, unsigned Depth) {
3337 // If X and Y are non-zero then so is X * Y as long as the multiplication
3338 // does not overflow.
3339 if (NSW || NUW)
3340 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3341 isKnownNonZero(Y, DemandedElts, Q, Depth);
3342
3343 // If either X or Y is odd, then if the other is non-zero the result can't
3344 // be zero.
3345 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3346 if (XKnown.One[0])
3347 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3348
3349 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3350 if (YKnown.One[0])
3351 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3352
3353 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3354 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3355 // the lowest known One of X and Y. If they are non-zero, the result
3356 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3357 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3358 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3359 BitWidth;
3360}
3361
3362static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3363 const SimplifyQuery &Q, const KnownBits &KnownVal,
3364 unsigned Depth) {
3365 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3366 switch (I->getOpcode()) {
3367 case Instruction::Shl:
3368 return Lhs.shl(Rhs);
3369 case Instruction::LShr:
3370 return Lhs.lshr(Rhs);
3371 case Instruction::AShr:
3372 return Lhs.ashr(Rhs);
3373 default:
3374 llvm_unreachable("Unknown Shift Opcode");
3375 }
3376 };
3377
3378 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3379 switch (I->getOpcode()) {
3380 case Instruction::Shl:
3381 return Lhs.lshr(Rhs);
3382 case Instruction::LShr:
3383 case Instruction::AShr:
3384 return Lhs.shl(Rhs);
3385 default:
3386 llvm_unreachable("Unknown Shift Opcode");
3387 }
3388 };
3389
3390 if (KnownVal.isUnknown())
3391 return false;
3392
3393 KnownBits KnownCnt =
3394 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3395 APInt MaxShift = KnownCnt.getMaxValue();
3396 unsigned NumBits = KnownVal.getBitWidth();
3397 if (MaxShift.uge(NumBits))
3398 return false;
3399
3400 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3401 return true;
3402
3403 // If all of the bits shifted out are known to be zero, and Val is known
3404 // non-zero then at least one non-zero bit must remain.
3405 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3406 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3407 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3408 return true;
3409
3410 return false;
3411}
3412
3414 const APInt &DemandedElts,
3415 const SimplifyQuery &Q, unsigned Depth) {
3416 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3417 switch (I->getOpcode()) {
3418 case Instruction::Alloca:
3419 // Alloca never returns null, malloc might.
3420 return I->getType()->getPointerAddressSpace() == 0;
3421 case Instruction::GetElementPtr:
3422 if (I->getType()->isPointerTy())
3424 break;
3425 case Instruction::BitCast: {
3426 // We need to be a bit careful here. We can only peek through the bitcast
3427 // if the scalar size of elements in the operand are smaller than and a
3428 // multiple of the size they are casting too. Take three cases:
3429 //
3430 // 1) Unsafe:
3431 // bitcast <2 x i16> %NonZero to <4 x i8>
3432 //
3433 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3434 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3435 // guranteed (imagine just sign bit set in the 2 i16 elements).
3436 //
3437 // 2) Unsafe:
3438 // bitcast <4 x i3> %NonZero to <3 x i4>
3439 //
3440 // Even though the scalar size of the src (`i3`) is smaller than the
3441 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3442 // its possible for the `3 x i4` elements to be zero because there are
3443 // some elements in the destination that don't contain any full src
3444 // element.
3445 //
3446 // 3) Safe:
3447 // bitcast <4 x i8> %NonZero to <2 x i16>
3448 //
3449 // This is always safe as non-zero in the 4 i8 elements implies
3450 // non-zero in the combination of any two adjacent ones. Since i8 is a
3451 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3452 // This all implies the 2 i16 elements are non-zero.
3453 Type *FromTy = I->getOperand(0)->getType();
3454 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3455 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3456 return isKnownNonZero(I->getOperand(0), Q, Depth);
3457 } break;
3458 case Instruction::IntToPtr:
3459 // Note that we have to take special care to avoid looking through
3460 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3461 // as casts that can alter the value, e.g., AddrSpaceCasts.
3462 if (!isa<ScalableVectorType>(I->getType()) &&
3463 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3464 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3465 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3466 break;
3467 case Instruction::PtrToAddr:
3468 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3469 // so we can directly forward.
3470 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3471 case Instruction::PtrToInt:
3472 // For inttoptr, make sure the result size is >= the address size. If the
3473 // address is non-zero, any larger value is also non-zero.
3474 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3475 I->getType()->getScalarSizeInBits())
3476 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3477 break;
3478 case Instruction::Trunc:
3479 // nuw/nsw trunc preserves zero/non-zero status of input.
3480 if (auto *TI = dyn_cast<TruncInst>(I))
3481 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3482 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3483 break;
3484
3485 // Iff x - y != 0, then x ^ y != 0
3486 // Therefore we can do the same exact checks
3487 case Instruction::Xor:
3488 case Instruction::Sub:
3489 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3490 I->getOperand(1), Depth);
3491 case Instruction::Or:
3492 // (X | (X != 0)) is non zero
3493 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3494 return true;
3495 // X | Y != 0 if X != Y.
3496 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3497 Depth))
3498 return true;
3499 // X | Y != 0 if X != 0 or Y != 0.
3500 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3501 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3502 case Instruction::SExt:
3503 case Instruction::ZExt:
3504 // ext X != 0 if X != 0.
3505 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3506
3507 case Instruction::Shl: {
3508 // shl nsw/nuw can't remove any non-zero bits.
3510 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3511 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3512
3513 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3514 // if the lowest bit is shifted off the end.
3516 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3517 if (Known.One[0])
3518 return true;
3519
3520 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3521 }
3522 case Instruction::LShr:
3523 case Instruction::AShr: {
3524 // shr exact can only shift out zero bits.
3526 if (BO->isExact())
3527 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3528
3529 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3530 // defined if the sign bit is shifted off the end.
3532 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3533 if (Known.isNegative())
3534 return true;
3535
3536 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3537 // position >= C, because the sum >= max(A, B).
3538 Value *A, *B;
3539 const APInt *C;
3540 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3541 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3542 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3543 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3544 if (!KnownA.One.lshr(*C).isZero())
3545 return true;
3546 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3547 if (!KnownB.One.lshr(*C).isZero())
3548 return true;
3549 }
3550
3551 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3552 }
3553 case Instruction::UDiv:
3554 case Instruction::SDiv: {
3555 // X / Y
3556 // div exact can only produce a zero if the dividend is zero.
3557 if (cast<PossiblyExactOperator>(I)->isExact())
3558 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3559
3560 KnownBits XKnown =
3561 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3562 // If X is fully unknown we won't be able to figure anything out so don't
3563 // both computing knownbits for Y.
3564 if (XKnown.isUnknown())
3565 return false;
3566
3567 KnownBits YKnown =
3568 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3569 if (I->getOpcode() == Instruction::SDiv) {
3570 // For signed division need to compare abs value of the operands.
3571 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3572 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3573 }
3574 // If X u>= Y then div is non zero (0/0 is UB).
3575 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3576 // If X is total unknown or X u< Y we won't be able to prove non-zero
3577 // with compute known bits so just return early.
3578 return XUgeY && *XUgeY;
3579 }
3580 case Instruction::Add: {
3581 // X + Y.
3582
3583 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3584 // non-zero.
3586 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3587 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3588 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3589 }
3590 case Instruction::Mul: {
3592 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3593 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3594 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3595 }
3596 case Instruction::Select: {
3597 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3598
3599 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3600 // then see if the select condition implies the arm is non-zero. For example
3601 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3602 // dominated by `X != 0`.
3603 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3604 Value *Op;
3605 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3606 // Op is trivially non-zero.
3607 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3608 return true;
3609
3610 // The condition of the select dominates the true/false arm. Check if the
3611 // condition implies that a given arm is non-zero.
3612 Value *X;
3613 CmpPredicate Pred;
3614 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3615 return false;
3616
3617 if (!IsTrueArm)
3618 Pred = ICmpInst::getInversePredicate(Pred);
3619
3620 return cmpExcludesZero(Pred, X);
3621 };
3622
3623 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3624 SelectArmIsNonZero(/* IsTrueArm */ false))
3625 return true;
3626 break;
3627 }
3628 case Instruction::PHI: {
3629 auto *PN = cast<PHINode>(I);
3631 return true;
3632
3633 // Check if all incoming values are non-zero using recursion.
3635 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3636 return llvm::all_of(PN->operands(), [&](const Use &U) {
3637 if (U.get() == PN)
3638 return true;
3639 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3640 // Check if the branch on the phi excludes zero.
3641 CmpPredicate Pred;
3642 Value *X;
3643 BasicBlock *TrueSucc, *FalseSucc;
3644 if (match(RecQ.CtxI,
3645 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3646 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3647 // Check for cases of duplicate successors.
3648 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3649 // If we're using the false successor, invert the predicate.
3650 if (FalseSucc == PN->getParent())
3651 Pred = CmpInst::getInversePredicate(Pred);
3652 if (cmpExcludesZero(Pred, X))
3653 return true;
3654 }
3655 }
3656 // Finally recurse on the edge and check it directly.
3657 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3658 });
3659 }
3660 case Instruction::InsertElement: {
3661 if (isa<ScalableVectorType>(I->getType()))
3662 break;
3663
3664 const Value *Vec = I->getOperand(0);
3665 const Value *Elt = I->getOperand(1);
3666 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3667
3668 unsigned NumElts = DemandedElts.getBitWidth();
3669 APInt DemandedVecElts = DemandedElts;
3670 bool SkipElt = false;
3671 // If we know the index we are inserting too, clear it from Vec check.
3672 if (CIdx && CIdx->getValue().ult(NumElts)) {
3673 DemandedVecElts.clearBit(CIdx->getZExtValue());
3674 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3675 }
3676
3677 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3678 // are non-zero.
3679 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3680 (DemandedVecElts.isZero() ||
3681 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3682 }
3683 case Instruction::ExtractElement:
3684 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3685 const Value *Vec = EEI->getVectorOperand();
3686 const Value *Idx = EEI->getIndexOperand();
3687 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3688 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3689 unsigned NumElts = VecTy->getNumElements();
3690 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3691 if (CIdx && CIdx->getValue().ult(NumElts))
3692 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3693 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3694 }
3695 }
3696 break;
3697 case Instruction::ShuffleVector: {
3698 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3699 if (!Shuf)
3700 break;
3701 APInt DemandedLHS, DemandedRHS;
3702 // For undef elements, we don't know anything about the common state of
3703 // the shuffle result.
3704 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3705 break;
3706 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3707 return (DemandedRHS.isZero() ||
3708 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3709 (DemandedLHS.isZero() ||
3710 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3711 }
3712 case Instruction::Freeze:
3713 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3714 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3715 Depth);
3716 case Instruction::Load: {
3717 auto *LI = cast<LoadInst>(I);
3718 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3719 // is never null.
3720 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3721 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3722 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3723 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3724 return true;
3725 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3727 }
3728
3729 // No need to fall through to computeKnownBits as range metadata is already
3730 // handled in isKnownNonZero.
3731 return false;
3732 }
3733 case Instruction::ExtractValue: {
3734 const WithOverflowInst *WO;
3736 switch (WO->getBinaryOp()) {
3737 default:
3738 break;
3739 case Instruction::Add:
3740 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3741 WO->getArgOperand(1),
3742 /*NSW=*/false,
3743 /*NUW=*/false, Depth);
3744 case Instruction::Sub:
3745 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3746 WO->getArgOperand(1), Depth);
3747 case Instruction::Mul:
3748 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3749 WO->getArgOperand(1),
3750 /*NSW=*/false, /*NUW=*/false, Depth);
3751 break;
3752 }
3753 }
3754 break;
3755 }
3756 case Instruction::Call:
3757 case Instruction::Invoke: {
3758 const auto *Call = cast<CallBase>(I);
3759 if (I->getType()->isPointerTy()) {
3760 if (Call->isReturnNonNull())
3761 return true;
3762 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3763 Call, /*MustPreserveOffset=*/true))
3764 return isKnownNonZero(RP, Q, Depth);
3765 } else {
3766 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3768 if (std::optional<ConstantRange> Range = Call->getRange()) {
3769 const APInt ZeroValue(Range->getBitWidth(), 0);
3770 if (!Range->contains(ZeroValue))
3771 return true;
3772 }
3773 if (const Value *RV = Call->getReturnedArgOperand())
3774 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3775 return true;
3776 }
3777
3778 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3779 switch (II->getIntrinsicID()) {
3780 case Intrinsic::sshl_sat:
3781 case Intrinsic::ushl_sat:
3782 case Intrinsic::abs:
3783 case Intrinsic::bitreverse:
3784 case Intrinsic::bswap:
3785 case Intrinsic::ctpop:
3786 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3787 // NB: We don't do usub_sat here as in any case we can prove its
3788 // non-zero, we will fold it to `sub nuw` in InstCombine.
3789 case Intrinsic::ssub_sat:
3790 // For most types, if x != y then ssub.sat x, y != 0. But
3791 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3792 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3793 if (BitWidth == 1)
3794 return false;
3795 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3796 II->getArgOperand(1), Depth);
3797 case Intrinsic::sadd_sat:
3798 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3799 II->getArgOperand(1),
3800 /*NSW=*/true, /* NUW=*/false, Depth);
3801 // Vec reverse preserves zero/non-zero status from input vec.
3802 case Intrinsic::vector_reverse:
3803 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3804 Q, Depth);
3805 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3806 case Intrinsic::vector_reduce_or:
3807 case Intrinsic::vector_reduce_umax:
3808 case Intrinsic::vector_reduce_umin:
3809 case Intrinsic::vector_reduce_smax:
3810 case Intrinsic::vector_reduce_smin:
3811 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3812 case Intrinsic::umax:
3813 case Intrinsic::uadd_sat:
3814 // umax(X, (X != 0)) is non zero
3815 // X +usat (X != 0) is non zero
3816 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3817 return true;
3818
3819 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3820 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3821 case Intrinsic::smax: {
3822 // If either arg is strictly positive the result is non-zero. Otherwise
3823 // the result is non-zero if both ops are non-zero.
3824 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3825 const KnownBits &OpKnown) {
3826 if (!OpNonZero.has_value())
3827 OpNonZero = OpKnown.isNonZero() ||
3828 isKnownNonZero(Op, DemandedElts, Q, Depth);
3829 return *OpNonZero;
3830 };
3831 // Avoid re-computing isKnownNonZero.
3832 std::optional<bool> Op0NonZero, Op1NonZero;
3833 KnownBits Op1Known =
3834 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3835 if (Op1Known.isNonNegative() &&
3836 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3837 return true;
3838 KnownBits Op0Known =
3839 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3840 if (Op0Known.isNonNegative() &&
3841 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3842 return true;
3843 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3844 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3845 }
3846 case Intrinsic::smin: {
3847 // If either arg is negative the result is non-zero. Otherwise
3848 // the result is non-zero if both ops are non-zero.
3849 KnownBits Op1Known =
3850 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3851 if (Op1Known.isNegative())
3852 return true;
3853 KnownBits Op0Known =
3854 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3855 if (Op0Known.isNegative())
3856 return true;
3857
3858 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3859 return true;
3860 }
3861 [[fallthrough]];
3862 case Intrinsic::umin:
3863 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3864 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3865 case Intrinsic::cttz:
3866 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3867 .Zero[0];
3868 case Intrinsic::ctlz:
3869 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3870 .isNonNegative();
3871 case Intrinsic::fshr:
3872 case Intrinsic::fshl:
3873 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3874 if (II->getArgOperand(0) == II->getArgOperand(1))
3875 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3876 break;
3877 case Intrinsic::vscale:
3878 return true;
3879 case Intrinsic::experimental_get_vector_length:
3880 return isKnownNonZero(I->getOperand(0), Q, Depth);
3881 default:
3882 break;
3883 }
3884 break;
3885 }
3886
3887 return false;
3888 }
3889 }
3890
3892 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3893 return Known.One != 0;
3894}
3895
3896/// Return true if the given value is known to be non-zero when defined. For
3897/// vectors, return true if every demanded element is known to be non-zero when
3898/// defined. For pointers, if the context instruction and dominator tree are
3899/// specified, perform context-sensitive analysis and return true if the
3900/// pointer couldn't possibly be null at the specified instruction.
3901/// Supports values with integer or pointer type and vectors of integers.
3902bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3903 const SimplifyQuery &Q, unsigned Depth) {
3904 Type *Ty = V->getType();
3905
3906#ifndef NDEBUG
3907 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3908
3909 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3910 assert(
3911 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3912 "DemandedElt width should equal the fixed vector number of elements");
3913 } else {
3914 assert(DemandedElts == APInt(1, 1) &&
3915 "DemandedElt width should be 1 for scalars");
3916 }
3917#endif
3918
3919 if (auto *C = dyn_cast<Constant>(V)) {
3920 if (C->isNullValue())
3921 return false;
3922 if (isa<ConstantInt>(C))
3923 // Must be non-zero due to null test above.
3924 return true;
3925
3926 // For constant vectors, check that all elements are poison or known
3927 // non-zero to determine that the whole vector is known non-zero.
3928 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3929 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3930 if (!DemandedElts[i])
3931 continue;
3932 Constant *Elt = C->getAggregateElement(i);
3933 if (!Elt || Elt->isNullValue())
3934 return false;
3935 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3936 return false;
3937 }
3938 return true;
3939 }
3940
3941 // Constant ptrauth can be null, iff the base pointer can be.
3942 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3943 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3944
3945 // A global variable is non null unless extern weak or an absolute symbol
3946 // reference. An alias is also excluded, as it may resolve to a weak
3947 // undefined symbol and thus to the null address. Where null is a valid
3948 // address an allocation may start there, so nothing can be assumed; that
3949 // covers both null_pointer_is_valid and address spaces other than zero.
3950 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3952 GV->getType()->getAddressSpace()) &&
3953 !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3954 !isa<GlobalAlias>(GV))
3955 return true;
3956 }
3957
3958 // For constant expressions, fall through to the Operator code below.
3959 if (!isa<ConstantExpr>(V))
3960 return false;
3961 }
3962
3963 if (const auto *A = dyn_cast<Argument>(V))
3964 if (std::optional<ConstantRange> Range = A->getRange()) {
3965 const APInt ZeroValue(Range->getBitWidth(), 0);
3966 if (!Range->contains(ZeroValue))
3967 return true;
3968 }
3969
3970 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3971 return true;
3972
3973 // Some of the tests below are recursive, so bail out if we hit the limit.
3975 return false;
3976
3977 // Check for pointer simplifications.
3978
3979 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3980 // A byval, inalloca may not be null in a non-default addres space. A
3981 // nonnull argument is assumed never 0.
3982 if (const Argument *A = dyn_cast<Argument>(V)) {
3983 if (((A->hasPassPointeeByValueCopyAttr() &&
3984 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3985 A->hasNonNullAttr()))
3986 return true;
3987 }
3988 }
3989
3990 if (const auto *I = dyn_cast<Operator>(V))
3991 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3992 return true;
3993
3994 if (!isa<Constant>(V) &&
3996 return true;
3997
3998 if (const Value *Stripped = stripNullTest(V))
3999 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
4000
4001 return false;
4002}
4003
4005 unsigned Depth) {
4006 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4007 APInt DemandedElts =
4008 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
4009 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
4010}
4011
4012/// If the pair of operators are the same invertible function, return the
4013/// the operands of the function corresponding to each input. Otherwise,
4014/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
4015/// every input value to exactly one output value. This is equivalent to
4016/// saying that Op1 and Op2 are equal exactly when the specified pair of
4017/// operands are equal, (except that Op1 and Op2 may be poison more often.)
4018static std::optional<std::pair<Value*, Value*>>
4020 const Operator *Op2) {
4021 if (Op1->getOpcode() != Op2->getOpcode())
4022 return std::nullopt;
4023
4024 auto getOperands = [&](unsigned OpNum) -> auto {
4025 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
4026 };
4027
4028 switch (Op1->getOpcode()) {
4029 default:
4030 break;
4031 case Instruction::Or:
4032 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
4033 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
4034 break;
4035 [[fallthrough]];
4036 case Instruction::Xor:
4037 case Instruction::Add: {
4038 Value *Other;
4039 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
4040 return std::make_pair(Op1->getOperand(1), Other);
4041 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
4042 return std::make_pair(Op1->getOperand(0), Other);
4043 break;
4044 }
4045 case Instruction::Sub:
4046 if (Op1->getOperand(0) == Op2->getOperand(0))
4047 return getOperands(1);
4048 if (Op1->getOperand(1) == Op2->getOperand(1))
4049 return getOperands(0);
4050 break;
4051 case Instruction::Mul: {
4052 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4053 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4054 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4055 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4056 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4057 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4058 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4059 break;
4060
4061 // Assume operand order has been canonicalized
4062 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4063 isa<ConstantInt>(Op1->getOperand(1)) &&
4064 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4065 return getOperands(0);
4066 break;
4067 }
4068 case Instruction::Shl: {
4069 // Same as multiplies, with the difference that we don't need to check
4070 // for a non-zero multiply. Shifts always multiply by non-zero.
4071 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4072 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4073 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4074 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4075 break;
4076
4077 if (Op1->getOperand(1) == Op2->getOperand(1))
4078 return getOperands(0);
4079 break;
4080 }
4081 case Instruction::AShr:
4082 case Instruction::LShr: {
4083 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4084 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4085 if (!PEO1->isExact() || !PEO2->isExact())
4086 break;
4087
4088 if (Op1->getOperand(1) == Op2->getOperand(1))
4089 return getOperands(0);
4090 break;
4091 }
4092 case Instruction::SExt:
4093 case Instruction::ZExt:
4094 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4095 return getOperands(0);
4096 break;
4097 case Instruction::PHI: {
4098 const PHINode *PN1 = cast<PHINode>(Op1);
4099 const PHINode *PN2 = cast<PHINode>(Op2);
4100
4101 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4102 // are a single invertible function of the start values? Note that repeated
4103 // application of an invertible function is also invertible
4104 BinaryOperator *BO1 = nullptr;
4105 Value *Start1 = nullptr, *Step1 = nullptr;
4106 BinaryOperator *BO2 = nullptr;
4107 Value *Start2 = nullptr, *Step2 = nullptr;
4108 if (PN1->getParent() != PN2->getParent() ||
4109 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4110 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4111 break;
4112
4114 cast<Operator>(BO2));
4115 if (!Values)
4116 break;
4117
4118 // We have to be careful of mutually defined recurrences here. Ex:
4119 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4120 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4121 // The invertibility of these is complicated, and not worth reasoning
4122 // about (yet?).
4123 if (Values->first != PN1 || Values->second != PN2)
4124 break;
4125
4126 return std::make_pair(Start1, Start2);
4127 }
4128 }
4129 return std::nullopt;
4130}
4131
4132/// Return true if V1 == (binop V2, X), where X is known non-zero.
4133/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4134/// implies V2 != V1.
4135static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4136 const APInt &DemandedElts,
4137 const SimplifyQuery &Q, unsigned Depth) {
4139 if (!BO)
4140 return false;
4141 switch (BO->getOpcode()) {
4142 default:
4143 break;
4144 case Instruction::Or:
4145 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4146 break;
4147 [[fallthrough]];
4148 case Instruction::Xor:
4149 case Instruction::Add:
4150 Value *Op = nullptr;
4151 if (V2 == BO->getOperand(0))
4152 Op = BO->getOperand(1);
4153 else if (V2 == BO->getOperand(1))
4154 Op = BO->getOperand(0);
4155 else
4156 return false;
4157 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4158 }
4159 return false;
4160}
4161
4162/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4163/// the multiplication is nuw or nsw.
4164static bool isNonEqualMul(const Value *V1, const Value *V2,
4165 const APInt &DemandedElts, const SimplifyQuery &Q,
4166 unsigned Depth) {
4167 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4168 const APInt *C;
4169 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4170 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4171 !C->isZero() && !C->isOne() &&
4172 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4173 }
4174 return false;
4175}
4176
4177/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4178/// the shift is nuw or nsw.
4179static bool isNonEqualShl(const Value *V1, const Value *V2,
4180 const APInt &DemandedElts, const SimplifyQuery &Q,
4181 unsigned Depth) {
4182 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4183 const APInt *C;
4184 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4185 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4186 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4187 }
4188 return false;
4189}
4190
4191static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4192 const APInt &DemandedElts, const SimplifyQuery &Q,
4193 unsigned Depth) {
4194 // Check two PHIs are in same block.
4195 if (PN1->getParent() != PN2->getParent())
4196 return false;
4197
4199 bool UsedFullRecursion = false;
4200 for (const BasicBlock *IncomBB : PN1->blocks()) {
4201 if (!VisitedBBs.insert(IncomBB).second)
4202 continue; // Don't reprocess blocks that we have dealt with already.
4203 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4204 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4205 const APInt *C1, *C2;
4206 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4207 continue;
4208
4209 // Only one pair of phi operands is allowed for full recursion.
4210 if (UsedFullRecursion)
4211 return false;
4212
4214 RecQ.CtxI = IncomBB->getTerminator();
4215 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4216 return false;
4217 UsedFullRecursion = true;
4218 }
4219 return true;
4220}
4221
4222static bool isNonEqualSelect(const Value *V1, const Value *V2,
4223 const APInt &DemandedElts, const SimplifyQuery &Q,
4224 unsigned Depth) {
4225 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4226 if (!SI1)
4227 return false;
4228
4229 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4230 const Value *Cond1 = SI1->getCondition();
4231 const Value *Cond2 = SI2->getCondition();
4232 if (Cond1 == Cond2)
4233 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4234 DemandedElts, Q, Depth + 1) &&
4235 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4236 DemandedElts, Q, Depth + 1);
4237 }
4238 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4239 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4240}
4241
4242// Check to see if A is both a GEP and is the incoming value for a PHI in the
4243// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4244// one of them being the recursive GEP A and the other a ptr at same base and at
4245// the same/higher offset than B we are only incrementing the pointer further in
4246// loop if offset of recursive GEP is greater than 0.
4248 const SimplifyQuery &Q) {
4249 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4250 return false;
4251
4252 auto *GEPA = dyn_cast<GEPOperator>(A);
4253 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4254 return false;
4255
4256 // Handle 2 incoming PHI values with one being a recursive GEP.
4257 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4258 if (!PN || PN->getNumIncomingValues() != 2)
4259 return false;
4260
4261 // Search for the recursive GEP as an incoming operand, and record that as
4262 // Step.
4263 Value *Start = nullptr;
4264 Value *Step = const_cast<Value *>(A);
4265 if (PN->getIncomingValue(0) == Step)
4266 Start = PN->getIncomingValue(1);
4267 else if (PN->getIncomingValue(1) == Step)
4268 Start = PN->getIncomingValue(0);
4269 else
4270 return false;
4271
4272 // Other incoming node base should match the B base.
4273 // StartOffset >= OffsetB && StepOffset > 0?
4274 // StartOffset <= OffsetB && StepOffset < 0?
4275 // Is non-equal if above are true.
4276 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4277 // optimisation to inbounds GEPs only.
4278 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4279 APInt StartOffset(IndexWidth, 0);
4280 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4281 APInt StepOffset(IndexWidth, 0);
4282 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4283
4284 // Check if Base Pointer of Step matches the PHI.
4285 if (Step != PN)
4286 return false;
4287 APInt OffsetB(IndexWidth, 0);
4288 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4289 return Start == B &&
4290 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4291 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4292}
4293
4294static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4295 const SimplifyQuery &Q, unsigned Depth) {
4296 if (!Q.CtxI)
4297 return false;
4298
4299 // Try to infer NonEqual based on information from dominating conditions.
4300 if (Q.DC && Q.DT) {
4301 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4302 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4303 Value *Cond = BI->getCondition();
4304 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4305 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4307 /*LHSIsTrue=*/true, Depth)
4308 .value_or(false))
4309 return true;
4310
4311 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4312 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4314 /*LHSIsTrue=*/false, Depth)
4315 .value_or(false))
4316 return true;
4317 }
4318
4319 return false;
4320 };
4321
4322 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4323 IsKnownNonEqualFromDominatingCondition(V2))
4324 return true;
4325 }
4326
4327 if (!Q.AC)
4328 return false;
4329
4330 // Try to infer NonEqual based on information from assumptions.
4331 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4332 if (!AssumeVH)
4333 continue;
4334 CallInst *I = cast<CallInst>(AssumeVH);
4335
4336 assert(I->getFunction() == Q.CtxI->getFunction() &&
4337 "Got assumption for the wrong function!");
4338 assert(I->getIntrinsicID() == Intrinsic::assume &&
4339 "must be an assume intrinsic");
4340
4341 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4342 /*LHSIsTrue=*/true, Depth)
4343 .value_or(false) &&
4345 return true;
4346 }
4347
4348 return false;
4349}
4350
4351static bool isNonEqualURem(const Value *X, const Value *Rem,
4352 const SimplifyQuery &Q) {
4353 const Value *Y;
4354 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4355 return false;
4356
4357 // For a defined urem, X != X urem Y exactly when X u>= Y.
4358 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4360 return true;
4361
4362 std::optional<bool> Implied =
4364 return Implied && *Implied;
4365}
4366
4367/// Return true if it is known that V1 != V2.
4368static bool isKnownNonEqual(const Value *V1, const Value *V2,
4369 const APInt &DemandedElts, const SimplifyQuery &Q,
4370 unsigned Depth) {
4371 if (V1 == V2)
4372 return false;
4373 if (V1->getType() != V2->getType())
4374 // We can't look through casts yet.
4375 return false;
4376
4378 return false;
4379
4380 // See if we can recurse through (exactly one of) our operands. This
4381 // requires our operation be 1-to-1 and map every input value to exactly
4382 // one output value. Such an operation is invertible.
4383 auto *O1 = dyn_cast<Operator>(V1);
4384 auto *O2 = dyn_cast<Operator>(V2);
4385 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4386 if (auto Values = getInvertibleOperands(O1, O2))
4387 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4388 Depth + 1);
4389
4390 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4391 const PHINode *PN2 = cast<PHINode>(V2);
4392 // FIXME: This is missing a generalization to handle the case where one is
4393 // a PHI and another one isn't.
4394 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4395 return true;
4396 };
4397 }
4398
4399 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4400 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4401 return true;
4402
4403 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4404 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4405 return true;
4406
4407 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4408 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4409 return true;
4410
4411 if (V1->getType()->isIntOrIntVectorTy()) {
4412 // Are any known bits in V1 contradictory to known bits in V2? If V1
4413 // has a known zero where V2 has a known one, they must not be equal.
4414 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4415 if (!Known1.isUnknown()) {
4416 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4417 if (Known1.Zero.intersects(Known2.One) ||
4418 Known2.Zero.intersects(Known1.One))
4419 return true;
4420 }
4421 }
4422
4423 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4424 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4425 return true;
4426
4429 return true;
4430
4431 Value *A, *B;
4432 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4433 // Check PtrToInt type matches the pointer size.
4434 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4436 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4437
4438 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4439 return true;
4440
4441 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4442 return true;
4443
4444 return false;
4445}
4446
4447/// For vector constants, loop over the elements and find the constant with the
4448/// minimum number of sign bits. Return 0 if the value is not a vector constant
4449/// or if any element was not analyzed; otherwise, return the count for the
4450/// element with the minimum number of sign bits.
4452 const APInt &DemandedElts,
4453 unsigned TyBits) {
4454 const auto *CV = dyn_cast<Constant>(V);
4455 if (!CV || !isa<FixedVectorType>(CV->getType()))
4456 return 0;
4457
4458 unsigned MinSignBits = TyBits;
4459 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4460 for (unsigned i = 0; i != NumElts; ++i) {
4461 if (!DemandedElts[i])
4462 continue;
4463 // If we find a non-ConstantInt, bail out.
4464 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4465 if (!Elt)
4466 return 0;
4467
4468 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4469 }
4470
4471 return MinSignBits;
4472}
4473
4474static unsigned ComputeNumSignBitsImpl(const Value *V,
4475 const APInt &DemandedElts,
4476 const SimplifyQuery &Q, unsigned Depth);
4477
4478static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4479 const SimplifyQuery &Q, unsigned Depth) {
4480 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4481 assert(Result > 0 && "At least one sign bit needs to be present!");
4482 return Result;
4483}
4484
4485/// Return the number of times the sign bit of the register is replicated into
4486/// the other bits. We know that at least 1 bit is always equal to the sign bit
4487/// (itself), but other cases can give us information. For example, immediately
4488/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4489/// other, so we return 3. For vectors, return the number of sign bits for the
4490/// vector element with the minimum number of known sign bits of the demanded
4491/// elements in the vector specified by DemandedElts.
4492static unsigned ComputeNumSignBitsImpl(const Value *V,
4493 const APInt &DemandedElts,
4494 const SimplifyQuery &Q, unsigned Depth) {
4495 Type *Ty = V->getType();
4496#ifndef NDEBUG
4497 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4498
4499 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4500 assert(
4501 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4502 "DemandedElt width should equal the fixed vector number of elements");
4503 } else {
4504 assert(DemandedElts == APInt(1, 1) &&
4505 "DemandedElt width should be 1 for scalars");
4506 }
4507#endif
4508
4509 // We return the minimum number of sign bits that are guaranteed to be present
4510 // in V, so for undef we have to conservatively return 1. We don't have the
4511 // same behavior for poison though -- that's a FIXME today.
4512
4513 Type *ScalarTy = Ty->getScalarType();
4514 unsigned TyBits = ScalarTy->isPointerTy() ?
4515 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4516 Q.DL.getTypeSizeInBits(ScalarTy);
4517
4518 unsigned Tmp, Tmp2;
4519 unsigned FirstAnswer = 1;
4520
4521 // Note that ConstantInt is handled by the general computeKnownBits case
4522 // below.
4523
4525 return 1;
4526
4527 if (auto *U = dyn_cast<Operator>(V)) {
4528 switch (Operator::getOpcode(V)) {
4529 default: break;
4530 case Instruction::BitCast: {
4531 Value *Src = U->getOperand(0);
4532 Type *SrcTy = Src->getType();
4533
4534 // Skip if the source type is not an integer or integer vector type
4535 // This ensures we only process integer-like types
4536 if (!SrcTy->isIntOrIntVectorTy())
4537 break;
4538
4539 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4540
4541 // Bitcast 'large element' scalar/vector to 'small element' vector.
4542 if ((SrcBits % TyBits) != 0)
4543 break;
4544
4545 // Only proceed if the destination type is a fixed-size vector
4546 if (isa<FixedVectorType>(Ty)) {
4547 // Fast case - sign splat can be simply split across the small elements.
4548 // This works for both vector and scalar sources
4549 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4550 if (Tmp == SrcBits)
4551 return TyBits;
4552 }
4553 break;
4554 }
4555 case Instruction::SExt:
4556 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4557 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4558 Tmp;
4559
4560 case Instruction::SDiv: {
4561 const APInt *Denominator;
4562 // sdiv X, C -> adds log(C) sign bits.
4563 if (match(U->getOperand(1), m_APInt(Denominator))) {
4564
4565 // Ignore non-positive denominator.
4566 if (!Denominator->isStrictlyPositive())
4567 break;
4568
4569 // Calculate the incoming numerator bits.
4570 unsigned NumBits =
4571 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4572
4573 // Add floor(log(C)) bits to the numerator bits.
4574 return std::min(TyBits, NumBits + Denominator->logBase2());
4575 }
4576 break;
4577 }
4578
4579 case Instruction::SRem: {
4580 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4581
4582 const APInt *Denominator;
4583 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4584 // positive constant. This let us put a lower bound on the number of sign
4585 // bits.
4586 if (match(U->getOperand(1), m_APInt(Denominator))) {
4587
4588 // Ignore non-positive denominator.
4589 if (Denominator->isStrictlyPositive()) {
4590 // Calculate the leading sign bit constraints by examining the
4591 // denominator. Given that the denominator is positive, there are two
4592 // cases:
4593 //
4594 // 1. The numerator is positive. The result range is [0,C) and
4595 // [0,C) u< (1 << ceilLogBase2(C)).
4596 //
4597 // 2. The numerator is negative. Then the result range is (-C,0] and
4598 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4599 //
4600 // Thus a lower bound on the number of sign bits is `TyBits -
4601 // ceilLogBase2(C)`.
4602
4603 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4604 Tmp = std::max(Tmp, ResBits);
4605 }
4606 }
4607 return Tmp;
4608 }
4609
4610 case Instruction::AShr: {
4611 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4612 // ashr X, C -> adds C sign bits. Vectors too.
4613 const APInt *ShAmt;
4614 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4615 if (ShAmt->uge(TyBits))
4616 break; // Bad shift.
4617 unsigned ShAmtLimited = ShAmt->getZExtValue();
4618 Tmp += ShAmtLimited;
4619 if (Tmp > TyBits) Tmp = TyBits;
4620 }
4621 return Tmp;
4622 }
4623 case Instruction::Shl: {
4624 const APInt *ShAmt;
4625 Value *X = nullptr;
4626 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4627 // shl destroys sign bits.
4628 if (ShAmt->uge(TyBits))
4629 break; // Bad shift.
4630 // We can look through a zext (more or less treating it as a sext) if
4631 // all extended bits are shifted out.
4632 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4633 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4634 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4635 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4636 } else
4637 Tmp =
4638 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4639 if (ShAmt->uge(Tmp))
4640 break; // Shifted all sign bits out.
4641 Tmp2 = ShAmt->getZExtValue();
4642 return Tmp - Tmp2;
4643 }
4644 break;
4645 }
4646 case Instruction::And:
4647 case Instruction::Or:
4648 case Instruction::Xor: // NOT is handled here.
4649 // Logical binary ops preserve the number of sign bits at the worst.
4650 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4651 if (Tmp != 1) {
4652 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4653 FirstAnswer = std::min(Tmp, Tmp2);
4654 // We computed what we know about the sign bits as our first
4655 // answer. Now proceed to the generic code that uses
4656 // computeKnownBits, and pick whichever answer is better.
4657 }
4658 break;
4659
4660 case Instruction::Select: {
4661 // If we have a clamp pattern, we know that the number of sign bits will
4662 // be the minimum of the clamp min/max range.
4663 const Value *X;
4664 const APInt *CLow, *CHigh;
4665 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4666 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4667
4668 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4669 if (Tmp == 1)
4670 break;
4671 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4672 return std::min(Tmp, Tmp2);
4673 }
4674
4675 case Instruction::Add:
4676 // Add can have at most one carry bit. Thus we know that the output
4677 // is, at worst, one more bit than the inputs.
4678 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4679 if (Tmp == 1) break;
4680
4681 // Special case decrementing a value (ADD X, -1):
4682 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4683 if (CRHS->isAllOnesValue()) {
4684 KnownBits Known(TyBits);
4685 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4686
4687 // If the input is known to be 0 or 1, the output is 0/-1, which is
4688 // all sign bits set.
4689 if ((Known.Zero | 1).isAllOnes())
4690 return TyBits;
4691
4692 // If we are subtracting one from a positive number, there is no carry
4693 // out of the result.
4694 if (Known.isNonNegative())
4695 return Tmp;
4696 }
4697
4698 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4699 if (Tmp2 == 1)
4700 break;
4701 return std::min(Tmp, Tmp2) - 1;
4702
4703 case Instruction::Sub:
4704 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4705 if (Tmp2 == 1)
4706 break;
4707
4708 // Handle NEG.
4709 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4710 if (CLHS->isNullValue()) {
4711 KnownBits Known(TyBits);
4712 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4713 // If the input is known to be 0 or 1, the output is 0/-1, which is
4714 // all sign bits set.
4715 if ((Known.Zero | 1).isAllOnes())
4716 return TyBits;
4717
4718 // If the input is known to be positive (the sign bit is known clear),
4719 // the output of the NEG has the same number of sign bits as the
4720 // input.
4721 if (Known.isNonNegative())
4722 return Tmp2;
4723
4724 // Otherwise, we treat this like a SUB.
4725 }
4726
4727 // Sub can have at most one carry bit. Thus we know that the output
4728 // is, at worst, one more bit than the inputs.
4729 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4730 if (Tmp == 1)
4731 break;
4732 return std::min(Tmp, Tmp2) - 1;
4733
4734 case Instruction::Mul: {
4735 // The output of the Mul can be at most twice the valid bits in the
4736 // inputs.
4737 unsigned SignBitsOp0 =
4738 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4739 if (SignBitsOp0 == 1)
4740 break;
4741 unsigned SignBitsOp1 =
4742 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4743 if (SignBitsOp1 == 1)
4744 break;
4745 unsigned OutValidBits =
4746 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4747 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4748 }
4749
4750 case Instruction::PHI: {
4751 const PHINode *PN = cast<PHINode>(U);
4752 unsigned NumIncomingValues = PN->getNumIncomingValues();
4753 // Don't analyze large in-degree PHIs.
4754 if (NumIncomingValues > 4) break;
4755 // Unreachable blocks may have zero-operand PHI nodes.
4756 if (NumIncomingValues == 0) break;
4757
4758 // Take the minimum of all incoming values. This can't infinitely loop
4759 // because of our depth threshold.
4761 Tmp = TyBits;
4762 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4763 if (Tmp == 1) return Tmp;
4764 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4765 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4766 DemandedElts, RecQ, Depth + 1));
4767 }
4768 return Tmp;
4769 }
4770
4771 case Instruction::Trunc: {
4772 // If the input contained enough sign bits that some remain after the
4773 // truncation, then we can make use of that. Otherwise we don't know
4774 // anything.
4775 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4776 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4777 if (Tmp > (OperandTyBits - TyBits))
4778 return Tmp - (OperandTyBits - TyBits);
4779
4780 return 1;
4781 }
4782
4783 case Instruction::ExtractElement:
4784 // Look through extract element. At the moment we keep this simple and
4785 // skip tracking the specific element. But at least we might find
4786 // information valid for all elements of the vector (for example if vector
4787 // is sign extended, shifted, etc).
4788 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4789
4790 case Instruction::ShuffleVector: {
4791 // Collect the minimum number of sign bits that are shared by every vector
4792 // element referenced by the shuffle.
4793 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4794 if (!Shuf) {
4795 // FIXME: Add support for shufflevector constant expressions.
4796 return 1;
4797 }
4798 APInt DemandedLHS, DemandedRHS;
4799 // For undef elements, we don't know anything about the common state of
4800 // the shuffle result.
4801 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4802 return 1;
4803 Tmp = std::numeric_limits<unsigned>::max();
4804 if (!!DemandedLHS) {
4805 const Value *LHS = Shuf->getOperand(0);
4806 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4807 }
4808 // If we don't know anything, early out and try computeKnownBits
4809 // fall-back.
4810 if (Tmp == 1)
4811 break;
4812 if (!!DemandedRHS) {
4813 const Value *RHS = Shuf->getOperand(1);
4814 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4815 Tmp = std::min(Tmp, Tmp2);
4816 }
4817 // If we don't know anything, early out and try computeKnownBits
4818 // fall-back.
4819 if (Tmp == 1)
4820 break;
4821 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4822 return Tmp;
4823 }
4824 case Instruction::Call: {
4825 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4826 switch (II->getIntrinsicID()) {
4827 default:
4828 break;
4829 case Intrinsic::abs:
4830 Tmp =
4831 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4832 if (Tmp == 1)
4833 break;
4834
4835 // Absolute value reduces number of sign bits by at most 1.
4836 return Tmp - 1;
4837 case Intrinsic::smin:
4838 case Intrinsic::smax: {
4839 const APInt *CLow, *CHigh;
4840 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4841 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4842 }
4843 }
4844 }
4845 }
4846 }
4847 }
4848
4849 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4850 // use this information.
4851
4852 // If we can examine all elements of a vector constant successfully, we're
4853 // done (we can't do any better than that). If not, keep trying.
4854 if (unsigned VecSignBits =
4855 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4856 return VecSignBits;
4857
4858 KnownBits Known(TyBits);
4859 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4860
4861 // If we know that the sign bit is either zero or one, determine the number of
4862 // identical bits in the top of the input value.
4863 return std::max(FirstAnswer, Known.countMinSignBits());
4864}
4865
4867 const TargetLibraryInfo *TLI) {
4868 const Function *F = CB.getCalledFunction();
4869 if (!F)
4871
4872 if (F->isIntrinsic())
4873 return F->getIntrinsicID();
4874
4875 // We are going to infer semantics of a library function based on mapping it
4876 // to an LLVM intrinsic. Check that the library function is available from
4877 // this callbase and in this environment.
4878 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4880
4881 LibFunc Func = TLI->getLibFunc(CB);
4882 if (Func == NotLibFunc)
4884
4885 switch (Func) {
4886 default:
4887 break;
4888 case LibFunc_sin:
4889 case LibFunc_sinf:
4890 case LibFunc_sinl:
4891 return Intrinsic::sin;
4892 case LibFunc_cos:
4893 case LibFunc_cosf:
4894 case LibFunc_cosl:
4895 return Intrinsic::cos;
4896 case LibFunc_tan:
4897 case LibFunc_tanf:
4898 case LibFunc_tanl:
4899 return Intrinsic::tan;
4900 case LibFunc_asin:
4901 case LibFunc_asinf:
4902 case LibFunc_asinl:
4903 return Intrinsic::asin;
4904 case LibFunc_acos:
4905 case LibFunc_acosf:
4906 case LibFunc_acosl:
4907 return Intrinsic::acos;
4908 case LibFunc_atan:
4909 case LibFunc_atanf:
4910 case LibFunc_atanl:
4911 return Intrinsic::atan;
4912 case LibFunc_atan2:
4913 case LibFunc_atan2f:
4914 case LibFunc_atan2l:
4915 return Intrinsic::atan2;
4916 case LibFunc_sinh:
4917 case LibFunc_sinhf:
4918 case LibFunc_sinhl:
4919 return Intrinsic::sinh;
4920 case LibFunc_cosh:
4921 case LibFunc_coshf:
4922 case LibFunc_coshl:
4923 return Intrinsic::cosh;
4924 case LibFunc_tanh:
4925 case LibFunc_tanhf:
4926 case LibFunc_tanhl:
4927 return Intrinsic::tanh;
4928 case LibFunc_exp:
4929 case LibFunc_expf:
4930 case LibFunc_expl:
4931 return Intrinsic::exp;
4932 case LibFunc_exp2:
4933 case LibFunc_exp2f:
4934 case LibFunc_exp2l:
4935 return Intrinsic::exp2;
4936 case LibFunc_exp10:
4937 case LibFunc_exp10f:
4938 case LibFunc_exp10l:
4939 return Intrinsic::exp10;
4940 case LibFunc_log:
4941 case LibFunc_logf:
4942 case LibFunc_logl:
4943 return Intrinsic::log;
4944 case LibFunc_log10:
4945 case LibFunc_log10f:
4946 case LibFunc_log10l:
4947 return Intrinsic::log10;
4948 case LibFunc_log2:
4949 case LibFunc_log2f:
4950 case LibFunc_log2l:
4951 return Intrinsic::log2;
4952 case LibFunc_fabs:
4953 case LibFunc_fabsf:
4954 case LibFunc_fabsl:
4955 return Intrinsic::fabs;
4956 case LibFunc_fmin:
4957 case LibFunc_fminf:
4958 case LibFunc_fminl:
4959 return Intrinsic::minnum;
4960 case LibFunc_fmax:
4961 case LibFunc_fmaxf:
4962 case LibFunc_fmaxl:
4963 return Intrinsic::maxnum;
4964 case LibFunc_copysign:
4965 case LibFunc_copysignf:
4966 case LibFunc_copysignl:
4967 return Intrinsic::copysign;
4968 case LibFunc_floor:
4969 case LibFunc_floorf:
4970 case LibFunc_floorl:
4971 return Intrinsic::floor;
4972 case LibFunc_ceil:
4973 case LibFunc_ceilf:
4974 case LibFunc_ceill:
4975 return Intrinsic::ceil;
4976 case LibFunc_trunc:
4977 case LibFunc_truncf:
4978 case LibFunc_truncl:
4979 return Intrinsic::trunc;
4980 case LibFunc_rint:
4981 case LibFunc_rintf:
4982 case LibFunc_rintl:
4983 return Intrinsic::rint;
4984 case LibFunc_nearbyint:
4985 case LibFunc_nearbyintf:
4986 case LibFunc_nearbyintl:
4987 return Intrinsic::nearbyint;
4988 case LibFunc_round:
4989 case LibFunc_roundf:
4990 case LibFunc_roundl:
4991 return Intrinsic::round;
4992 case LibFunc_roundeven:
4993 case LibFunc_roundevenf:
4994 case LibFunc_roundevenl:
4995 return Intrinsic::roundeven;
4996 case LibFunc_pow:
4997 case LibFunc_powf:
4998 case LibFunc_powl:
4999 return Intrinsic::pow;
5000 case LibFunc_sqrt:
5001 case LibFunc_sqrtf:
5002 case LibFunc_sqrtl:
5003 return Intrinsic::sqrt;
5004 }
5005
5007}
5008
5009/// Given an exploded icmp instruction, return true if the comparison only
5010/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
5011/// the result of the comparison is true when the input value is signed.
5013 bool &TrueIfSigned) {
5014 switch (Pred) {
5015 case ICmpInst::ICMP_SLT: // True if LHS s< 0
5016 TrueIfSigned = true;
5017 return RHS.isZero();
5018 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
5019 TrueIfSigned = true;
5020 return RHS.isAllOnes();
5021 case ICmpInst::ICMP_SGT: // True if LHS s> -1
5022 TrueIfSigned = false;
5023 return RHS.isAllOnes();
5024 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
5025 TrueIfSigned = false;
5026 return RHS.isZero();
5027 case ICmpInst::ICMP_UGT:
5028 // True if LHS u> RHS and RHS == sign-bit-mask - 1
5029 TrueIfSigned = true;
5030 return RHS.isMaxSignedValue();
5031 case ICmpInst::ICMP_UGE:
5032 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5033 TrueIfSigned = true;
5034 return RHS.isMinSignedValue();
5035 case ICmpInst::ICMP_ULT:
5036 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5037 TrueIfSigned = false;
5038 return RHS.isMinSignedValue();
5039 case ICmpInst::ICMP_ULE:
5040 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
5041 TrueIfSigned = false;
5042 return RHS.isMaxSignedValue();
5043 default:
5044 return false;
5045 }
5046}
5047
5049 bool CondIsTrue,
5050 const Instruction *CtxI,
5051 KnownFPClass &KnownFromContext,
5052 unsigned Depth = 0) {
5053 Value *A, *B;
5055 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
5056 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
5057 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
5058 Depth + 1);
5059 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
5060 Depth + 1);
5061 return;
5062 }
5064 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
5065 Depth + 1);
5066 return;
5067 }
5068 CmpPredicate Pred;
5069 Value *LHS;
5070 uint64_t ClassVal = 0;
5071 const APFloat *CRHS;
5072 const APInt *RHS;
5073 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5074 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5075 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
5076 LHS != V);
5077 if (CmpVal == V)
5078 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5080 m_Specific(V), m_ConstantInt(ClassVal)))) {
5081 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5082 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5083 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5084 m_APInt(RHS)))) {
5085 bool TrueIfSigned;
5086 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5087 return;
5088 if (TrueIfSigned == CondIsTrue)
5089 KnownFromContext.signBitMustBeOne();
5090 else
5091 KnownFromContext.signBitMustBeZero();
5092 }
5093}
5094
5095/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5096/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5097/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5098/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5099/// exponent range is [-149, -2], but the 0 edge case is above this range).
5100static std::tuple<int, int, int>
5102 if (!Q.CtxI || !Q.DC || !Q.DT)
5104
5105 // Intersect the bounds implied by every dominating condition, keeping the
5106 // tightest maximum. A value may participate in multiple compares
5107 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5108 int MaxExp = APFloat::IEK_Inf;
5109 int MaxExpNonZero = APFloat::IEK_Inf;
5110
5111 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5112 CmpPredicate Pred;
5113 const APFloat *LimitC;
5114 if (!match(BI->getCondition(),
5115 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5116 continue;
5117
5118 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5119 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5120 continue;
5121
5122 // If fabs(x) <= K, implies the exponent min exp range.
5123 // if fabs(x) >= K, swap the successor
5124 bool IsLessEqual =
5125 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5126 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5127 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5128
5129 bool KnownStrictlyLess =
5130 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5131 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5132
5133 BasicBlockEdge Edge1(BI->getParent(),
5134 BI->getSuccessor(IsLessEqual ? 0 : 1));
5135 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5136 // frexp returns an exponent one greater than ilogb.
5137 int Exp = ilogb(*LimitC) + 1;
5138
5139 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5140 // exponent drops by one when K is exact power of two.
5141 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5142 --Exp;
5143
5144 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5145 // may exclude.
5146
5147 // TODO: Figure out lower bound to detect no-underflow.
5148 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5149 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5150 }
5151 }
5152
5153 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5154}
5155
5157 const SimplifyQuery &Q) {
5158 KnownFPClass KnownFromContext;
5159
5160 if (Q.CC && Q.CC->AffectedValues.contains(V))
5162 KnownFromContext);
5163
5164 if (!Q.CtxI)
5165 return KnownFromContext;
5166
5167 if (Q.DC && Q.DT) {
5168 // Handle dominating conditions.
5169 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5170 Value *Cond = BI->getCondition();
5171
5172 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5173 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5174 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5175 KnownFromContext);
5176
5177 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5178 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5179 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5180 KnownFromContext);
5181 }
5182 }
5183
5184 if (!Q.AC)
5185 return KnownFromContext;
5186
5187 // Try to restrict the floating-point classes based on information from
5188 // assumptions.
5189 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5190 if (!AssumeVH)
5191 continue;
5192 CallInst *I = cast<CallInst>(AssumeVH);
5193
5194 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5195 "Got assumption for the wrong function!");
5196 assert(I->getIntrinsicID() == Intrinsic::assume &&
5197 "must be an assume intrinsic");
5198
5199 if (!isValidAssumeForContext(I, Q))
5200 continue;
5201
5202 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5203 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5204 }
5205
5206 return KnownFromContext;
5207}
5208
5210 Value *Arm, bool Invert,
5211 const SimplifyQuery &SQ,
5212 unsigned Depth) {
5213
5214 KnownFPClass KnownSrc;
5216 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5217 Depth + 1);
5218 KnownSrc = KnownSrc.unionWith(Known);
5219 if (KnownSrc.isUnknown())
5220 return;
5221
5222 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5223 Known = KnownSrc;
5224}
5225
5226void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5227 FPClassTest InterestedClasses, KnownFPClass &Known,
5228 const SimplifyQuery &Q, unsigned Depth);
5229
5231 FPClassTest InterestedClasses,
5232 const SimplifyQuery &Q, unsigned Depth) {
5233 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5234 APInt DemandedElts =
5235 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5236 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5237}
5238
5240 const APInt &DemandedElts,
5241 FPClassTest InterestedClasses,
5243 const SimplifyQuery &Q,
5244 unsigned Depth) {
5245 if ((InterestedClasses &
5247 return;
5248
5249 KnownFPClass KnownSrc;
5250 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5251 KnownSrc, Q, Depth + 1);
5252 Known = KnownFPClass::fptrunc(KnownSrc);
5253}
5254
5256 switch (IID) {
5257 case Intrinsic::minimum:
5259 case Intrinsic::maximum:
5261 case Intrinsic::minimumnum:
5263 case Intrinsic::maximumnum:
5265 case Intrinsic::minnum:
5267 case Intrinsic::maxnum:
5269 default:
5270 llvm_unreachable("not a floating-point min-max intrinsic");
5271 }
5272}
5273
5274/// \return true if this is a floating point value that is known to have a
5275/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5276static bool isAbsoluteValueULEOne(const Value *V) {
5277 // TODO: Handle frexp
5278 // TODO: Other rounding intrinsics?
5279 // TODO: Try computeKnownExponentRangeFromContext
5280
5281 // fabs(x - floor(x)) <= 1
5282 const Value *SubFloorX;
5283 if (match(V, m_FSub(m_Value(SubFloorX),
5285 return true;
5286
5289}
5290
5291void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5292 FPClassTest InterestedClasses, KnownFPClass &Known,
5293 const SimplifyQuery &Q, unsigned Depth) {
5294 assert(Known.isUnknown() && "should not be called with known information");
5295
5296 if (!DemandedElts) {
5297 // No demanded elts, better to assume we don't know anything.
5298 Known.resetAll();
5299 return;
5300 }
5301
5302 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5303
5304 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5305 Known = KnownFPClass(CFP->getValueAPF());
5306 return;
5307 }
5308
5310 Known.setKnownFPClasses(fcPosZero);
5311 Known.setSignBit(false);
5312 return;
5313 }
5314
5315 if (isa<PoisonValue>(V)) {
5316 Known.setKnownFPClasses(fcNone);
5317 Known.setSignBit(false);
5318 return;
5319 }
5320
5321 // Try to handle fixed width vector constants
5322 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5323 const Constant *CV = dyn_cast<Constant>(V);
5324 if (VFVTy && CV) {
5325 Known.setKnownFPClasses(fcNone);
5326 bool SignBitAllZero = true;
5327 bool SignBitAllOne = true;
5328
5329 // For vectors, verify that each element is not NaN.
5330 unsigned NumElts = VFVTy->getNumElements();
5331 for (unsigned i = 0; i != NumElts; ++i) {
5332 if (!DemandedElts[i])
5333 continue;
5334
5335 Constant *Elt = CV->getAggregateElement(i);
5336 if (!Elt) {
5337 Known = KnownFPClass();
5338 return;
5339 }
5340 if (isa<PoisonValue>(Elt))
5341 continue;
5342 auto *CElt = dyn_cast<ConstantFP>(Elt);
5343 if (!CElt) {
5344 Known = KnownFPClass();
5345 return;
5346 }
5347
5348 const APFloat &C = CElt->getValueAPF();
5349 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5350 if (C.isNegative())
5351 SignBitAllZero = false;
5352 else
5353 SignBitAllOne = false;
5354 }
5355 if (SignBitAllOne != SignBitAllZero)
5356 Known.setSignBit(SignBitAllOne);
5357 return;
5358 }
5359
5360 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5361 Known.setKnownFPClasses(fcNone);
5362 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5363 Known |= CDS->getElementAsAPFloat(I).classify();
5364 return;
5365 }
5366
5367 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5368 // TODO: Handle complex aggregates
5369 Known.setKnownFPClasses(fcNone);
5370 for (const Use &Op : CA->operands()) {
5371 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5372 if (!CFP) {
5373 Known = KnownFPClass();
5374 return;
5375 }
5376
5377 Known |= CFP->getValueAPF().classify();
5378 }
5379
5380 return;
5381 }
5382
5383 FPClassTest KnownNotFromFlags = fcNone;
5384 if (const auto *CB = dyn_cast<CallBase>(V))
5385 KnownNotFromFlags |= CB->getRetNoFPClass();
5386 else if (const auto *Arg = dyn_cast<Argument>(V))
5387 KnownNotFromFlags |= Arg->getNoFPClass();
5388
5389 const Operator *Op = dyn_cast<Operator>(V);
5391 if (FPOp->hasNoNaNs())
5392 KnownNotFromFlags |= fcNan;
5393 if (FPOp->hasNoInfs())
5394 KnownNotFromFlags |= fcInf;
5395 }
5396
5397 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5398 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5399
5400 // We no longer need to find out about these bits from inputs if we can
5401 // assume this from flags/attributes.
5402 InterestedClasses &= ~KnownNotFromFlags;
5403
5404 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5405 Known.knownNot(KnownNotFromFlags);
5406 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5407 if (*AssumedClasses.getSignBit())
5408 Known.signBitMustBeOne();
5409 else
5410 Known.signBitMustBeZero();
5411 }
5412 });
5413
5414 if (!Op)
5415 return;
5416
5417 // All recursive calls that increase depth must come after this.
5419 return;
5420
5421 const unsigned Opc = Op->getOpcode();
5422 switch (Opc) {
5423 case Instruction::FNeg: {
5424 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5425 Known, Q, Depth + 1);
5426 Known.fneg();
5427 break;
5428 }
5429 case Instruction::Select: {
5430 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5431 KnownFPClass Res;
5432 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5433 Depth + 1);
5434 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5435 Depth);
5436 return Res;
5437 };
5438 // Only known if known in both the LHS and RHS.
5439 Known =
5440 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5441 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5442 break;
5443 }
5444 case Instruction::Load: {
5445 const MDNode *NoFPClass =
5446 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5447 if (!NoFPClass)
5448 break;
5449
5450 ConstantInt *MaskVal =
5452 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5453 break;
5454 }
5455 case Instruction::Call: {
5456 const CallInst *II = cast<CallInst>(Op);
5457 const Intrinsic::ID IID = II->getIntrinsicID();
5458 switch (IID) {
5459 case Intrinsic::fabs: {
5460 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5461 // If we only care about the sign bit we don't need to inspect the
5462 // operand.
5463 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5464 InterestedClasses, Known, Q, Depth + 1);
5465 }
5466
5467 Known.fabs();
5468 break;
5469 }
5470 case Intrinsic::copysign: {
5471 KnownFPClass KnownSign;
5472
5473 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5474 Known, Q, Depth + 1);
5475 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5476 KnownSign, Q, Depth + 1);
5477 Known.copysign(KnownSign);
5478 break;
5479 }
5480 case Intrinsic::fma:
5481 case Intrinsic::fmuladd: {
5482 if ((InterestedClasses & (fcNegative | fcNan)) == fcNone)
5483 break;
5484
5485 const bool IsFMA = IID == Intrinsic::fma;
5486
5487 // FIXME: This should check isGuaranteedNotToBeUndef
5488 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5489 KnownFPClass KnownSrc, KnownAddend;
5490 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5491 InterestedClasses, KnownAddend, Q, Depth + 1);
5492 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5493 InterestedClasses, KnownSrc, Q, Depth + 1);
5494
5495 const Function *F = II->getFunction();
5496 const fltSemantics &FltSem =
5497 II->getType()->getScalarType()->getFltSemantics();
5499 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5500
5501 if ((KnownNotFromFlags & fcNan) == fcNan) {
5502 KnownSrc.knownNot(fcNan);
5503 KnownAddend.knownNot(fcNan);
5504 }
5505
5506 if ((KnownNotFromFlags & fcInf) == fcInf) {
5507 KnownSrc.knownNot(fcInf);
5508 KnownAddend.knownNot(fcInf);
5509 }
5510
5511 Known = IsFMA
5512 ? KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode)
5513 : KnownFPClass::fmuladd_square(KnownSrc, KnownAddend, Mode);
5514 break;
5515 }
5516
5517 KnownFPClass KnownSrc[3];
5518 for (int I = 0; I != 3; ++I) {
5519 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5520 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5521 if (KnownSrc[I].isUnknown())
5522 return;
5523
5524 if ((KnownNotFromFlags & fcNan) == fcNan)
5525 KnownSrc[I].knownNot(fcNan);
5526 if ((KnownNotFromFlags & fcInf) == fcInf)
5527 KnownSrc[I].knownNot(fcInf);
5528 }
5529
5530 const Function *F = II->getFunction();
5531 const fltSemantics &FltSem =
5532 II->getType()->getScalarType()->getFltSemantics();
5534 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5535 Known =
5536 IsFMA ? KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode)
5537 : KnownFPClass::fmuladd(KnownSrc[0], KnownSrc[1], KnownSrc[2],
5538 Mode);
5539 break;
5540 }
5541 case Intrinsic::sqrt:
5542 case Intrinsic::experimental_constrained_sqrt: {
5543 KnownFPClass KnownSrc;
5544 FPClassTest InterestedSrcs = InterestedClasses;
5545 if (InterestedClasses & fcNan)
5546 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5547
5548 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5549 KnownSrc, Q, Depth + 1);
5550
5552
5553 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5554 if (!HasNSZ) {
5555 const Function *F = II->getFunction();
5556 const fltSemantics &FltSem =
5557 II->getType()->getScalarType()->getFltSemantics();
5558 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5559 }
5560
5561 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5562 if (HasNSZ)
5563 Known.knownNot(fcNegZero);
5564
5565 break;
5566 }
5567 case Intrinsic::sin: {
5568 KnownFPClass KnownSrc;
5569 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5570 KnownSrc, Q, Depth + 1);
5571 Known = KnownFPClass::sin(KnownSrc);
5572 break;
5573 }
5574 case Intrinsic::cos: {
5575 KnownFPClass KnownSrc;
5576 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5577 KnownSrc, Q, Depth + 1);
5578 Known = KnownFPClass::cos(KnownSrc);
5579 break;
5580 }
5581 case Intrinsic::tan: {
5582 KnownFPClass KnownSrc;
5583 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5584 KnownSrc, Q, Depth + 1);
5585 Known = KnownFPClass::tan(KnownSrc);
5586 break;
5587 }
5588 case Intrinsic::sinh: {
5589 KnownFPClass KnownSrc;
5590 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5591 KnownSrc, Q, Depth + 1);
5592 Known = KnownFPClass::sinh(KnownSrc);
5593 break;
5594 }
5595 case Intrinsic::cosh: {
5596 KnownFPClass KnownSrc;
5597 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5598 KnownSrc, Q, Depth + 1);
5599 Known = KnownFPClass::cosh(KnownSrc);
5600 break;
5601 }
5602 case Intrinsic::tanh: {
5603 KnownFPClass KnownSrc;
5604 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5605 KnownSrc, Q, Depth + 1);
5606 Known = KnownFPClass::tanh(KnownSrc);
5607 break;
5608 }
5609 case Intrinsic::asin: {
5610 KnownFPClass KnownSrc;
5611 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5612 KnownSrc, Q, Depth + 1);
5613 Known = KnownFPClass::asin(KnownSrc);
5614 break;
5615 }
5616 case Intrinsic::acos: {
5617 KnownFPClass KnownSrc;
5618 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5619 KnownSrc, Q, Depth + 1);
5620 Known = KnownFPClass::acos(KnownSrc);
5621 break;
5622 }
5623 case Intrinsic::atan: {
5624 KnownFPClass KnownSrc;
5625 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5626 KnownSrc, Q, Depth + 1);
5627 Known = KnownFPClass::atan(KnownSrc);
5628 break;
5629 }
5630 case Intrinsic::atan2: {
5631 FPClassTest InterestedY = InterestedClasses;
5632 FPClassTest InterestedX = InterestedClasses;
5633
5634 // We can rule out negative values if y cannot have a negative value.
5635 if ((InterestedClasses & fcNegFinite) != fcNone)
5636 InterestedY |= fcNegative;
5637
5638 // We can rule out positive values if y cannot have a positive value.
5639 if ((InterestedClasses & fcPosFinite) != fcNone)
5640 InterestedY |= fcPositive | fcNegSubnormal;
5641
5642 // We can rule out zero and subnormal if x cannot have a positive value.
5643 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5644 InterestedX |= fcPositive | fcNegSubnormal;
5645
5646 KnownFPClass KnownY, KnownX;
5647 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5648 KnownY, Q, Depth + 1);
5649 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5650 KnownX, Q, Depth + 1);
5651
5652 const Function *F = II->getFunction();
5654 F ? F->getDenormalMode(
5655 II->getType()->getScalarType()->getFltSemantics())
5657 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5658 break;
5659 }
5660 case Intrinsic::maxnum:
5661 case Intrinsic::minnum:
5662 case Intrinsic::minimum:
5663 case Intrinsic::maximum:
5664 case Intrinsic::minimumnum:
5665 case Intrinsic::maximumnum: {
5666 KnownFPClass KnownLHS, KnownRHS;
5667 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5668 KnownLHS, Q, Depth + 1);
5669 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5670 KnownRHS, Q, Depth + 1);
5671
5672 const Function *F = II->getFunction();
5673
5675 F ? F->getDenormalMode(
5676 II->getType()->getScalarType()->getFltSemantics())
5678
5679 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5680 Mode);
5681 break;
5682 }
5683 case Intrinsic::canonicalize: {
5684 KnownFPClass KnownSrc;
5685 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5686 KnownSrc, Q, Depth + 1);
5687
5688 const Function *F = II->getFunction();
5689 DenormalMode DenormMode =
5690 F ? F->getDenormalMode(
5691 II->getType()->getScalarType()->getFltSemantics())
5693 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5694 break;
5695 }
5696 case Intrinsic::vector_reduce_fmax:
5697 case Intrinsic::vector_reduce_fmin:
5698 case Intrinsic::vector_reduce_fmaximum:
5699 case Intrinsic::vector_reduce_fminimum:
5700 case Intrinsic::vector_reduce_fmaximumnum:
5701 case Intrinsic::vector_reduce_fminimumnum: {
5702 // reduce min/max will choose an element from one of the vector elements,
5703 // so we can infer and class information that is common to all elements.
5704 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5705 InterestedClasses, Q, Depth + 1);
5706 // Can only propagate sign if output is never NaN.
5707 if (!Known.isKnownNeverNaN())
5708 Known.setSignBit(std::nullopt);
5709 break;
5710 }
5711 // reverse preserves all characteristics of the input vec's element.
5712 case Intrinsic::vector_reverse:
5714 II->getArgOperand(0), DemandedElts.reverseBits(),
5715 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5716 break;
5717 case Intrinsic::trunc:
5718 case Intrinsic::floor:
5719 case Intrinsic::ceil:
5720 case Intrinsic::rint:
5721 case Intrinsic::nearbyint:
5722 case Intrinsic::round:
5723 case Intrinsic::roundeven: {
5724 KnownFPClass KnownSrc;
5725 FPClassTest InterestedSrcs = InterestedClasses;
5726
5727 // Negative round ups towards zero produce negative zero.
5728 if (InterestedSrcs & fcNegFinite)
5729 InterestedSrcs |= fcNegFinite;
5730
5731 // Negative subnormals may flush to positive zero.
5732 if (InterestedSrcs & fcPosFinite)
5733 InterestedSrcs |= fcPosFinite | fcNegSubnormal;
5734
5735 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5736 KnownSrc, Q, Depth + 1);
5737
5738 const Function *F = II->getFunction();
5740 F ? F->getDenormalMode(
5741 II->getType()->getScalarType()->getFltSemantics())
5743 const bool IsMultiUnitFPType =
5744 V->getType()->getScalarType()->isMultiUnitFPType();
5745
5746 switch (IID) {
5747 case Intrinsic::trunc:
5748 Known = KnownFPClass::trunc(KnownSrc, Mode);
5749 break;
5750 case Intrinsic::floor:
5751 Known = KnownFPClass::floor(KnownSrc, IsMultiUnitFPType, Mode);
5752 break;
5753 case Intrinsic::ceil:
5754 Known = KnownFPClass::ceil(KnownSrc, IsMultiUnitFPType, Mode);
5755 break;
5756 default:
5757 Known =
5758 KnownFPClass::roundToIntegral(KnownSrc, IsMultiUnitFPType, Mode);
5759 break;
5760 }
5761 break;
5762 }
5763 case Intrinsic::exp:
5764 case Intrinsic::exp2:
5765 case Intrinsic::exp10:
5766 case Intrinsic::amdgcn_exp2: {
5767 KnownFPClass KnownSrc;
5768 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5769 KnownSrc, Q, Depth + 1);
5770
5771 Known = KnownFPClass::exp(KnownSrc);
5772
5773 Type *EltTy = II->getType()->getScalarType();
5774 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5775 Known.knownNot(fcSubnormal);
5776
5777 break;
5778 }
5779 case Intrinsic::fptrunc_round: {
5780 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5781 Q, Depth);
5782 break;
5783 }
5784 case Intrinsic::log:
5785 case Intrinsic::log10:
5786 case Intrinsic::log2:
5787 case Intrinsic::experimental_constrained_log:
5788 case Intrinsic::experimental_constrained_log10:
5789 case Intrinsic::experimental_constrained_log2:
5790 case Intrinsic::amdgcn_log: {
5791 FPClassTest InterestedSrcs = fcNone;
5792
5793 // log(negative) produces NaN.
5794 if ((InterestedClasses & fcNan) != fcNone)
5795 InterestedSrcs |= fcNan | fcNegative;
5796
5797 // log(logical-zero) produces negative infinity.
5798 if ((InterestedClasses & fcNegInf) != fcNone)
5799 InterestedSrcs |= fcZero | fcSubnormal;
5800
5801 // log(x) < -0.0 if x < +1.0
5802 if ((InterestedClasses & fcNegNormal) != fcNone)
5803 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5804
5805 // log(x) >= +0.0 if x >= +1.0
5806 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5807 InterestedSrcs |= fcPosNormal;
5808
5809 // log(x) is positive infinity iff x is positive infinity.
5810 if ((InterestedClasses & fcPosInf) != fcNone)
5811 InterestedSrcs |= fcPosInf;
5812
5813 KnownFPClass KnownSrc;
5814 if (InterestedSrcs != fcNone)
5815 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5816 KnownSrc, Q, Depth + 1);
5817 const Function *F = II->getFunction();
5819 F ? F->getDenormalMode(
5820 II->getType()->getScalarType()->getFltSemantics())
5822 const bool IsMultiUnitFPType =
5823 V->getType()->getScalarType()->isMultiUnitFPType();
5824 Known = KnownFPClass::log(KnownSrc, Mode, IsMultiUnitFPType);
5825 break;
5826 }
5827 case Intrinsic::pow: {
5828 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5829 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5830 if (!WantNaN && !WantNegative)
5831 break;
5832
5833 FPClassTest InterestedLHS = fcNone;
5834 FPClassTest InterestedRHS = fcNone;
5835 if (WantNaN) {
5836 // pow may return NaN if one of the arguments is NaN. NaN may also be
5837 // produced from a negative, non-zero finite base and a non-integer
5838 // exponent.
5839 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5840 InterestedRHS |= fcNan;
5841 }
5842 if (WantNegative) {
5843 // A negative value is returned when a negative base is raised to an odd
5844 // integer power. Only normal values can be odd integers.
5845 InterestedLHS |= fcNegative;
5846 InterestedRHS |= fcNormal;
5847 }
5848
5849 KnownFPClass KnownLHS;
5850 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5851 KnownLHS, Q, Depth + 1);
5852
5853 // If the LHS is unknown, then querying the RHS is only useful for rare
5854 // edge cases.
5855 if (KnownLHS.isUnknown())
5856 break;
5857
5858 KnownFPClass KnownRHS;
5859 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5860 KnownRHS, Q, Depth + 1);
5861 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5862 break;
5863 }
5864 case Intrinsic::powi: {
5865 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5866 break;
5867
5868 // The exponent is always a scalar, even when raising a vector to a power.
5869 const Value *Exp = II->getArgOperand(1);
5870 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5871 KnownBits ExponentKnownBits(BitWidth);
5872 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5873
5874 FPClassTest InterestedSrcs = fcNone;
5875 if (InterestedClasses & fcNan)
5876 InterestedSrcs |= fcNan;
5877 if (!ExponentKnownBits.isZero()) {
5878 if (InterestedClasses & fcInf)
5879 InterestedSrcs |= fcFinite | fcInf;
5880 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5881 InterestedSrcs |= fcNegative;
5882 }
5883
5884 KnownFPClass KnownSrc;
5885 if (InterestedSrcs != fcNone)
5886 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5887 KnownSrc, Q, Depth + 1);
5888
5889 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5890 break;
5891 }
5892 case Intrinsic::ldexp: {
5893 KnownFPClass KnownSrc;
5894 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5895 KnownSrc, Q, Depth + 1);
5896 // Can refine inf/zero handling based on the exponent operand.
5897 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5898
5899 const Value *ExpArg = II->getArgOperand(1);
5900 ConstantRange ExpKnownRange =
5901 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5902 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5903 : ConstantRange::getFull(
5904 ExpArg->getType()->getScalarSizeInBits());
5905
5906 const fltSemantics &Flt =
5907 II->getType()->getScalarType()->getFltSemantics();
5908
5909 const Function *F = II->getFunction();
5911 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5912
5913 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5914 ExpKnownRange.getSignedMax(), Flt, Mode);
5915 break;
5916 }
5917 case Intrinsic::arithmetic_fence: {
5918 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5919 Known, Q, Depth + 1);
5920 break;
5921 }
5922 case Intrinsic::experimental_constrained_sitofp:
5923 case Intrinsic::experimental_constrained_uitofp:
5924 // Cannot produce nan
5925 Known.knownNot(fcNan);
5926
5927 // sitofp and uitofp turn into +0.0 for zero.
5928 Known.knownNot(fcNegZero);
5929
5930 // Integers cannot be subnormal
5931 Known.knownNot(fcSubnormal);
5932
5933 if (IID == Intrinsic::experimental_constrained_uitofp)
5934 Known.signBitMustBeZero();
5935
5936 // TODO: Copy inf handling from instructions
5937 break;
5938
5939 case Intrinsic::amdgcn_fract: {
5940 Known.knownNot(fcInf);
5941
5942 if (InterestedClasses & fcNan) {
5943 KnownFPClass KnownSrc;
5944 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5945 InterestedClasses, KnownSrc, Q, Depth + 1);
5946
5947 if (KnownSrc.isKnownNeverInfOrNaN())
5948 Known.knownNot(fcNan);
5949 else if (KnownSrc.isKnownNever(fcSNan))
5950 Known.knownNot(fcSNan);
5951 }
5952
5953 break;
5954 }
5955 case Intrinsic::amdgcn_rcp: {
5956 KnownFPClass KnownSrc;
5957 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5958 KnownSrc, Q, Depth + 1);
5959
5960 Known.propagateNonNaN(KnownSrc);
5961
5962 Type *EltTy = II->getType()->getScalarType();
5963
5964 // f32 denormal always flushed.
5965 if (EltTy->isFloatTy()) {
5966 Known.knownNot(fcSubnormal);
5967 KnownSrc.knownNot(fcSubnormal);
5968 }
5969
5970 if (KnownSrc.isKnownNever(fcNegative))
5971 Known.knownNot(fcNegative);
5972 if (KnownSrc.isKnownNever(fcPositive))
5973 Known.knownNot(fcPositive);
5974
5975 if (const Function *F = II->getFunction()) {
5976 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5977 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5978 Known.knownNot(fcPosInf);
5979 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5980 Known.knownNot(fcNegInf);
5981 }
5982
5983 break;
5984 }
5985 case Intrinsic::amdgcn_rsq: {
5986 KnownFPClass KnownSrc;
5987 // The only negative value that can be returned is -inf for -0 inputs.
5989
5990 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5991 KnownSrc, Q, Depth + 1);
5992
5993 // Negative -> nan
5994 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5995 Known.knownNot(fcNan);
5996 else if (KnownSrc.isKnownNever(fcSNan))
5997 Known.knownNot(fcSNan);
5998
5999 // +inf -> +0
6000 if (KnownSrc.isKnownNeverPosInfinity())
6001 Known.knownNot(fcPosZero);
6002
6003 Type *EltTy = II->getType()->getScalarType();
6004
6005 // f32 denormal always flushed.
6006 if (EltTy->isFloatTy())
6007 Known.knownNot(fcPosSubnormal);
6008
6009 if (const Function *F = II->getFunction()) {
6010 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
6011
6012 // -0 -> -inf
6013 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
6014 Known.knownNot(fcNegInf);
6015
6016 // +0 -> +inf
6017 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
6018 Known.knownNot(fcPosInf);
6019 }
6020
6021 break;
6022 }
6023 case Intrinsic::amdgcn_trig_preop: {
6024 // Always returns a value [0, 1)
6025 Known.knownNot(fcNan | fcInf | fcNegative);
6026 break;
6027 }
6028 case Intrinsic::convert_from_arbitrary_fp: {
6029 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
6030 StringRef FormatStr = cast<MDString>(MD)->getString();
6031
6032 const fltSemantics *SrcSemantics =
6034 if (!SrcSemantics)
6035 break;
6036
6037 const fltSemantics DstSemantics =
6038 II->getType()->getScalarType()->getFltSemantics();
6039
6040 if (!APFloat::semanticsHasNaN(*SrcSemantics))
6041 Known.knownNot(fcNan);
6042
6043 // fcInf can only be cleared if the source format has no Inf encoding
6044 // and the dst max exp can accommodate src max exp.
6045 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
6046 APFloat::semanticsMaxExponent(*SrcSemantics) <=
6047 APFloat::semanticsMaxExponent(DstSemantics))
6048 Known.knownNot(fcInf);
6049
6050 // Check and clear all neg flags for formats that do not have signed
6051 // representation.
6052 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
6053 Known.knownNot(fcNegative);
6054
6055 // Check if format has no zero at all (Float8E8M0FNU), or no negative
6056 // zero.
6057 if (!APFloat::semanticsHasZero(*SrcSemantics))
6058 Known.knownNot(fcZero);
6059 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
6060 Known.knownNot(fcNegZero);
6061
6062 // If src lands normally in dest, the result can never be subnormal.
6063 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6064 Known.knownNot(fcSubnormal);
6065 break;
6066 }
6067 default:
6068 break;
6069 }
6070
6071 break;
6072 }
6073 case Instruction::FAdd:
6074 case Instruction::FSub: {
6075 KnownFPClass KnownLHS, KnownRHS;
6076 bool WantNegative =
6077 Op->getOpcode() == Instruction::FAdd &&
6078 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
6079 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6080 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
6081
6082 if (!WantNaN && !WantNegative && !WantNegZero)
6083 break;
6084
6085 FPClassTest InterestedSrcs = InterestedClasses;
6086 if (WantNegative)
6087 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
6088 if (InterestedClasses & fcNan)
6089 InterestedSrcs |= fcInf;
6090 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
6091 KnownRHS, Q, Depth + 1);
6092
6093 // Special case fadd x, x, which is the canonical form of fmul x, 2.
6094 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
6095 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
6096 Depth + 1);
6097 if (Self)
6098 KnownLHS = KnownRHS;
6099
6100 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
6101 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
6102 WantNegZero || Opc == Instruction::FSub) {
6103
6104 // FIXME: Context function should always be passed in separately
6105 const Function *F = cast<Instruction>(Op)->getFunction();
6106 const fltSemantics &FltSem =
6107 Op->getType()->getScalarType()->getFltSemantics();
6109 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6110
6111 if (Self && Opc == Instruction::FAdd) {
6112 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6113 } else {
6114 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6115 // there's no point.
6116
6117 if (!Self) {
6118 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6119 KnownLHS, Q, Depth + 1);
6120 }
6121
6122 Known = Opc == Instruction::FAdd
6123 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6124 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6125 }
6126 }
6127
6128 break;
6129 }
6130 case Instruction::FMul: {
6131 const Function *F = cast<Instruction>(Op)->getFunction();
6133 F ? F->getDenormalMode(
6134 Op->getType()->getScalarType()->getFltSemantics())
6136
6137 Value *LHS = Op->getOperand(0);
6138 Value *RHS = Op->getOperand(1);
6139 // X * X is always non-negative or a NaN.
6140 if (LHS == RHS &&
6141 isGuaranteedNotToBeUndef(LHS, Q.AC, Q.CtxI, Q.DT, Depth + 1)) {
6142 KnownFPClass KnownSrc;
6143 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6144 Depth + 1);
6145 Known = KnownFPClass::square(KnownSrc, Mode);
6146 break;
6147 }
6148
6149 KnownFPClass KnownLHS, KnownRHS;
6150
6151 const APFloat *CRHS;
6152 if (match(RHS, m_APFloat(CRHS))) {
6153 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6154 Depth + 1);
6155 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6156 } else {
6157 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6158 Depth + 1);
6159 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6160 // additional not-nan if the addend is known-not negative infinity if the
6161 // multiply is known-not infinity.
6162
6163 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6164 Depth + 1);
6165 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6166 }
6167
6168 /// Propgate no-infs if the other source is known smaller than one, such
6169 /// that this cannot introduce overflow.
6170 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6171 Known.knownNot(fcInf);
6172 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6173 Known.knownNot(fcInf);
6174
6175 break;
6176 }
6177 case Instruction::FDiv: {
6178 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6179
6180 const Function *F = cast<Instruction>(Op)->getFunction();
6181 const fltSemantics &FltSem =
6182 Op->getType()->getScalarType()->getFltSemantics();
6184 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6185
6186 if (Op->getOperand(0) == Op->getOperand(1) &&
6187 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6188 // X / X is always exactly 1.0 or a NaN.
6189 Known.setKnownFPClasses(fcNan | fcPosNormal);
6190
6191 if (!WantNan)
6192 break;
6193
6194 KnownFPClass KnownSrc;
6195 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6196 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6197 Depth + 1);
6198
6199 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6200 break;
6201 }
6202
6203 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6204 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6205 if (!WantNan && !WantNegative && !WantPositive)
6206 break;
6207
6208 KnownFPClass KnownLHS, KnownRHS;
6209 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6210 Q, Depth + 1);
6211
6212 bool KnowSomethingUseful =
6213 KnownRHS.isKnownNeverNaN() ||
6216
6217 if (KnowSomethingUseful)
6218 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6219 Q, Depth + 1);
6220
6221 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6222 break;
6223 }
6224 case Instruction::FRem: {
6225 FPClassTest InterestedLHS = fcNone;
6226 FPClassTest InterestedRHS = fcNone;
6227
6228 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
6229 if (InterestedClasses & fcNan) {
6230 InterestedLHS |= fcNan | fcInf;
6231 InterestedRHS |= fcNan | fcZero | fcSubnormal;
6232 }
6233
6234 // The sign for frem is the same as the first operand.
6235 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
6236 InterestedLHS |= fcPosNormal | fcPosSubnormal;
6237 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
6238 InterestedLHS |= fcNegNormal | fcNegSubnormal;
6239
6240 // A negative zero result requires a negative finite first operand.
6241 if (InterestedClasses & fcNegZero)
6242 InterestedLHS |= fcNegFinite;
6243
6244 // A positive zero result can additionally come from a negative finite
6245 // result being flushed to positive zero.
6246 if (InterestedClasses & fcPosZero)
6247 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
6248
6249 const Function *F = cast<Instruction>(Op)->getFunction();
6251 F ? F->getDenormalMode(
6252 Op->getType()->getScalarType()->getFltSemantics())
6254
6255 if (Op->getOperand(0) == Op->getOperand(1) &&
6256 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6257 // X % X is always exactly [+-]0.0 or a NaN.
6258 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
6259 KnownFPClass KnownSrc;
6260 if (InterestedSrcs != fcNone)
6261 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6262 KnownSrc, Q, Depth + 1);
6263 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6264 break;
6265 }
6266
6267 KnownFPClass KnownLHS;
6268 if (InterestedLHS != fcNone)
6269 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedLHS,
6270 KnownLHS, Q, Depth + 1);
6271
6272 KnownFPClass KnownRHS;
6273 // RHS is only useful for refining NaN classes.
6274 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
6275 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
6276 KnownRHS, Q, Depth + 1);
6277
6278 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6279
6280 break;
6281 }
6282 case Instruction::FPExt: {
6283 KnownFPClass KnownSrc;
6284 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6285 KnownSrc, Q, Depth + 1);
6286
6287 const fltSemantics &DstTy =
6288 Op->getType()->getScalarType()->getFltSemantics();
6289 const fltSemantics &SrcTy =
6290 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6291
6292 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6293 break;
6294 }
6295 case Instruction::FPTrunc: {
6296 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6297 Depth);
6298 break;
6299 }
6300 case Instruction::SIToFP:
6301 case Instruction::UIToFP: {
6302 // Cannot produce nan
6303 Known.knownNot(fcNan);
6304
6305 // Integers cannot be subnormal
6306 Known.knownNot(fcSubnormal);
6307
6308 // sitofp and uitofp turn into +0.0 for zero.
6309 Known.knownNot(fcNegZero);
6310
6311 // UIToFP is always non-negative regardless of known bits.
6312 if (Op->getOpcode() == Instruction::UIToFP)
6313 Known.signBitMustBeZero();
6314
6315 // Only compute known bits if we can learn something useful from them.
6316 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6317 break;
6318
6319 KnownBits IntKnown =
6320 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6321
6322 // If the integer is non-zero, the result cannot be +0.0
6323 if (IntKnown.isNonZero())
6324 Known.knownNot(fcPosZero);
6325
6326 if (Op->getOpcode() == Instruction::SIToFP) {
6327 // If the signed integer is known non-negative, the result is
6328 // non-negative. If the signed integer is known negative, the result is
6329 // negative.
6330 if (IntKnown.isNonNegative()) {
6331 Known.signBitMustBeZero();
6332 } else if (IntKnown.isNegative()) {
6333 Known.signBitMustBeOne();
6334 }
6335 }
6336
6337 // Guard kept for ilogb()
6338 if (InterestedClasses & fcInf) {
6339 // Get width of largest magnitude integer known.
6340 // This still works for a signed minimum value because the largest FP
6341 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6342 int IntSize = IntKnown.getBitWidth();
6343 if (Op->getOpcode() == Instruction::UIToFP)
6344 IntSize -= IntKnown.countMinLeadingZeros();
6345 else if (Op->getOpcode() == Instruction::SIToFP)
6346 IntSize -= IntKnown.countMinSignBits();
6347
6348 // If the exponent of the largest finite FP value can hold the largest
6349 // integer, the result of the cast must be finite.
6350 Type *FPTy = Op->getType()->getScalarType();
6351 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6352 Known.knownNot(fcInf);
6353 }
6354
6355 break;
6356 }
6357 case Instruction::ExtractElement: {
6358 // Look through extract element. If the index is non-constant or
6359 // out-of-range demand all elements, otherwise just the extracted element.
6360 const Value *Vec = Op->getOperand(0);
6361
6362 APInt DemandedVecElts;
6363 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6364 unsigned NumElts = VecTy->getNumElements();
6365 DemandedVecElts = APInt::getAllOnes(NumElts);
6366 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6367 if (CIdx && CIdx->getValue().ult(NumElts))
6368 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6369 } else {
6370 DemandedVecElts = APInt(1, 1);
6371 }
6372
6373 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6374 Q, Depth + 1);
6375 }
6376 case Instruction::InsertElement: {
6377 if (isa<ScalableVectorType>(Op->getType()))
6378 return;
6379
6380 const Value *Vec = Op->getOperand(0);
6381 const Value *Elt = Op->getOperand(1);
6382 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6383 unsigned NumElts = DemandedElts.getBitWidth();
6384 APInt DemandedVecElts = DemandedElts;
6385 bool NeedsElt = true;
6386 // If we know the index we are inserting to, clear it from Vec check.
6387 if (CIdx && CIdx->getValue().ult(NumElts)) {
6388 DemandedVecElts.clearBit(CIdx->getZExtValue());
6389 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6390 }
6391
6392 // Do we demand the inserted element?
6393 if (NeedsElt) {
6394 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6395 // If we don't know any bits, early out.
6396 if (Known.isUnknown())
6397 break;
6398 } else {
6399 Known.setKnownFPClasses(fcNone);
6400 }
6401
6402 // Do we need anymore elements from Vec?
6403 if (!DemandedVecElts.isZero()) {
6404 KnownFPClass Known2;
6405 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6406 Depth + 1);
6407 Known |= Known2;
6408 }
6409
6410 break;
6411 }
6412 case Instruction::ShuffleVector: {
6413 // Handle vector splat idiom
6414 if (Value *Splat = getSplatValue(V)) {
6415 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6416 break;
6417 }
6418
6419 // For undef elements, we don't know anything about the common state of
6420 // the shuffle result.
6421 APInt DemandedLHS, DemandedRHS;
6422 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6423 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6424 return;
6425
6426 if (!!DemandedLHS) {
6427 const Value *LHS = Shuf->getOperand(0);
6428 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6429 Depth + 1);
6430
6431 // If we don't know any bits, early out.
6432 if (Known.isUnknown())
6433 break;
6434 } else {
6435 Known.setKnownFPClasses(fcNone);
6436 }
6437
6438 if (!!DemandedRHS) {
6439 KnownFPClass Known2;
6440 const Value *RHS = Shuf->getOperand(1);
6441 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6442 Depth + 1);
6443 Known |= Known2;
6444 }
6445
6446 break;
6447 }
6448 case Instruction::ExtractValue: {
6449 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6450 ArrayRef<unsigned> Indices = Extract->getIndices();
6451 const Value *Src = Extract->getAggregateOperand();
6452 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6453 Indices[0] == 0) {
6454 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6455 switch (II->getIntrinsicID()) {
6456 case Intrinsic::frexp: {
6457 FPClassTest InterestedSrcs = InterestedClasses;
6458
6459 // Positive subnormals and negative subnormals could become positive
6460 // zero.
6461 if (InterestedClasses & fcPosZero)
6462 InterestedSrcs |= fcSubnormal;
6463
6464 // Negative subnormals could become negative zero.
6465 if (InterestedClasses & fcNegZero)
6466 InterestedSrcs |= fcNegSubnormal;
6467
6468 if (InterestedClasses & fcPosNormal)
6469 InterestedSrcs |= fcPosSubnormal;
6470
6471 if (InterestedClasses & fcNegNormal)
6472 InterestedSrcs |= fcNegSubnormal;
6473
6474 KnownFPClass KnownSrc;
6475 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6476 InterestedSrcs, KnownSrc, Q, Depth + 1);
6477
6478 const Function *F = cast<Instruction>(Op)->getFunction();
6479 const fltSemantics &FltSem =
6480 Op->getType()->getScalarType()->getFltSemantics();
6481
6483 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6484 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6485 return;
6486 }
6487 default:
6488 break;
6489 }
6490 }
6491 }
6492
6493 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6494 Depth + 1);
6495 break;
6496 }
6497 case Instruction::PHI: {
6498 const PHINode *P = cast<PHINode>(Op);
6499 // Unreachable blocks may have zero-operand PHI nodes.
6500 if (P->getNumIncomingValues() == 0)
6501 break;
6502
6503 // Otherwise take the unions of the known bit sets of the operands,
6504 // taking conservative care to avoid excessive recursion.
6505 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6506
6507 if (Depth < PhiRecursionLimit) {
6508 // Skip if every incoming value references to ourself.
6509 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6510 break;
6511
6512 bool First = true;
6513
6514 for (const Use &U : P->operands()) {
6515 Value *IncValue;
6516 Instruction *CtxI;
6517 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6518 // Skip direct self references.
6519 if (IncValue == P)
6520 continue;
6521
6522 KnownFPClass KnownSrc;
6523 // Recurse, but cap the recursion to two levels, because we don't want
6524 // to waste time spinning around in loops. We need at least depth 2 to
6525 // detect known sign bits.
6526 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6528 PhiRecursionLimit);
6529
6530 if (First) {
6531 Known = KnownSrc;
6532 First = false;
6533 } else {
6534 Known |= KnownSrc;
6535 }
6536
6537 if (Known.getKnownFPClasses() == fcAllFlags)
6538 break;
6539 }
6540 }
6541
6542 // Look for the case of a for loop which has a positive
6543 // initial value and is incremented by a squared value.
6544 // This will propagate sign information out of such loops.
6545 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6546 break;
6547 for (unsigned I = 0; I < 2; I++) {
6548 Value *RecurValue = P->getIncomingValue(1 - I);
6550 if (!II)
6551 continue;
6552 Value *R, *L, *Init;
6553 PHINode *PN;
6555 PN == P) {
6556 switch (II->getIntrinsicID()) {
6557 case Intrinsic::fma:
6558 case Intrinsic::fmuladd: {
6559 KnownFPClass KnownStart;
6560 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6561 Q, Depth + 1);
6562 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6563 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6565 break;
6566 }
6567 }
6568 }
6569 }
6570 break;
6571 }
6572 case Instruction::BitCast: {
6573 const Value *Src;
6574 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6575 !Src->getType()->isIntOrIntVectorTy())
6576 break;
6577
6578 const Type *Ty = Op->getType();
6579
6580 Value *CastLHS, *CastRHS;
6581
6582 // Match bitcast(umax(bitcast(a), bitcast(b)))
6583 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6584 m_BitCast(m_Value(CastRHS)))) &&
6585 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6586 KnownFPClass KnownLHS, KnownRHS;
6587 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6588 Depth + 1);
6589 if (!KnownRHS.isUnknown()) {
6590 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6591 Q, Depth + 1);
6592 Known = KnownLHS | KnownRHS;
6593 }
6594
6595 return;
6596 }
6597
6598 const Type *EltTy = Ty->getScalarType();
6599 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6600 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6601
6603 break;
6604 }
6605 default:
6606 break;
6607 }
6608}
6609
6611 const APInt &DemandedElts,
6612 FPClassTest InterestedClasses,
6613 const SimplifyQuery &SQ,
6614 unsigned Depth) {
6615 KnownFPClass KnownClasses;
6616 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6617 Depth);
6618 return KnownClasses;
6619}
6620
6622 FPClassTest InterestedClasses,
6623 const SimplifyQuery &SQ,
6624 unsigned Depth) {
6626 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6627 return Known;
6628}
6629
6631 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6632 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6633 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6634 return computeKnownFPClass(V, InterestedClasses,
6635 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6636 Depth);
6637}
6638
6640llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6641 FastMathFlags FMF, FPClassTest InterestedClasses,
6642 const SimplifyQuery &SQ, unsigned Depth) {
6643 if (FMF.noNaNs())
6644 InterestedClasses &= ~fcNan;
6645 if (FMF.noInfs())
6646 InterestedClasses &= ~fcInf;
6647
6648 KnownFPClass Result =
6649 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6650
6651 if (FMF.noNaNs())
6652 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6653 if (FMF.noInfs())
6654 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6655 return Result;
6656}
6657
6659 FPClassTest InterestedClasses,
6660 const SimplifyQuery &SQ,
6661 unsigned Depth) {
6662 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6663 APInt DemandedElts =
6664 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6665 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6666 Depth);
6667}
6668
6670 unsigned Depth) {
6672 return Known.isKnownNeverNegZero();
6673}
6674
6676 unsigned Depth) {
6679 return Known.cannotBeOrderedLessThanZero();
6680}
6681
6683 unsigned Depth) {
6685 return Known.isKnownNeverInfinity();
6686}
6687
6688/// Return true if the floating-point value can never contain a NaN or infinity.
6690 unsigned Depth) {
6692 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6693}
6694
6695/// Return true if the floating-point scalar value is not a NaN or if the
6696/// floating-point vector value has no NaN elements. Return false if a value
6697/// could ever be NaN.
6699 unsigned Depth) {
6701 return Known.isKnownNeverNaN();
6702}
6703
6704/// Return false if we can prove that the specified FP value's sign bit is 0.
6705/// Return true if we can prove that the specified FP value's sign bit is 1.
6706/// Otherwise return std::nullopt.
6707std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6708 const SimplifyQuery &SQ,
6709 unsigned Depth) {
6711 return Known.getSignBit();
6712}
6713
6715 auto *User = cast<Instruction>(U.getUser());
6716 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6717 if (FPOp->hasNoSignedZeros())
6718 return true;
6719 }
6720
6721 switch (User->getOpcode()) {
6722 case Instruction::FPToSI:
6723 case Instruction::FPToUI:
6724 return true;
6725 case Instruction::FCmp:
6726 // fcmp treats both positive and negative zero as equal.
6727 return true;
6728 case Instruction::Call:
6729 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6730 switch (II->getIntrinsicID()) {
6731 case Intrinsic::fabs:
6732 return true;
6733 case Intrinsic::copysign:
6734 return U.getOperandNo() == 0;
6735 case Intrinsic::is_fpclass: {
6736 auto Test =
6737 static_cast<FPClassTest>(
6738 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6741 }
6742 default:
6743 return false;
6744 }
6745 }
6746 return false;
6747 default:
6748 return false;
6749 }
6750}
6751
6753 auto *User = cast<Instruction>(U.getUser());
6754 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6755 if (FPOp->hasNoNaNs())
6756 return true;
6757 }
6758
6759 switch (User->getOpcode()) {
6760 case Instruction::FPToSI:
6761 case Instruction::FPToUI:
6762 return true;
6763 // Proper FP math operations ignore the sign bit of NaN.
6764 case Instruction::FAdd:
6765 case Instruction::FSub:
6766 case Instruction::FMul:
6767 case Instruction::FDiv:
6768 case Instruction::FRem:
6769 case Instruction::FPTrunc:
6770 case Instruction::FPExt:
6771 case Instruction::FCmp:
6772 return true;
6773 // Bitwise FP operations should preserve the sign bit of NaN.
6774 case Instruction::FNeg:
6775 case Instruction::Select:
6776 case Instruction::PHI:
6777 return false;
6778 case Instruction::Ret:
6779 return User->getFunction()->getAttributes().getRetNoFPClass() &
6781 case Instruction::Call:
6782 case Instruction::Invoke: {
6783 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6784 switch (II->getIntrinsicID()) {
6785 case Intrinsic::fabs:
6786 return true;
6787 case Intrinsic::copysign:
6788 return U.getOperandNo() == 0;
6789 // Other proper FP math intrinsics ignore the sign bit of NaN.
6790 case Intrinsic::maxnum:
6791 case Intrinsic::minnum:
6792 case Intrinsic::maximum:
6793 case Intrinsic::minimum:
6794 case Intrinsic::maximumnum:
6795 case Intrinsic::minimumnum:
6796 case Intrinsic::canonicalize:
6797 case Intrinsic::fma:
6798 case Intrinsic::fmuladd:
6799 case Intrinsic::sqrt:
6800 case Intrinsic::pow:
6801 case Intrinsic::powi:
6802 case Intrinsic::fptoui_sat:
6803 case Intrinsic::fptosi_sat:
6804 case Intrinsic::is_fpclass:
6805 return true;
6806 default:
6807 return false;
6808 }
6809 }
6810
6811 FPClassTest NoFPClass =
6812 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6813 return NoFPClass & FPClassTest::fcNan;
6814 }
6815 default:
6816 return false;
6817 }
6818}
6819
6821 FastMathFlags FMF) {
6822 if (isa<PoisonValue>(V))
6823 return true;
6824 if (isa<UndefValue>(V))
6825 return false;
6826
6827 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6828 return true;
6829
6831 if (!I)
6832 return false;
6833
6834 switch (I->getOpcode()) {
6835 case Instruction::SIToFP:
6836 case Instruction::UIToFP:
6837 // TODO: Could check nofpclass(inf) on incoming argument
6838 if (FMF.noInfs())
6839 return true;
6840
6841 // Need to check int size cannot produce infinity, which computeKnownFPClass
6842 // knows how to do already.
6843 return isKnownNeverInfinity(I, SQ);
6844 case Instruction::Call: {
6845 const CallInst *CI = cast<CallInst>(I);
6846 switch (CI->getIntrinsicID()) {
6847 case Intrinsic::trunc:
6848 case Intrinsic::floor:
6849 case Intrinsic::ceil:
6850 case Intrinsic::rint:
6851 case Intrinsic::nearbyint:
6852 case Intrinsic::round:
6853 case Intrinsic::roundeven:
6854 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6855 default:
6856 break;
6857 }
6858
6859 break;
6860 }
6861 default:
6862 break;
6863 }
6864
6865 return false;
6866}
6867
6869
6870 // All byte-wide stores are splatable, even of arbitrary variables.
6871 if (V->getType()->isIntegerTy(8))
6872 return V;
6873
6874 LLVMContext &Ctx = V->getContext();
6875
6876 // Undef don't care.
6877 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6878 if (isa<UndefValue>(V))
6879 return UndefInt8;
6880
6881 // Return poison for zero-sized type.
6882 if (DL.getTypeStoreSize(V->getType()).isZero())
6883 return PoisonValue::get(Type::getInt8Ty(Ctx));
6884
6886 if (!C) {
6887 // Conceptually, we could handle things like:
6888 // %a = zext i8 %X to i16
6889 // %b = shl i16 %a, 8
6890 // %c = or i16 %a, %b
6891 // but until there is an example that actually needs this, it doesn't seem
6892 // worth worrying about.
6893 return nullptr;
6894 }
6895
6896 // Handle 'null' ConstantArrayZero etc.
6897 if (C->isNullValue())
6899
6900 // Constant floating-point values can be handled as integer values if the
6901 // corresponding integer value is "byteable". An important case is 0.0.
6902 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6903 Type *ScalarTy = CFP->getType()->getScalarType();
6904 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6905 return isBytewiseValue(
6906 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6907
6908 // Don't handle long double formats, which have strange constraints.
6909 return nullptr;
6910 }
6911
6912 // We can handle constant integers that are multiple of 8 bits.
6913 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6914 if (CI->getBitWidth() % 8 == 0) {
6915 if (!CI->getValue().isSplat(8))
6916 return nullptr;
6917 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6918 }
6919 }
6920
6921 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6922 if (CE->getOpcode() == Instruction::IntToPtr) {
6923 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6924 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6926 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6927 return isBytewiseValue(Op, DL);
6928 }
6929 }
6930 }
6931
6932 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6933 if (LHS == RHS)
6934 return LHS;
6935 if (!LHS || !RHS)
6936 return nullptr;
6937 if (LHS == UndefInt8)
6938 return RHS;
6939 if (RHS == UndefInt8)
6940 return LHS;
6941 return nullptr;
6942 };
6943
6945 Value *Val = UndefInt8;
6946 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6947 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6948 return nullptr;
6949 return Val;
6950 }
6951
6953 Value *Val = UndefInt8;
6954 for (Value *Op : C->operands())
6955 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6956 return nullptr;
6957 return Val;
6958 }
6959
6960 // Don't try to handle the handful of other constants.
6961 return nullptr;
6962}
6963
6964// This is the recursive version of BuildSubAggregate. It takes a few different
6965// arguments. Idxs is the index within the nested struct From that we are
6966// looking at now (which is of type IndexedType). IdxSkip is the number of
6967// indices from Idxs that should be left out when inserting into the resulting
6968// struct. To is the result struct built so far, new insertvalue instructions
6969// build on that.
6970static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6972 unsigned IdxSkip,
6973 BasicBlock::iterator InsertBefore) {
6974 StructType *STy = dyn_cast<StructType>(IndexedType);
6975 if (STy) {
6976 // Save the original To argument so we can modify it
6977 Value *OrigTo = To;
6978 // General case, the type indexed by Idxs is a struct
6979 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6980 // Process each struct element recursively
6981 Idxs.push_back(i);
6982 Value *PrevTo = To;
6983 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6984 InsertBefore);
6985 Idxs.pop_back();
6986 if (!To) {
6987 // Couldn't find any inserted value for this index? Cleanup
6988 while (PrevTo != OrigTo) {
6990 PrevTo = Del->getAggregateOperand();
6991 Del->eraseFromParent();
6992 }
6993 // Stop processing elements
6994 break;
6995 }
6996 }
6997 // If we successfully found a value for each of our subaggregates
6998 if (To)
6999 return To;
7000 }
7001 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
7002 // the struct's elements had a value that was inserted directly. In the latter
7003 // case, perhaps we can't determine each of the subelements individually, but
7004 // we might be able to find the complete struct somewhere.
7005
7006 // Find the value that is at that particular spot
7007 Value *V = FindInsertedValue(From, Idxs);
7008
7009 if (!V)
7010 return nullptr;
7011
7012 // Insert the value in the new (sub) aggregate
7013 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
7014 InsertBefore);
7015}
7016
7017// This helper takes a nested struct and extracts a part of it (which is again a
7018// struct) into a new value. For example, given the struct:
7019// { a, { b, { c, d }, e } }
7020// and the indices "1, 1" this returns
7021// { c, d }.
7022//
7023// It does this by inserting an insertvalue for each element in the resulting
7024// struct, as opposed to just inserting a single struct. This will only work if
7025// each of the elements of the substruct are known (ie, inserted into From by an
7026// insertvalue instruction somewhere).
7027//
7028// All inserted insertvalue instructions are inserted before InsertBefore
7030 BasicBlock::iterator InsertBefore) {
7031 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
7032 idx_range);
7033 Value *To = PoisonValue::get(IndexedType);
7034 SmallVector<unsigned, 10> Idxs(idx_range);
7035 unsigned IdxSkip = Idxs.size();
7036
7037 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
7038}
7039
7040/// Given an aggregate and a sequence of indices, see if the scalar value
7041/// indexed is already around as a register, for example if it was inserted
7042/// directly into the aggregate.
7043///
7044/// If InsertBefore is not null, this function will duplicate (modified)
7045/// insertvalues when a part of a nested struct is extracted.
7046Value *
7048 std::optional<BasicBlock::iterator> InsertBefore) {
7049 // Nothing to index? Just return V then (this is useful at the end of our
7050 // recursion).
7051 if (idx_range.empty())
7052 return V;
7053 // We have indices, so V should have an indexable type.
7054 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
7055 "Not looking at a struct or array?");
7056 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
7057 "Invalid indices for type?");
7058
7059 if (Constant *C = dyn_cast<Constant>(V)) {
7060 C = C->getAggregateElement(idx_range[0]);
7061 if (!C) return nullptr;
7062 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
7063 }
7064
7066 // Loop the indices for the insertvalue instruction in parallel with the
7067 // requested indices
7068 const unsigned *req_idx = idx_range.begin();
7069 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7070 i != e; ++i, ++req_idx) {
7071 if (req_idx == idx_range.end()) {
7072 // We can't handle this without inserting insertvalues
7073 if (!InsertBefore)
7074 return nullptr;
7075
7076 // The requested index identifies a part of a nested aggregate. Handle
7077 // this specially. For example,
7078 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7079 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7080 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7081 // This can be changed into
7082 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7083 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7084 // which allows the unused 0,0 element from the nested struct to be
7085 // removed.
7086 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7087 *InsertBefore);
7088 }
7089
7090 // This insert value inserts something else than what we are looking for.
7091 // See if the (aggregate) value inserted into has the value we are
7092 // looking for, then.
7093 if (*req_idx != *i)
7094 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7095 InsertBefore);
7096 }
7097 // If we end up here, the indices of the insertvalue match with those
7098 // requested (though possibly only partially). Now we recursively look at
7099 // the inserted value, passing any remaining indices.
7100 return FindInsertedValue(I->getInsertedValueOperand(),
7101 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7102 }
7103
7105 // If we're extracting a value from an aggregate that was extracted from
7106 // something else, we can extract from that something else directly instead.
7107 // However, we will need to chain I's indices with the requested indices.
7108
7109 // Calculate the number of indices required
7110 unsigned size = I->getNumIndices() + idx_range.size();
7111 // Allocate some space to put the new indices in
7113 Idxs.reserve(size);
7114 // Add indices from the extract value instruction
7115 Idxs.append(I->idx_begin(), I->idx_end());
7116
7117 // Add requested indices
7118 Idxs.append(idx_range.begin(), idx_range.end());
7119
7120 assert(Idxs.size() == size
7121 && "Number of indices added not correct?");
7122
7123 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7124 }
7125 // Otherwise, we don't know (such as, extracting from a function return value
7126 // or load instruction)
7127 return nullptr;
7128}
7129
7130// If V refers to an initialized global constant, set Slice either to
7131// its initializer if the size of its elements equals ElementSize, or,
7132// for ElementSize == 8, to its representation as an array of unsiged
7133// char. Return true on success.
7134// Offset is in the unit "nr of ElementSize sized elements".
7137 unsigned ElementSize, uint64_t Offset) {
7138 assert(V && "V should not be null.");
7139 assert((ElementSize % 8) == 0 &&
7140 "ElementSize expected to be a multiple of the size of a byte.");
7141 unsigned ElementSizeInBytes = ElementSize / 8;
7142
7143 // Drill down into the pointer expression V, ignoring any intervening
7144 // casts, and determine the identity of the object it references along
7145 // with the cumulative byte offset into it.
7146 const GlobalVariable *GV =
7148 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7149 // Fail if V is not based on constant global object.
7150 return false;
7151
7152 const DataLayout &DL = GV->getDataLayout();
7153 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7154
7156 /*AllowNonInbounds*/ true))
7157 // Fail if a constant offset could not be determined.
7158 return false;
7159
7160 uint64_t StartIdx = Off.getLimitedValue();
7161 if (StartIdx == UINT64_MAX)
7162 // Fail if the constant offset is excessive.
7163 return false;
7164
7165 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7166 // elements. Simply bail out if that isn't possible.
7167 if ((StartIdx % ElementSizeInBytes) != 0)
7168 return false;
7169
7170 Offset += StartIdx / ElementSizeInBytes;
7171 ConstantDataArray *Array = nullptr;
7172 ArrayType *ArrayTy = nullptr;
7173
7174 if (GV->getInitializer()->isNullValue()) {
7175 Type *GVTy = GV->getValueType();
7176 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7177 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7178
7179 Slice.Array = nullptr;
7180 Slice.Offset = 0;
7181 // Return an empty Slice for undersized constants to let callers
7182 // transform even undefined library calls into simpler, well-defined
7183 // expressions. This is preferable to making the calls although it
7184 // prevents sanitizers from detecting such calls.
7185 Slice.Length = Length < Offset ? 0 : Length - Offset;
7186 return true;
7187 }
7188
7189 auto *Init = const_cast<Constant *>(GV->getInitializer());
7190 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7191 Type *InitElTy = ArrayInit->getElementType();
7192 if (InitElTy->isIntegerTy(ElementSize)) {
7193 // If Init is an initializer for an array of the expected type
7194 // and size, use it as is.
7195 Array = ArrayInit;
7196 ArrayTy = ArrayInit->getType();
7197 }
7198 }
7199
7200 if (!Array) {
7201 if (ElementSize != 8)
7202 // TODO: Handle conversions to larger integral types.
7203 return false;
7204
7205 // Otherwise extract the portion of the initializer starting
7206 // at Offset as an array of bytes, and reset Offset.
7208 if (!Init)
7209 return false;
7210
7211 Offset = 0;
7213 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7214 }
7215
7216 uint64_t NumElts = ArrayTy->getArrayNumElements();
7217 if (Offset > NumElts)
7218 return false;
7219
7220 Slice.Array = Array;
7221 Slice.Offset = Offset;
7222 Slice.Length = NumElts - Offset;
7223 return true;
7224}
7225
7226/// Extract bytes from the initializer of the constant array V, which need
7227/// not be a nul-terminated string. On success, store the bytes in Str and
7228/// return true. When TrimAtNul is set, Str will contain only the bytes up
7229/// to but not including the first nul. Return false on failure.
7231 bool TrimAtNul) {
7233 if (!getConstantDataArrayInfo(V, Slice, 8))
7234 return false;
7235
7236 if (Slice.Array == nullptr) {
7237 if (TrimAtNul) {
7238 // Return a nul-terminated string even for an empty Slice. This is
7239 // safe because all existing SimplifyLibcalls callers require string
7240 // arguments and the behavior of the functions they fold is undefined
7241 // otherwise. Folding the calls this way is preferable to making
7242 // the undefined library calls, even though it prevents sanitizers
7243 // from reporting such calls.
7244 Str = StringRef();
7245 return true;
7246 }
7247 if (Slice.Length == 1) {
7248 Str = StringRef("", 1);
7249 return true;
7250 }
7251 // We cannot instantiate a StringRef as we do not have an appropriate string
7252 // of 0s at hand.
7253 return false;
7254 }
7255
7256 // Start out with the entire array in the StringRef.
7257 Str = Slice.Array->getAsString();
7258 // Skip over 'offset' bytes.
7259 Str = Str.substr(Slice.Offset);
7260
7261 if (TrimAtNul) {
7262 // Trim off the \0 and anything after it. If the array is not nul
7263 // terminated, we just return the whole end of string. The client may know
7264 // some other way that the string is length-bound.
7265 Str = Str.substr(0, Str.find('\0'));
7266 }
7267 return true;
7268}
7269
7270// These next two are very similar to the above, but also look through PHI
7271// nodes.
7272// TODO: See if we can integrate these two together.
7273
7274/// If we can compute the length of the string pointed to by
7275/// the specified pointer, return 'len+1'. If we can't, return 0.
7278 unsigned CharSize) {
7279 // Look through noop bitcast instructions.
7280 V = V->stripPointerCasts();
7281
7282 // If this is a PHI node, there are two cases: either we have already seen it
7283 // or we haven't.
7284 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7285 if (!PHIs.insert(PN).second)
7286 return ~0ULL; // already in the set.
7287
7288 // If it was new, see if all the input strings are the same length.
7289 uint64_t LenSoFar = ~0ULL;
7290 for (Value *IncValue : PN->incoming_values()) {
7291 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7292 if (Len == 0) return 0; // Unknown length -> unknown.
7293
7294 if (Len == ~0ULL) continue;
7295
7296 if (Len != LenSoFar && LenSoFar != ~0ULL)
7297 return 0; // Disagree -> unknown.
7298 LenSoFar = Len;
7299 }
7300
7301 // Success, all agree.
7302 return LenSoFar;
7303 }
7304
7305 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7306 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7307 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7308 if (Len1 == 0) return 0;
7309 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7310 if (Len2 == 0) return 0;
7311 if (Len1 == ~0ULL) return Len2;
7312 if (Len2 == ~0ULL) return Len1;
7313 if (Len1 != Len2) return 0;
7314 return Len1;
7315 }
7316
7317 // Otherwise, see if we can read the string.
7319 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7320 return 0;
7321
7322 if (Slice.Array == nullptr)
7323 // Zeroinitializer (including an empty one).
7324 return 1;
7325
7326 // Search for the first nul character. Return a conservative result even
7327 // when there is no nul. This is safe since otherwise the string function
7328 // being folded such as strlen is undefined, and can be preferable to
7329 // making the undefined library call.
7330 unsigned NullIndex = 0;
7331 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7332 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7333 break;
7334 }
7335
7336 return NullIndex + 1;
7337}
7338
7339/// If we can compute the length of the string pointed to by
7340/// the specified pointer, return 'len+1'. If we can't, return 0.
7341uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7342 if (!V->getType()->isPointerTy())
7343 return 0;
7344
7346 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7347 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7348 // an empty string as a length.
7349 return Len == ~0ULL ? 1 : Len;
7350}
7351
7352const Value *
7354 bool MustPreserveOffset,
7355 bool MustPreserveProvenance) {
7356 assert(Call &&
7357 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7358 if (const Value *RV = Call->getReturnedArgOperand())
7359 return RV;
7360 // This can be used only as a aliasing property.
7362 Call, MustPreserveOffset, MustPreserveProvenance))
7363 return Call->getArgOperand(0);
7364 return nullptr;
7365}
7366
7368 const CallBase *Call, bool MustPreserveOffset,
7369 bool MustPreserveProvenance) {
7370 switch (Call->getIntrinsicID()) {
7371 case Intrinsic::launder_invariant_group:
7372 case Intrinsic::aarch64_irg:
7373 case Intrinsic::aarch64_tagp:
7374 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7375 // input pointer (and thus preserves the byte offset, which is the property
7376 // the MustPreserveOffset flag selects). However, it will not necessarily
7377 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7378 // descriptor", which has "all loads return 0, all stores are dropped"
7379 // semantics. Given the context of this intrinsic list, no one should be
7380 // relying on such a strict bit-exact null mapping (and, at time of
7381 // writing, they are not), but we document this fact out of an abundance
7382 // of caution.
7383 case Intrinsic::amdgcn_make_buffer_rsrc:
7384 return !MustPreserveProvenance;
7385 case Intrinsic::ptrmask:
7386 return !MustPreserveOffset;
7387 case Intrinsic::threadlocal_address:
7388 // The underlying variable changes with thread ID. The Thread ID may change
7389 // at coroutine suspend points.
7390 return !Call->getParent()->getParent()->isPresplitCoroutine();
7391 default:
7392 return false;
7393 }
7394}
7395
7396/// \p PN defines a loop-variant pointer to an object. Check if the
7397/// previous iteration of the loop was referring to the same object as \p PN.
7399 const LoopInfo *LI) {
7400 // Find the loop-defined value.
7401 Loop *L = LI->getLoopFor(PN->getParent());
7402 if (PN->getNumIncomingValues() != 2)
7403 return true;
7404
7405 // Find the value from previous iteration.
7406 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7407 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7408 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7409 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7410 return true;
7411
7412 // If a new pointer is loaded in the loop, the pointer references a different
7413 // object in every iteration. E.g.:
7414 // for (i)
7415 // int *p = a[i];
7416 // ...
7417 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7418 if (!L->isLoopInvariant(Load->getPointerOperand()))
7419 return false;
7420 return true;
7421}
7422
7423const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7424 bool MustPreserveProvenance) {
7425 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7426 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7427 const Value *PtrOp = GEP->getPointerOperand();
7428 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7429 return V;
7430 V = PtrOp;
7431 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7432 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7433 Value *NewV = cast<Operator>(V)->getOperand(0);
7434 if (!NewV->getType()->isPointerTy())
7435 return V;
7436 V = NewV;
7437 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7438 if (GA->isInterposable())
7439 return V;
7440 V = GA->getAliasee();
7441 } else {
7442 if (auto *PHI = dyn_cast<PHINode>(V)) {
7443 // Look through single-arg phi nodes created by LCSSA.
7444 if (PHI->getNumIncomingValues() == 1) {
7445 V = PHI->getIncomingValue(0);
7446 continue;
7447 }
7448 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7449 // CaptureTracking can know about special capturing properties of some
7450 // intrinsics like launder.invariant.group, that can't be expressed with
7451 // the attributes, but have properties like returning aliasing pointer.
7452 // Because some analysis may assume that nocaptured pointer is not
7453 // returned from some special intrinsic (because function would have to
7454 // be marked with returns attribute), it is crucial to use this function
7455 // because it should be in sync with CaptureTracking. Not using it may
7456 // cause weird miscompilations where 2 aliasing pointers are assumed to
7457 // noalias.
7459 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7460 V = RP;
7461 continue;
7462 }
7463 }
7464
7465 return V;
7466 }
7467 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7468 }
7469 return V;
7470}
7471
7474 const LoopInfo *LI, unsigned MaxLookup) {
7477 Worklist.push_back(V);
7478 do {
7479 const Value *P = Worklist.pop_back_val();
7480 P = getUnderlyingObject(P, MaxLookup);
7481
7482 if (!Visited.insert(P).second)
7483 continue;
7484
7485 if (auto *SI = dyn_cast<SelectInst>(P)) {
7486 Worklist.push_back(SI->getTrueValue());
7487 Worklist.push_back(SI->getFalseValue());
7488 continue;
7489 }
7490
7491 if (auto *PN = dyn_cast<PHINode>(P)) {
7492 // If this PHI changes the underlying object in every iteration of the
7493 // loop, don't look through it. Consider:
7494 // int **A;
7495 // for (i) {
7496 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7497 // Curr = A[i];
7498 // *Prev, *Curr;
7499 //
7500 // Prev is tracking Curr one iteration behind so they refer to different
7501 // underlying objects.
7502 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7504 append_range(Worklist, PN->incoming_values());
7505 else
7506 Objects.push_back(P);
7507 continue;
7508 }
7509
7510 Objects.push_back(P);
7511 } while (!Worklist.empty());
7512}
7513
7515 bool MustPreserveProvenance) {
7516 const unsigned MaxVisited = 8;
7517
7520 Worklist.push_back(V);
7521 const Value *Object = nullptr;
7522 // Used as fallback if we can't find a common underlying object through
7523 // recursion.
7524 bool First = true;
7525 const Value *FirstObject =
7526 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7527 do {
7528 const Value *P = Worklist.pop_back_val();
7529 P = First ? FirstObject
7531 MustPreserveProvenance);
7532 First = false;
7533
7534 if (!Visited.insert(P).second)
7535 continue;
7536
7537 if (Visited.size() == MaxVisited)
7538 return FirstObject;
7539
7540 if (auto *SI = dyn_cast<SelectInst>(P)) {
7541 Worklist.push_back(SI->getTrueValue());
7542 Worklist.push_back(SI->getFalseValue());
7543 continue;
7544 }
7545
7546 if (auto *PN = dyn_cast<PHINode>(P)) {
7547 append_range(Worklist, PN->incoming_values());
7548 continue;
7549 }
7550
7551 if (!Object)
7552 Object = P;
7553 else if (Object != P)
7554 return FirstObject;
7555 } while (!Worklist.empty());
7556
7557 return Object ? Object : FirstObject;
7558}
7559
7560/// This is the function that does the work of looking through basic
7561/// ptrtoint+arithmetic+inttoptr sequences.
7562static const Value *getUnderlyingObjectFromInt(const Value *V) {
7563 do {
7564 if (const Operator *U = dyn_cast<Operator>(V)) {
7565 // If we find a ptrtoint, we can transfer control back to the
7566 // regular getUnderlyingObjectFromInt.
7567 if (U->getOpcode() == Instruction::PtrToInt)
7568 return U->getOperand(0);
7569 // If we find an add of a constant, a multiplied value, or a phi, it's
7570 // likely that the other operand will lead us to the base
7571 // object. We don't have to worry about the case where the
7572 // object address is somehow being computed by the multiply,
7573 // because our callers only care when the result is an
7574 // identifiable object.
7575 if (U->getOpcode() != Instruction::Add ||
7576 (!isa<ConstantInt>(U->getOperand(1)) &&
7577 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7578 !isa<PHINode>(U->getOperand(1))))
7579 return V;
7580 V = U->getOperand(0);
7581 } else {
7582 return V;
7583 }
7584 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7585 } while (true);
7586}
7587
7588/// This is a wrapper around getUnderlyingObjects and adds support for basic
7589/// ptrtoint+arithmetic+inttoptr sequences.
7590/// It returns false if unidentified object is found in getUnderlyingObjects.
7592 SmallVectorImpl<Value *> &Objects) {
7594 SmallVector<const Value *, 4> Working(1, V);
7595 bool AllObjectsIdentified = true;
7596 do {
7597 V = Working.pop_back_val();
7598
7600 getUnderlyingObjects(V, Objs);
7601
7602 for (const Value *V : Objs) {
7603 if (!Visited.insert(V).second)
7604 continue;
7605 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7606 const Value *O =
7607 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7608 if (O->getType()->isPointerTy()) {
7609 Working.push_back(O);
7610 continue;
7611 }
7612 }
7613 AllObjectsIdentified &= isIdentifiedObject(V);
7614 Objects.push_back(const_cast<Value *>(V));
7615 }
7616 } while (!Working.empty());
7617 return AllObjectsIdentified;
7618}
7619
7621 AllocaInst *Result = nullptr;
7623 SmallVector<Value *, 4> Worklist;
7624
7625 auto AddWork = [&](Value *V) {
7626 if (Visited.insert(V).second)
7627 Worklist.push_back(V);
7628 };
7629
7630 AddWork(V);
7631 do {
7632 V = Worklist.pop_back_val();
7633 assert(Visited.count(V));
7634
7635 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7636 if (Result && Result != AI)
7637 return nullptr;
7638 Result = AI;
7639 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7640 AddWork(CI->getOperand(0));
7641 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7642 for (Value *IncValue : PN->incoming_values())
7643 AddWork(IncValue);
7644 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7645 AddWork(SI->getTrueValue());
7646 AddWork(SI->getFalseValue());
7648 if (OffsetZero && !GEP->hasAllZeroIndices())
7649 return nullptr;
7650 AddWork(GEP->getPointerOperand());
7651 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7652 Value *Returned = CB->getReturnedArgOperand();
7653 if (Returned)
7654 AddWork(Returned);
7655 else
7656 return nullptr;
7657 } else {
7658 return nullptr;
7659 }
7660 } while (!Worklist.empty());
7661
7662 return Result;
7663}
7664
7666 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7667 for (const User *U : V->users()) {
7669 if (!II)
7670 return false;
7671
7672 if (AllowLifetime && II->isLifetimeStartOrEnd())
7673 continue;
7674
7675 if (AllowDroppable && II->isDroppable())
7676 continue;
7677
7678 return false;
7679 }
7680 return true;
7681}
7682
7685 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7686}
7689 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7690}
7691
7693 if (auto *II = dyn_cast<IntrinsicInst>(I))
7694 return isTriviallyVectorizable(II->getIntrinsicID());
7695 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7696 return (!Shuffle || Shuffle->isSelect()) &&
7698}
7699
7701 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7702 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7703 bool IgnoreUBImplyingAttrs) {
7704 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7705 AC, DT, TLI, UseVariableInfo,
7706 IgnoreUBImplyingAttrs);
7707}
7708
7710 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7711 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7712 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7713#ifndef NDEBUG
7714 if (Inst->getOpcode() != Opcode) {
7715 // Check that the operands are actually compatible with the Opcode override.
7716 auto hasEqualReturnAndLeadingOperandTypes =
7717 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7718 if (Inst->getNumOperands() < NumLeadingOperands)
7719 return false;
7720 const Type *ExpectedType = Inst->getType();
7721 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7722 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7723 return false;
7724 return true;
7725 };
7727 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7728 assert(!Instruction::isUnaryOp(Opcode) ||
7729 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7730 }
7731#endif
7732
7733 switch (Opcode) {
7734 default:
7735 return true;
7736 case Instruction::UDiv:
7737 case Instruction::URem: {
7738 // x / y is undefined if y == 0.
7739 const APInt *V;
7740 if (match(Inst->getOperand(1), m_APInt(V)))
7741 return *V != 0;
7742 return false;
7743 }
7744 case Instruction::SDiv:
7745 case Instruction::SRem: {
7746 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7747 const APInt *Numerator, *Denominator;
7748 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7749 return false;
7750 // We cannot hoist this division if the denominator is 0.
7751 if (*Denominator == 0)
7752 return false;
7753 // It's safe to hoist if the denominator is not 0 or -1.
7754 if (!Denominator->isAllOnes())
7755 return true;
7756 // At this point we know that the denominator is -1. It is safe to hoist as
7757 // long we know that the numerator is not INT_MIN.
7758 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7759 return !Numerator->isMinSignedValue();
7760 // The numerator *might* be MinSignedValue.
7761 return false;
7762 }
7763 case Instruction::Load: {
7764 if (!UseVariableInfo)
7765 return false;
7766
7767 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7768 if (!LI)
7769 return false;
7770 if (mustSuppressSpeculation(*LI))
7771 return false;
7772 const DataLayout &DL = LI->getDataLayout();
7774 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7775 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7776 }
7777 case Instruction::Call: {
7778 auto *CI = dyn_cast<const CallInst>(Inst);
7779 if (!CI)
7780 return false;
7781 const Function *Callee = CI->getCalledFunction();
7782
7783 // The called function could have undefined behavior or side-effects, even
7784 // if marked readnone nounwind.
7785 if (!Callee || !Callee->isSpeculatable())
7786 return false;
7787 // Since the operands may be changed after hoisting, undefined behavior may
7788 // be triggered by some UB-implying attributes.
7789 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7790 }
7791 case Instruction::VAArg:
7792 case Instruction::Alloca:
7793 case Instruction::Invoke:
7794 case Instruction::CallBr:
7795 case Instruction::PHI:
7796 case Instruction::Store:
7797 case Instruction::Ret:
7798 case Instruction::UncondBr:
7799 case Instruction::CondBr:
7800 case Instruction::IndirectBr:
7801 case Instruction::Switch:
7802 case Instruction::Unreachable:
7803 case Instruction::Fence:
7804 case Instruction::AtomicRMW:
7805 case Instruction::AtomicCmpXchg:
7806 case Instruction::LandingPad:
7807 case Instruction::Resume:
7808 case Instruction::CatchSwitch:
7809 case Instruction::CatchPad:
7810 case Instruction::CatchRet:
7811 case Instruction::CleanupPad:
7812 case Instruction::CleanupRet:
7813 return false; // Misc instructions which have effects
7814 }
7815}
7816
7818 if (I.mayReadOrWriteMemory())
7819 // Memory dependency possible
7820 return true;
7822 // Can't move above a maythrow call or infinite loop. Or if an
7823 // inalloca alloca, above a stacksave call.
7824 return true;
7826 // 1) Can't reorder two inf-loop calls, even if readonly
7827 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7828 // safe to speculative execute. (Inverse of above)
7829 return true;
7830 return false;
7831}
7832
7833/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7847
7848/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7851 bool ForSigned,
7852 const SimplifyQuery &SQ) {
7853 ConstantRange CR1 =
7854 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7855 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7858 return CR1.intersectWith(CR2, RangeType);
7859}
7860
7862 const Value *RHS,
7863 const SimplifyQuery &SQ,
7864 bool IsNSW) {
7865 ConstantRange LHSRange =
7866 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7867 ConstantRange RHSRange =
7868 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7869
7870 // mul nsw of two non-negative numbers is also nuw.
7871 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7873
7874 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7875}
7876
7878 const Value *RHS,
7879 const SimplifyQuery &SQ) {
7880 // Multiplying n * m significant bits yields a result of n + m significant
7881 // bits. If the total number of significant bits does not exceed the
7882 // result bit width (minus 1), there is no overflow.
7883 // This means if we have enough leading sign bits in the operands
7884 // we can guarantee that the result does not overflow.
7885 // Ref: "Hacker's Delight" by Henry Warren
7886 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7887
7888 // Note that underestimating the number of sign bits gives a more
7889 // conservative answer.
7890 unsigned SignBits =
7891 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7892
7893 // First handle the easy case: if we have enough sign bits there's
7894 // definitely no overflow.
7895 if (SignBits > BitWidth + 1)
7897
7898 // There are two ambiguous cases where there can be no overflow:
7899 // SignBits == BitWidth + 1 and
7900 // SignBits == BitWidth
7901 // The second case is difficult to check, therefore we only handle the
7902 // first case.
7903 if (SignBits == BitWidth + 1) {
7904 // It overflows only when both arguments are negative and the true
7905 // product is exactly the minimum negative number.
7906 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7907 // For simplicity we just check if at least one side is not negative.
7908 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7909 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7910 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7912 }
7914}
7915
7918 const WithCache<const Value *> &RHS,
7919 const SimplifyQuery &SQ) {
7920 ConstantRange LHSRange =
7921 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7922 ConstantRange RHSRange =
7923 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7924 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7925}
7926
7927static OverflowResult
7930 const AddOperator *Add, const SimplifyQuery &SQ) {
7931 if (Add && Add->hasNoSignedWrap()) {
7933 }
7934
7935 // If LHS and RHS each have at least two sign bits, the addition will look
7936 // like
7937 //
7938 // XX..... +
7939 // YY.....
7940 //
7941 // If the carry into the most significant position is 0, X and Y can't both
7942 // be 1 and therefore the carry out of the addition is also 0.
7943 //
7944 // If the carry into the most significant position is 1, X and Y can't both
7945 // be 0 and therefore the carry out of the addition is also 1.
7946 //
7947 // Since the carry into the most significant position is always equal to
7948 // the carry out of the addition, there is no signed overflow.
7949 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7951
7952 ConstantRange LHSRange =
7953 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7954 ConstantRange RHSRange =
7955 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7956 OverflowResult OR =
7957 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7959 return OR;
7960
7961 // The remaining code needs Add to be available. Early returns if not so.
7962 if (!Add)
7964
7965 // If the sign of Add is the same as at least one of the operands, this add
7966 // CANNOT overflow. If this can be determined from the known bits of the
7967 // operands the above signedAddMayOverflow() check will have already done so.
7968 // The only other way to improve on the known bits is from an assumption, so
7969 // call computeKnownBitsFromContext() directly.
7970 bool LHSOrRHSKnownNonNegative =
7971 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7972 bool LHSOrRHSKnownNegative =
7973 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7974 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7975 KnownBits AddKnown(LHSRange.getBitWidth());
7976 computeKnownBitsFromContext(Add, AddKnown, SQ);
7977 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7978 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7980 }
7981
7983}
7984
7986 const Value *RHS,
7987 const SimplifyQuery &SQ) {
7988 // X - (X % ?)
7989 // The remainder of a value can't have greater magnitude than itself,
7990 // so the subtraction can't overflow.
7991
7992 // X - (X -nuw ?)
7993 // In the minimal case, this would simplify to "?", so there's no subtract
7994 // at all. But if this analysis is used to peek through casts, for example,
7995 // then determining no-overflow may allow other transforms.
7996
7997 // TODO: There are other patterns like this.
7998 // See simplifyICmpWithBinOpOnLHS() for candidates.
7999 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
8000 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
8001 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8003
8004 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
8005 SQ.DL)) {
8006 if (*C)
8009 }
8010
8011 ConstantRange LHSRange =
8012 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
8013 ConstantRange RHSRange =
8014 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
8015 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
8016}
8017
8019 const Value *RHS,
8020 const SimplifyQuery &SQ) {
8021 // X - (X % ?)
8022 // The remainder of a value can't have greater magnitude than itself,
8023 // so the subtraction can't overflow.
8024
8025 // X - (X -nsw ?)
8026 // In the minimal case, this would simplify to "?", so there's no subtract
8027 // at all. But if this analysis is used to peek through casts, for example,
8028 // then determining no-overflow may allow other transforms.
8029 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
8030 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
8031 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8033
8034 // If LHS and RHS each have at least two sign bits, the subtraction
8035 // cannot overflow.
8036 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
8038
8039 ConstantRange LHSRange =
8040 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
8041 ConstantRange RHSRange =
8042 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
8043 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
8044}
8045
8047 const DominatorTree &DT) {
8048 SmallVector<const CondBrInst *, 2> GuardingBranches;
8050
8051 for (const User *U : WO->users()) {
8052 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
8053 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
8054
8055 if (EVI->getIndices()[0] == 0)
8056 Results.push_back(EVI);
8057 else {
8058 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
8059
8060 for (const auto *U : EVI->users())
8061 if (const auto *B = dyn_cast<CondBrInst>(U))
8062 GuardingBranches.push_back(B);
8063 }
8064 } else {
8065 // We are using the aggregate directly in a way we don't want to analyze
8066 // here (storing it to a global, say).
8067 return false;
8068 }
8069 }
8070
8071 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8072 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8073
8074 // Check if all users of the add are provably no-wrap.
8075 for (const auto *Result : Results) {
8076 // If the extractvalue itself is not executed on overflow, the we don't
8077 // need to check each use separately, since domination is transitive.
8078 if (DT.dominates(NoWrapEdge, Result->getParent()))
8079 continue;
8080
8081 for (const auto &RU : Result->uses())
8082 if (!DT.dominates(NoWrapEdge, RU))
8083 return false;
8084 }
8085
8086 return true;
8087 };
8088
8089 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8090}
8091
8092/// Shifts return poison if shiftwidth is larger than the bitwidth.
8093static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8094 auto *C = dyn_cast<Constant>(ShiftAmount);
8095 if (!C)
8096 return false;
8097
8098 // Shifts return poison if shiftwidth is larger than the bitwidth.
8100 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8101 unsigned NumElts = FVTy->getNumElements();
8102 for (unsigned i = 0; i < NumElts; ++i)
8103 ShiftAmounts.push_back(C->getAggregateElement(i));
8104 } else if (isa<ScalableVectorType>(C->getType()))
8105 return false; // Can't tell, just return false to be safe
8106 else
8107 ShiftAmounts.push_back(C);
8108
8109 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8110 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8111 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8112 });
8113
8114 return Safe;
8115}
8116
8118 bool ConsiderFlagsAndMetadata) {
8119
8120 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8121 Op->hasPoisonGeneratingAnnotations())
8122 return true;
8123
8124 unsigned Opcode = Op->getOpcode();
8125
8126 // Check whether opcode is a poison/undef-generating operation
8127 switch (Opcode) {
8128 case Instruction::Shl:
8129 case Instruction::AShr:
8130 case Instruction::LShr:
8131 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8132 case Instruction::FPToSI:
8133 case Instruction::FPToUI:
8134 // fptosi/ui yields poison if the resulting value does not fit in the
8135 // destination type.
8136 return true;
8137 case Instruction::Call:
8138 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8139 switch (II->getIntrinsicID()) {
8140 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8141 case Intrinsic::ctlz:
8142 case Intrinsic::cttz:
8143 case Intrinsic::abs:
8144 // We're not considering flags so it is safe to just return false.
8145 return false;
8146 case Intrinsic::sshl_sat:
8147 case Intrinsic::ushl_sat:
8148 if (!includesPoison(Kind) ||
8149 shiftAmountKnownInRange(II->getArgOperand(1)))
8150 return false;
8151 break;
8152 }
8153 }
8154 [[fallthrough]];
8155 case Instruction::CallBr:
8156 case Instruction::Invoke: {
8157 const auto *CB = cast<CallBase>(Op);
8158 return !CB->hasRetAttr(Attribute::NoUndef) &&
8159 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8160 }
8161 case Instruction::InsertElement:
8162 case Instruction::ExtractElement: {
8163 // If index exceeds the length of the vector, it returns poison
8164 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8165 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8166 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8167 if (includesPoison(Kind))
8168 return !Idx ||
8169 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8170 return false;
8171 }
8172 case Instruction::ShuffleVector: {
8174 ? cast<ConstantExpr>(Op)->getShuffleMask()
8175 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8176 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8177 }
8178 case Instruction::FNeg:
8179 case Instruction::PHI:
8180 case Instruction::Select:
8181 case Instruction::ExtractValue:
8182 case Instruction::InsertValue:
8183 case Instruction::Freeze:
8184 case Instruction::ICmp:
8185 case Instruction::FCmp:
8186 case Instruction::GetElementPtr:
8187 return false;
8188 case Instruction::AddrSpaceCast:
8189 return true;
8190 default: {
8191 const auto *CE = dyn_cast<ConstantExpr>(Op);
8192 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8193 return false;
8194 else if (Instruction::isBinaryOp(Opcode))
8195 return false;
8196 // Be conservative and return true.
8197 return true;
8198 }
8199 }
8200}
8201
8203 bool ConsiderFlagsAndMetadata) {
8204 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8205 ConsiderFlagsAndMetadata);
8206}
8207
8208bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8209 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8210 ConsiderFlagsAndMetadata);
8211}
8212
8213static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8214 unsigned Depth) {
8215 if (ValAssumedPoison == V)
8216 return true;
8217
8218 const unsigned MaxDepth = 2;
8219 if (Depth >= MaxDepth)
8220 return false;
8221
8222 if (const auto *I = dyn_cast<Instruction>(V)) {
8223 if (any_of(I->operands(), [=](const Use &Op) {
8224 return propagatesPoison(Op) &&
8225 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8226 }))
8227 return true;
8228
8229 // V = extractvalue V0, idx
8230 // V2 = extractvalue V0, idx2
8231 // V0's elements are all poison or not. (e.g., add_with_overflow)
8232 const WithOverflowInst *II;
8234 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8235 llvm::is_contained(II->args(), ValAssumedPoison)))
8236 return true;
8237 }
8238 return false;
8239}
8240
8241static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8242 unsigned Depth) {
8243 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8244 return true;
8245
8246 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8247 return true;
8248
8249 const unsigned MaxDepth = 2;
8250 if (Depth >= MaxDepth)
8251 return false;
8252
8253 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8254 if (I && !canCreatePoison(cast<Operator>(I))) {
8255 return all_of(I->operands(), [=](const Value *Op) {
8256 return impliesPoison(Op, V, Depth + 1);
8257 });
8258 }
8259 return false;
8260}
8261
8262bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8263 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8264}
8265
8266static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8267
8269 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8270 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8272 return false;
8273
8274 if (isa<MetadataAsValue>(V))
8275 return false;
8276
8277 if (const auto *A = dyn_cast<Argument>(V)) {
8278 if (A->hasAttribute(Attribute::NoUndef) ||
8279 A->hasAttribute(Attribute::Dereferenceable) ||
8280 A->hasAttribute(Attribute::DereferenceableOrNull))
8281 return true;
8282 }
8283
8284 if (auto *C = dyn_cast<Constant>(V)) {
8285 if (isa<PoisonValue>(C))
8286 return !includesPoison(Kind);
8287
8288 if (isa<UndefValue>(C))
8289 return !includesUndef(Kind);
8290
8293 return true;
8294
8295 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8296 if (isa<ConstantExpr>(C)) {
8297 // Scalable vectors can use a ConstantExpr to build a splat.
8298 if (Constant *SplatC = C->getSplatValue())
8299 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8300 return true;
8301 } else if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
8302 return all_of(CA->operands(), [&](const Use &Op) {
8303 return isGuaranteedNotToBeUndefOrPoison(Op.get(), AC, CtxI, DT,
8304 Depth + 1, Kind);
8305 });
8306 }
8307 }
8308 }
8309
8310 // Strip cast operations from a pointer value.
8311 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8312 // inbounds with zero offset. To guarantee that the result isn't poison, the
8313 // stripped pointer is checked as it has to be pointing into an allocated
8314 // object or be null `null` to ensure `inbounds` getelement pointers with a
8315 // zero offset could not produce poison.
8316 // It can strip off addrspacecast that do not change bit representation as
8317 // well. We believe that such addrspacecast is equivalent to no-op.
8318 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8319 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8320 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8321 return true;
8322
8323 auto OpCheck = [&](const Value *V) {
8324 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8325 };
8326
8327 if (auto *Opr = dyn_cast<Operator>(V)) {
8328 // If the value is a freeze instruction, then it can never
8329 // be undef or poison.
8330 if (isa<FreezeInst>(V))
8331 return true;
8332
8333 if (const auto *CB = dyn_cast<CallBase>(V)) {
8334 if (CB->hasRetAttr(Attribute::NoUndef) ||
8335 CB->hasRetAttr(Attribute::Dereferenceable) ||
8336 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8337 return true;
8338 }
8339
8340 if (!::canCreateUndefOrPoison(Opr, Kind,
8341 /*ConsiderFlagsAndMetadata=*/true)) {
8342 if (const auto *PN = dyn_cast<PHINode>(V)) {
8343 unsigned Num = PN->getNumIncomingValues();
8344 bool IsWellDefined = true;
8345 for (unsigned i = 0; i < Num; ++i) {
8346 if (PN == PN->getIncomingValue(i))
8347 continue;
8348 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8349 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8350 DT, Depth + 1, Kind)) {
8351 IsWellDefined = false;
8352 break;
8353 }
8354 }
8355 if (IsWellDefined)
8356 return true;
8357 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8358 : nullptr) {
8359 // For splats we only need to check the value being splatted.
8360 if (OpCheck(Splat))
8361 return true;
8362 } else if (all_of(Opr->operands(), OpCheck))
8363 return true;
8364 }
8365 }
8366
8367 if (auto *I = dyn_cast<LoadInst>(V))
8368 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8369 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8370 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8371 return true;
8372
8374 return true;
8375
8376 // CtxI may be null or a cloned instruction.
8377 if (!CtxI || !CtxI->getParent() || !DT)
8378 return false;
8379
8380 auto *DNode = DT->getNode(CtxI->getParent());
8381 if (!DNode)
8382 // Unreachable block
8383 return false;
8384
8385 // If V is used as a branch condition before reaching CtxI, V cannot be
8386 // undef or poison.
8387 // br V, BB1, BB2
8388 // BB1:
8389 // CtxI ; V cannot be undef or poison here
8390 auto *Dominator = DNode->getIDom();
8391 // This check is purely for compile time reasons: we can skip the IDom walk
8392 // if what we are checking for includes undef and the value is not an integer.
8393 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8394 while (Dominator) {
8395 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8396
8397 Value *Cond = nullptr;
8398 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8399 Cond = BI->getCondition();
8400 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8401 Cond = SI->getCondition();
8402 }
8403
8404 if (Cond) {
8405 if (Cond == V)
8406 return true;
8407 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8408 // For poison, we can analyze further
8409 auto *Opr = cast<Operator>(Cond);
8410 if (any_of(Opr->operands(), [V](const Use &U) {
8411 return V == U && propagatesPoison(U);
8412 }))
8413 return true;
8414 }
8415 }
8416
8417 Dominator = Dominator->getIDom();
8418 }
8419
8420 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8421 return true;
8422
8423 return false;
8424}
8425
8427 const Instruction *CtxI,
8428 const DominatorTree *DT,
8429 unsigned Depth) {
8430 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8432}
8433
8435 const Instruction *CtxI,
8436 const DominatorTree *DT, unsigned Depth) {
8437 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8439}
8440
8442 const Instruction *CtxI,
8443 const DominatorTree *DT, unsigned Depth) {
8444 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8446}
8447
8448/// Return true if undefined behavior would provably be executed on the path to
8449/// OnPathTo if Root produced a posion result. Note that this doesn't say
8450/// anything about whether OnPathTo is actually executed or whether Root is
8451/// actually poison. This can be used to assess whether a new use of Root can
8452/// be added at a location which is control equivalent with OnPathTo (such as
8453/// immediately before it) without introducing UB which didn't previously
8454/// exist. Note that a false result conveys no information.
8456 Instruction *OnPathTo,
8457 DominatorTree *DT) {
8458 // Basic approach is to assume Root is poison, propagate poison forward
8459 // through all users we can easily track, and then check whether any of those
8460 // users are provable UB and must execute before out exiting block might
8461 // exit.
8462
8463 // The set of all recursive users we've visited (which are assumed to all be
8464 // poison because of said visit)
8467 Worklist.push_back(Root);
8468 while (!Worklist.empty()) {
8469 const Instruction *I = Worklist.pop_back_val();
8470
8471 // If we know this must trigger UB on a path leading our target.
8472 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8473 return true;
8474
8475 // If we can't analyze propagation through this instruction, just skip it
8476 // and transitive users. Safe as false is a conservative result.
8477 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8478 return KnownPoison.contains(U) && propagatesPoison(U);
8479 }))
8480 continue;
8481
8482 if (KnownPoison.insert(I).second)
8483 for (const User *User : I->users())
8484 Worklist.push_back(cast<Instruction>(User));
8485 }
8486
8487 // Might be non-UB, or might have a path we couldn't prove must execute on
8488 // way to exiting bb.
8489 return false;
8490}
8491
8493 const SimplifyQuery &SQ) {
8494 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8495 Add, SQ);
8496}
8497
8500 const WithCache<const Value *> &RHS,
8501 const SimplifyQuery &SQ) {
8502 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8503}
8504
8506 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8507 // of time because it's possible for another thread to interfere with it for an
8508 // arbitrary length of time, but programs aren't allowed to rely on that.
8509
8510 // If there is no successor, then execution can't transfer to it.
8511 if (isa<ReturnInst>(I))
8512 return false;
8514 return false;
8515
8516 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8517 // Instruction::willReturn.
8518 //
8519 // FIXME: Move this check into Instruction::willReturn.
8520 if (isa<CatchPadInst>(I)) {
8521 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8522 default:
8523 // A catchpad may invoke exception object constructors and such, which
8524 // in some languages can be arbitrary code, so be conservative by default.
8525 return false;
8527 // For CoreCLR, it just involves a type test.
8528 return true;
8529 }
8530 }
8531
8532 // An instruction that returns without throwing must transfer control flow
8533 // to a successor.
8534 return !I->mayThrow() && I->willReturn();
8535}
8536
8538 // TODO: This is slightly conservative for invoke instruction since exiting
8539 // via an exception *is* normal control for them.
8540 for (const Instruction &I : *BB)
8542 return false;
8543 return true;
8544}
8545
8552
8555 assert(ScanLimit && "scan limit must be non-zero");
8556 for (const Instruction &I : Range) {
8557 if (--ScanLimit == 0)
8558 return false;
8560 return false;
8561 }
8562 return true;
8563}
8564
8566 const Loop *L) {
8567 // The loop header is guaranteed to be executed for every iteration.
8568 //
8569 // FIXME: Relax this constraint to cover all basic blocks that are
8570 // guaranteed to be executed at every iteration.
8571 if (I->getParent() != L->getHeader()) return false;
8572
8573 for (const Instruction &LI : *L->getHeader()) {
8574 if (&LI == I) return true;
8575 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8576 }
8577 llvm_unreachable("Instruction not contained in its own parent basic block.");
8578}
8579
8581 switch (IID) {
8582 // TODO: Add more intrinsics.
8583 case Intrinsic::sadd_with_overflow:
8584 case Intrinsic::ssub_with_overflow:
8585 case Intrinsic::smul_with_overflow:
8586 case Intrinsic::uadd_with_overflow:
8587 case Intrinsic::usub_with_overflow:
8588 case Intrinsic::umul_with_overflow:
8589 // If an input is a vector containing a poison element, the
8590 // two output vectors (calculated results, overflow bits)'
8591 // corresponding lanes are poison.
8592 return true;
8593 case Intrinsic::ctpop:
8594 case Intrinsic::ctlz:
8595 case Intrinsic::cttz:
8596 case Intrinsic::abs:
8597 case Intrinsic::smax:
8598 case Intrinsic::smin:
8599 case Intrinsic::umax:
8600 case Intrinsic::umin:
8601 case Intrinsic::scmp:
8602 case Intrinsic::smulh:
8603 case Intrinsic::umulh:
8604 case Intrinsic::is_fpclass:
8605 case Intrinsic::ptrmask:
8606 case Intrinsic::ucmp:
8607 case Intrinsic::bitreverse:
8608 case Intrinsic::bswap:
8609 case Intrinsic::sadd_sat:
8610 case Intrinsic::ssub_sat:
8611 case Intrinsic::sshl_sat:
8612 case Intrinsic::uadd_sat:
8613 case Intrinsic::usub_sat:
8614 case Intrinsic::ushl_sat:
8615 case Intrinsic::smul_fix:
8616 case Intrinsic::smul_fix_sat:
8617 case Intrinsic::umul_fix:
8618 case Intrinsic::umul_fix_sat:
8619 case Intrinsic::pow:
8620 case Intrinsic::powi:
8621 case Intrinsic::sin:
8622 case Intrinsic::sinh:
8623 case Intrinsic::cos:
8624 case Intrinsic::cosh:
8625 case Intrinsic::sincos:
8626 case Intrinsic::sincospi:
8627 case Intrinsic::tan:
8628 case Intrinsic::tanh:
8629 case Intrinsic::asin:
8630 case Intrinsic::acos:
8631 case Intrinsic::atan:
8632 case Intrinsic::atan2:
8633 case Intrinsic::canonicalize:
8634 case Intrinsic::sqrt:
8635 case Intrinsic::fma:
8636 case Intrinsic::fmuladd:
8637 case Intrinsic::exp:
8638 case Intrinsic::exp2:
8639 case Intrinsic::exp10:
8640 case Intrinsic::log:
8641 case Intrinsic::log2:
8642 case Intrinsic::log10:
8643 case Intrinsic::modf:
8644 case Intrinsic::floor:
8645 case Intrinsic::ceil:
8646 case Intrinsic::trunc:
8647 case Intrinsic::rint:
8648 case Intrinsic::nearbyint:
8649 case Intrinsic::round:
8650 case Intrinsic::roundeven:
8651 case Intrinsic::lrint:
8652 case Intrinsic::llrint:
8653 case Intrinsic::fshl:
8654 case Intrinsic::fshr:
8655 case Intrinsic::frexp:
8656 case Intrinsic::get_active_lane_mask:
8657 case Intrinsic::mask_beforefirst:
8658 return true;
8659 default:
8660 return false;
8661 }
8662}
8663
8664bool llvm::propagatesPoison(const Use &PoisonOp) {
8665 const Operator *I = cast<Operator>(PoisonOp.getUser());
8666 switch (I->getOpcode()) {
8667 case Instruction::Freeze:
8668 case Instruction::PHI:
8669 case Instruction::Invoke:
8670 return false;
8671 case Instruction::Select:
8672 return PoisonOp.getOperandNo() == 0;
8673 case Instruction::Call:
8674 if (auto *II = dyn_cast<IntrinsicInst>(I))
8675 return intrinsicPropagatesPoison(II->getIntrinsicID());
8676 return false;
8677 case Instruction::ICmp:
8678 case Instruction::FCmp:
8679 case Instruction::GetElementPtr:
8680 return true;
8681 default:
8683 return true;
8684
8685 // Be conservative and return false.
8686 return false;
8687 }
8688}
8689
8690/// Enumerates all operands of \p I that are guaranteed to not be undef or
8691/// poison. If the callback \p Handle returns true, stop processing and return
8692/// true. Otherwise, return false.
8693template <typename CallableT>
8695 const CallableT &Handle) {
8696 switch (I->getOpcode()) {
8697 case Instruction::Store:
8698 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8699 return true;
8700 break;
8701
8702 case Instruction::Load:
8703 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8704 return true;
8705 break;
8706
8707 // Since dereferenceable attribute imply noundef, atomic operations
8708 // also implicitly have noundef pointers too
8709 case Instruction::AtomicCmpXchg:
8711 return true;
8712 break;
8713
8714 case Instruction::AtomicRMW:
8715 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8716 return true;
8717 break;
8718
8719 case Instruction::Call:
8720 case Instruction::Invoke: {
8721 const CallBase *CB = cast<CallBase>(I);
8722 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8723 return true;
8724 for (unsigned i = 0; i < CB->arg_size(); ++i)
8725 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8726 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8727 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8728 Handle(CB->getArgOperand(i)))
8729 return true;
8730 break;
8731 }
8732 case Instruction::Ret:
8733 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8734 Handle(I->getOperand(0)))
8735 return true;
8736 break;
8737 case Instruction::Switch:
8738 if (Handle(cast<SwitchInst>(I)->getCondition()))
8739 return true;
8740 break;
8741 case Instruction::CondBr:
8742 if (Handle(cast<CondBrInst>(I)->getCondition()))
8743 return true;
8744 break;
8745 default:
8746 break;
8747 }
8748
8749 return false;
8750}
8751
8752/// Enumerates all operands of \p I that are guaranteed to not be poison.
8753template <typename CallableT>
8755 const CallableT &Handle) {
8756 if (handleGuaranteedWellDefinedOps(I, Handle))
8757 return true;
8758 switch (I->getOpcode()) {
8759 // Divisors of these operations are allowed to be partially undef.
8760 case Instruction::UDiv:
8761 case Instruction::SDiv:
8762 case Instruction::URem:
8763 case Instruction::SRem:
8764 return Handle(I->getOperand(1));
8765 default:
8766 return false;
8767 }
8768}
8769
8771 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8773 I, [&](const Value *V) { return KnownPoison.count(V); });
8774}
8775
8777 bool PoisonOnly) {
8778 // We currently only look for uses of values within the same basic
8779 // block, as that makes it easier to guarantee that the uses will be
8780 // executed given that Inst is executed.
8781 //
8782 // FIXME: Expand this to consider uses beyond the same basic block. To do
8783 // this, look out for the distinction between post-dominance and strong
8784 // post-dominance.
8785 const BasicBlock *BB = nullptr;
8787 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8788 BB = Inst->getParent();
8789 Begin = Inst->getIterator();
8790 Begin++;
8791 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8792 if (Arg->getParent()->isDeclaration())
8793 return false;
8794 BB = &Arg->getParent()->getEntryBlock();
8795 Begin = BB->begin();
8796 } else {
8797 return false;
8798 }
8799
8800 // Limit number of instructions we look at, to avoid scanning through large
8801 // blocks. The current limit is chosen arbitrarily.
8802 unsigned ScanLimit = 32;
8804
8805 if (!PoisonOnly) {
8806 // Since undef does not propagate eagerly, be conservative & just check
8807 // whether a value is directly passed to an instruction that must take
8808 // well-defined operands.
8809
8810 for (const auto &I : make_range(Begin, End)) {
8811 if (--ScanLimit == 0)
8812 break;
8813
8814 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8815 return WellDefinedOp == V;
8816 }))
8817 return true;
8818
8820 break;
8821 }
8822 return false;
8823 }
8824
8825 // Set of instructions that we have proved will yield poison if Inst
8826 // does.
8827 SmallPtrSet<const Value *, 16> YieldsPoison;
8829
8830 YieldsPoison.insert(V);
8831 Visited.insert(BB);
8832
8833 while (true) {
8834 for (const auto &I : make_range(Begin, End)) {
8835 if (--ScanLimit == 0)
8836 return false;
8837 if (mustTriggerUB(&I, YieldsPoison))
8838 return true;
8840 return false;
8841
8842 // If an operand is poison and propagates it, mark I as yielding poison.
8843 for (const Use &Op : I.operands()) {
8844 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8845 YieldsPoison.insert(&I);
8846 break;
8847 }
8848 }
8849
8850 // Special handling for select, which returns poison if its operand 0 is
8851 // poison (handled in the loop above) *or* if both its true/false operands
8852 // are poison (handled here).
8853 if (I.getOpcode() == Instruction::Select &&
8854 YieldsPoison.count(I.getOperand(1)) &&
8855 YieldsPoison.count(I.getOperand(2))) {
8856 YieldsPoison.insert(&I);
8857 }
8858 }
8859
8860 BB = BB->getSingleSuccessor();
8861 if (!BB || !Visited.insert(BB).second)
8862 break;
8863
8864 Begin = BB->getFirstNonPHIIt();
8865 End = BB->end();
8866 }
8867 return false;
8868}
8869
8871 return ::programUndefinedIfUndefOrPoison(Inst, false);
8872}
8873
8875 return ::programUndefinedIfUndefOrPoison(Inst, true);
8876}
8877
8878static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8879 if (FMF.noNaNs())
8880 return true;
8881
8882 if (auto *C = dyn_cast<ConstantFP>(V))
8883 return !C->isNaN();
8884
8885 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8886 if (!C->getElementType()->isFloatingPointTy())
8887 return false;
8888 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8889 if (C->getElementAsAPFloat(I).isNaN())
8890 return false;
8891 }
8892 return true;
8893 }
8894
8896 return true;
8897
8898 return false;
8899}
8900
8901static bool isKnownNonZero(const Value *V) {
8902 if (auto *C = dyn_cast<ConstantFP>(V))
8903 return !C->isZero();
8904
8905 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8906 if (!C->getElementType()->isFloatingPointTy())
8907 return false;
8908 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8909 if (C->getElementAsAPFloat(I).isZero())
8910 return false;
8911 }
8912 return true;
8913 }
8914
8915 return false;
8916}
8917
8918/// Match clamp pattern for float types without care about NaNs or signed zeros.
8919/// Given non-min/max outer cmp/select from the clamp pattern this
8920/// function recognizes if it can be substitued by a "canonical" min/max
8921/// pattern.
8923 Value *CmpLHS, Value *CmpRHS,
8924 Value *TrueVal, Value *FalseVal,
8925 Value *&LHS, Value *&RHS) {
8926 // Try to match
8927 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8928 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8929 // and return description of the outer Max/Min.
8930
8931 // First, check if select has inverse order:
8932 if (CmpRHS == FalseVal) {
8933 std::swap(TrueVal, FalseVal);
8934 Pred = CmpInst::getInversePredicate(Pred);
8935 }
8936
8937 // Assume success now. If there's no match, callers should not use these anyway.
8938 LHS = TrueVal;
8939 RHS = FalseVal;
8940
8941 const APFloat *FC1;
8942 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8943 return {SPF_UNKNOWN, SPNB_NA, false};
8944
8945 const APFloat *FC2;
8946 switch (Pred) {
8947 case CmpInst::FCMP_OLT:
8948 case CmpInst::FCMP_OLE:
8949 case CmpInst::FCMP_ULT:
8950 case CmpInst::FCMP_ULE:
8951 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8952 *FC1 < *FC2)
8953 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8954 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8955 *FC1 < *FC2)
8956 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8957 break;
8958 case CmpInst::FCMP_OGT:
8959 case CmpInst::FCMP_OGE:
8960 case CmpInst::FCMP_UGT:
8961 case CmpInst::FCMP_UGE:
8962 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8963 *FC1 > *FC2)
8964 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8965 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8966 *FC1 > *FC2)
8967 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8968 break;
8969 default:
8970 break;
8971 }
8972
8973 return {SPF_UNKNOWN, SPNB_NA, false};
8974}
8975
8976/// Recognize variations of:
8977/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8979 Value *CmpLHS, Value *CmpRHS,
8980 Value *TrueVal, Value *FalseVal) {
8981 // Swap the select operands and predicate to match the patterns below.
8982 if (CmpRHS != TrueVal) {
8983 Pred = ICmpInst::getSwappedPredicate(Pred);
8984 std::swap(TrueVal, FalseVal);
8985 }
8986 const APInt *C1;
8987 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8988 const APInt *C2;
8989 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8990 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8991 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8992 return {SPF_SMAX, SPNB_NA, false};
8993
8994 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8995 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8996 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8997 return {SPF_SMIN, SPNB_NA, false};
8998
8999 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
9000 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
9001 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
9002 return {SPF_UMAX, SPNB_NA, false};
9003
9004 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
9005 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9006 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
9007 return {SPF_UMIN, SPNB_NA, false};
9008 }
9009 return {SPF_UNKNOWN, SPNB_NA, false};
9010}
9011
9012/// If the input value is the result of a 'not' op, constant integer, or vector
9013/// splat of a constant integer, return the bitwise-not source value.
9014/// TODO: This could be extended to handle non-splat vector integer constants.
9016 Value *NotV;
9017 if (match(V, m_Not(m_Value(NotV))))
9018 return NotV;
9019
9020 const APInt *C;
9021 if (match(V, m_APInt(C)))
9022 return ConstantInt::get(V->getType(), ~(*C));
9023
9024 return nullptr;
9025}
9026
9027/// Match non-obvious integer minimum and maximum sequences.
9029 Value *CmpRHS, Value *TrueVal,
9030 Value *FalseVal, Value *&LHS,
9031 Value *&RHS) {
9032 // Assume success. If there's no match, callers should not use these anyway.
9033 LHS = TrueVal;
9034 RHS = FalseVal;
9035
9036 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9038 return SPR;
9039
9040 // Look through 'not' ops to find disguised min/max.
9041 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9042 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9043 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9044 switch (Pred) {
9045 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9046 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9047 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9048 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9049 default: break;
9050 }
9051 }
9052
9053 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9054 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9055 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9056 switch (Pred) {
9057 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9058 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9059 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9060 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9061 default: break;
9062 }
9063 }
9064
9065 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9066 return {SPF_UNKNOWN, SPNB_NA, false};
9067
9068 const APInt *C1;
9069 if (!match(CmpRHS, m_APInt(C1)))
9070 return {SPF_UNKNOWN, SPNB_NA, false};
9071
9072 // An unsigned min/max can be written with a signed compare.
9073 const APInt *C2;
9074 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9075 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9076 // Is the sign bit set?
9077 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9078 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9079 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9080 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9081
9082 // Is the sign bit clear?
9083 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9084 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9085 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9086 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9087 }
9088
9089 return {SPF_UNKNOWN, SPNB_NA, false};
9090}
9091
9092bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9093 bool AllowPoison) {
9094 assert(X && Y && "Invalid operand");
9095
9096 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9097 if (!match(X, m_Neg(m_Specific(Y))))
9098 return false;
9099
9100 auto *BO = cast<BinaryOperator>(X);
9101 if (NeedNSW && !BO->hasNoSignedWrap())
9102 return false;
9103
9104 auto *Zero = cast<Constant>(BO->getOperand(0));
9105 if (!AllowPoison && !Zero->isNullValue())
9106 return false;
9107
9108 return true;
9109 };
9110
9111 // X = -Y or Y = -X
9112 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9113 return true;
9114
9115 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9116 Value *A, *B;
9117 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9118 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9119 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9121}
9122
9123bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9124 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9125 Value *A, *B, *C;
9126 CmpPredicate Pred1, Pred2;
9127 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9128 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9129 return false;
9130
9131 // They must both have samesign flag or not.
9132 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9133 return false;
9134
9135 if (B == C)
9136 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9137
9138 // Try to infer the relationship from constant ranges.
9139 const APInt *RHSC1, *RHSC2;
9140 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9141 return false;
9142
9143 // Sign bits of two RHSCs should match.
9144 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9145 return false;
9146
9147 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9148 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9149
9150 return CR1.inverse() == CR2;
9151}
9152
9154 SelectPatternNaNBehavior NaNBehavior,
9155 bool Ordered) {
9156 switch (Pred) {
9157 default:
9158 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9159 case ICmpInst::ICMP_UGT:
9160 case ICmpInst::ICMP_UGE:
9161 return {SPF_UMAX, SPNB_NA, false};
9162 case ICmpInst::ICMP_SGT:
9163 case ICmpInst::ICMP_SGE:
9164 return {SPF_SMAX, SPNB_NA, false};
9165 case ICmpInst::ICMP_ULT:
9166 case ICmpInst::ICMP_ULE:
9167 return {SPF_UMIN, SPNB_NA, false};
9168 case ICmpInst::ICMP_SLT:
9169 case ICmpInst::ICMP_SLE:
9170 return {SPF_SMIN, SPNB_NA, false};
9171 case FCmpInst::FCMP_UGT:
9172 case FCmpInst::FCMP_UGE:
9173 case FCmpInst::FCMP_OGT:
9174 case FCmpInst::FCMP_OGE:
9175 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9176 case FCmpInst::FCMP_ULT:
9177 case FCmpInst::FCMP_ULE:
9178 case FCmpInst::FCMP_OLT:
9179 case FCmpInst::FCMP_OLE:
9180 return {SPF_FMINNUM, NaNBehavior, Ordered};
9181 }
9182}
9183
9184std::optional<std::pair<CmpPredicate, Constant *>>
9187 "Only for relational integer predicates.");
9188 if (isa<UndefValue>(C))
9189 return std::nullopt;
9190
9191 Type *Type = C->getType();
9192 bool IsSigned = ICmpInst::isSigned(Pred);
9193
9195 bool WillIncrement =
9196 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9197
9198 // Check if the constant operand can be safely incremented/decremented
9199 // without overflowing/underflowing.
9200 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9201 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9202 return false;
9203
9204 if (!Pred.hasSameSign())
9205 return true;
9206
9207 // Crossing the corresponding boundary in the other ordering changes the
9208 // sign bit, and therefore changes the poison domain.
9209 return WillIncrement ? !C->isMaxValue(!IsSigned)
9210 : !C->isMinValue(!IsSigned);
9211 };
9212
9213 Constant *SafeReplacementConstant = nullptr;
9214 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9215 // Bail out if the constant can't be safely incremented/decremented.
9216 if (!ConstantIsOk(CI))
9217 return std::nullopt;
9218 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9219 unsigned NumElts = FVTy->getNumElements();
9220 for (unsigned i = 0; i != NumElts; ++i) {
9221 Constant *Elt = C->getAggregateElement(i);
9222 if (!Elt)
9223 return std::nullopt;
9224
9225 if (isa<UndefValue>(Elt))
9226 continue;
9227
9228 // Bail out if we can't determine if this constant is min/max or if we
9229 // know that this constant is min/max.
9230 auto *CI = dyn_cast<ConstantInt>(Elt);
9231 if (!CI || !ConstantIsOk(CI))
9232 return std::nullopt;
9233
9234 if (!SafeReplacementConstant)
9235 SafeReplacementConstant = CI;
9236 }
9237 } else if (isa<VectorType>(C->getType())) {
9238 // Handle scalable splat
9239 Value *SplatC = C->getSplatValue();
9240 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9241 // Bail out if the constant can't be safely incremented/decremented.
9242 if (!CI || !ConstantIsOk(CI))
9243 return std::nullopt;
9244 } else {
9245 // ConstantExpr?
9246 return std::nullopt;
9247 }
9248
9249 // It may not be safe to change a compare predicate in the presence of
9250 // undefined elements, so replace those elements with the first safe constant
9251 // that we found.
9252 // TODO: in case of poison, it is safe; let's replace undefs only.
9253 if (C->containsUndefOrPoisonElement()) {
9254 assert(SafeReplacementConstant && "Replacement constant not set");
9255 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9256 }
9257
9259 Pred.hasSameSign());
9260
9261 // Increment or decrement the constant.
9262 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9263 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9264
9265 return std::make_pair(NewPred, NewC);
9266}
9267
9269 FastMathFlags FMF, Value *CmpLHS,
9270 Value *CmpRHS, Value *TrueVal,
9271 Value *FalseVal, Value *&LHS,
9272 Value *&RHS) {
9273 if (CmpInst::isFPPredicate(Pred)) {
9274 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9275 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9276 // purpose of identifying min/max. Disregard vector constants with undefined
9277 // elements because those can not be back-propagated for analysis.
9278 Value *OutputZeroVal = nullptr;
9279 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9280 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9281 OutputZeroVal = TrueVal;
9282 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9283 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9284 OutputZeroVal = FalseVal;
9285
9286 if (OutputZeroVal) {
9287 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9288 CmpLHS = OutputZeroVal;
9289 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9290 CmpRHS = OutputZeroVal;
9291 }
9292 }
9293
9294 LHS = CmpLHS;
9295 RHS = CmpRHS;
9296
9297 // Signed zero may return inconsistent results between implementations.
9298 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9299 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9300 // Therefore, we behave conservatively and only proceed if at least one of the
9301 // operands is known to not be zero or if we don't care about signed zero.
9302 if (CmpInst::isFPPredicate(Pred)) {
9303 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9304 !isKnownNonZero(CmpRHS))
9305 return {SPF_UNKNOWN, SPNB_NA, false};
9306 }
9307
9308 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9309 bool Ordered = false;
9310
9311 // When given one NaN and one non-NaN input:
9312 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9313 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9314 // ordered comparison fails), which could be NaN or non-NaN.
9315 // so here we discover exactly what NaN behavior is required/accepted.
9316 if (CmpInst::isFPPredicate(Pred)) {
9317 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9318 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9319
9320 if (LHSSafe && RHSSafe) {
9321 // Both operands are known non-NaN.
9322 NaNBehavior = SPNB_RETURNS_ANY;
9323 Ordered = CmpInst::isOrdered(Pred);
9324 } else if (CmpInst::isOrdered(Pred)) {
9325 // An ordered comparison will return false when given a NaN, so it
9326 // returns the RHS.
9327 Ordered = true;
9328 if (LHSSafe)
9329 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9330 NaNBehavior = SPNB_RETURNS_NAN;
9331 else if (RHSSafe)
9332 NaNBehavior = SPNB_RETURNS_OTHER;
9333 else
9334 // Completely unsafe.
9335 return {SPF_UNKNOWN, SPNB_NA, false};
9336 } else {
9337 Ordered = false;
9338 // An unordered comparison will return true when given a NaN, so it
9339 // returns the LHS.
9340 if (LHSSafe)
9341 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9342 NaNBehavior = SPNB_RETURNS_OTHER;
9343 else if (RHSSafe)
9344 NaNBehavior = SPNB_RETURNS_NAN;
9345 else
9346 // Completely unsafe.
9347 return {SPF_UNKNOWN, SPNB_NA, false};
9348 }
9349 }
9350
9351 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9352 std::swap(CmpLHS, CmpRHS);
9353 Pred = CmpInst::getSwappedPredicate(Pred);
9354 if (NaNBehavior == SPNB_RETURNS_NAN)
9355 NaNBehavior = SPNB_RETURNS_OTHER;
9356 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9357 NaNBehavior = SPNB_RETURNS_NAN;
9358 Ordered = !Ordered;
9359 }
9360
9361 // ([if]cmp X, Y) ? X : Y
9362 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9363 return getSelectPattern(Pred, NaNBehavior, Ordered);
9364
9365 if (isKnownNegation(TrueVal, FalseVal)) {
9366 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9367 // match against either LHS or sign-preserving operations on LHS, like
9368 // sext(LHS), or binary ops that do not wrap in signed sense.
9369 auto CmpLHSOrSExt =
9370 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9371 auto MaybeSExtOrMulCmpLHS =
9372 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9373 m_NSWShl(CmpLHSOrSExt, m_Value()));
9374 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9375 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9376 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9377 // Set the return values. If the compare uses the negated value (-X >s 0),
9378 // swap the return values because the negated value is always 'RHS'.
9379 LHS = TrueVal;
9380 RHS = FalseVal;
9381 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9382 std::swap(LHS, RHS);
9383
9384 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9385 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9386 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9387 return {SPF_ABS, SPNB_NA, false};
9388
9389 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9390 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9391 return {SPF_ABS, SPNB_NA, false};
9392
9393 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9394 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9395 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9396 return {SPF_NABS, SPNB_NA, false};
9397 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9398 // Set the return values. If the compare uses the negated value (-X >s 0),
9399 // swap the return values because the negated value is always 'RHS'.
9400 LHS = FalseVal;
9401 RHS = TrueVal;
9402 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9403 std::swap(LHS, RHS);
9404
9405 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9406 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9407 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9408 return {SPF_NABS, SPNB_NA, false};
9409
9410 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9411 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9412 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9413 return {SPF_ABS, SPNB_NA, false};
9414 }
9415 }
9416
9417 if (CmpInst::isIntPredicate(Pred))
9418 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9419
9420 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9421 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9422 // semantics than minNum. Be conservative in such case.
9423 if (NaNBehavior != SPNB_RETURNS_ANY ||
9424 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9425 !isKnownNonZero(CmpRHS)))
9426 return {SPF_UNKNOWN, SPNB_NA, false};
9427
9428 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9429}
9430
9432 Instruction::CastOps *CastOp) {
9433 const DataLayout &DL = CmpI->getDataLayout();
9434
9435 Constant *CastedTo = nullptr;
9436 switch (*CastOp) {
9437 case Instruction::ZExt:
9438 if (CmpI->isUnsigned())
9439 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9440 break;
9441 case Instruction::SExt:
9442 if (CmpI->isSigned())
9443 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9444 break;
9445 case Instruction::Trunc:
9446 Constant *CmpConst;
9447 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9448 CmpConst->getType() == SrcTy) {
9449 // Here we have the following case:
9450 //
9451 // %cond = cmp iN %x, CmpConst
9452 // %tr = trunc iN %x to iK
9453 // %narrowsel = select i1 %cond, iK %t, iK C
9454 //
9455 // We can always move trunc after select operation:
9456 //
9457 // %cond = cmp iN %x, CmpConst
9458 // %widesel = select i1 %cond, iN %x, iN CmpConst
9459 // %tr = trunc iN %widesel to iK
9460 //
9461 // Note that C could be extended in any way because we don't care about
9462 // upper bits after truncation. It can't be abs pattern, because it would
9463 // look like:
9464 //
9465 // select i1 %cond, x, -x.
9466 //
9467 // So only min/max pattern could be matched. Such match requires widened C
9468 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9469 // CmpConst == C is checked below.
9470 CastedTo = CmpConst;
9471 } else {
9472 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9473 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9474 }
9475 break;
9476 case Instruction::FPTrunc:
9477 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9478 break;
9479 case Instruction::FPExt:
9480 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9481 break;
9482 case Instruction::FPToUI:
9483 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9484 break;
9485 case Instruction::FPToSI:
9486 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9487 break;
9488 case Instruction::UIToFP:
9489 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9490 break;
9491 case Instruction::SIToFP:
9492 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9493 break;
9494 default:
9495 break;
9496 }
9497
9498 if (!CastedTo)
9499 return nullptr;
9500
9501 // Make sure the cast doesn't lose any information.
9502 Constant *CastedBack =
9503 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9504 if (CastedBack && CastedBack != C)
9505 return nullptr;
9506
9507 return CastedTo;
9508}
9509
9510/// Helps to match a select pattern in case of a type mismatch.
9511///
9512/// The function processes the case when type of true and false values of a
9513/// select instruction differs from type of the cmp instruction operands because
9514/// of a cast instruction. The function checks if it is legal to move the cast
9515/// operation after "select". If yes, it returns the new second value of
9516/// "select" (with the assumption that cast is moved):
9517/// 1. As operand of cast instruction when both values of "select" are same cast
9518/// instructions.
9519/// 2. As restored constant (by applying reverse cast operation) when the first
9520/// value of the "select" is a cast operation and the second value is a
9521/// constant. It is implemented in lookThroughCastConst().
9522/// 3. As one operand is cast instruction and the other is not. The operands in
9523/// sel(cmp) are in different type integer.
9524/// NOTE: We return only the new second value because the first value could be
9525/// accessed as operand of cast instruction.
9527 Instruction::CastOps *CastOp) {
9528 auto *Cast1 = dyn_cast<CastInst>(V1);
9529 if (!Cast1)
9530 return nullptr;
9531
9532 *CastOp = Cast1->getOpcode();
9533 Type *SrcTy = Cast1->getSrcTy();
9534 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9535 // If V1 and V2 are both the same cast from the same type, look through V1.
9536 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9537 return Cast2->getOperand(0);
9538 return nullptr;
9539 }
9540
9541 auto *C = dyn_cast<Constant>(V2);
9542 if (C)
9543 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9544
9545 Value *CastedTo = nullptr;
9546 if (*CastOp == Instruction::Trunc) {
9547 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9548 // Here we have the following case:
9549 // %y_ext = sext iK %y to iN
9550 // %cond = cmp iN %x, %y_ext
9551 // %tr = trunc iN %x to iK
9552 // %narrowsel = select i1 %cond, iK %tr, iK %y
9553 //
9554 // We can always move trunc after select operation:
9555 // %y_ext = sext iK %y to iN
9556 // %cond = cmp iN %x, %y_ext
9557 // %widesel = select i1 %cond, iN %x, iN %y_ext
9558 // %tr = trunc iN %widesel to iK
9559 assert(V2->getType() == Cast1->getType() &&
9560 "V2 and Cast1 should be the same type.");
9561 CastedTo = CmpI->getOperand(1);
9562 }
9563 }
9564
9565 return CastedTo;
9566}
9568 Instruction::CastOps *CastOp) {
9570 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9571
9572 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9573 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9574
9575 Value *TrueVal = SI->getTrueValue();
9576 Value *FalseVal = SI->getFalseValue();
9577
9579 CmpI, TrueVal, FalseVal, LHS, RHS, SI->getFastMathFlagsOrNone(), CastOp);
9580}
9581
9583 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9584 FastMathFlags FMF, Instruction::CastOps *CastOp) {
9585 CmpInst::Predicate Pred = CmpI->getPredicate();
9586 Value *CmpLHS = CmpI->getOperand(0);
9587 Value *CmpRHS = CmpI->getOperand(1);
9588 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9589 FMF.setNoNaNs();
9590
9591 // Bail out early.
9592 if (CmpI->isEquality())
9593 return {SPF_UNKNOWN, SPNB_NA, false};
9594
9595 // Deal with type mismatches.
9596 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9597 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9598 // If this is a potential fmin/fmax with a cast to integer, then ignore
9599 // -0.0 because there is no corresponding integer value.
9600 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9601 FMF.setNoSignedZeros();
9602 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9603 cast<CastInst>(TrueVal)->getOperand(0), C,
9604 LHS, RHS);
9605 }
9606 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9607 // If this is a potential fmin/fmax with a cast to integer, then ignore
9608 // -0.0 because there is no corresponding integer value.
9609 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9610 FMF.setNoSignedZeros();
9611 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, C,
9612 cast<CastInst>(FalseVal)->getOperand(0), LHS,
9613 RHS);
9614 }
9615 }
9616 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS,
9617 RHS);
9618}
9619
9621 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9622 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9623 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9624 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9625 if (SPF == SPF_FMINNUM)
9626 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9627 if (SPF == SPF_FMAXNUM)
9628 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9629 llvm_unreachable("unhandled!");
9630}
9631
9633 switch (SPF) {
9635 return Intrinsic::umin;
9637 return Intrinsic::umax;
9639 return Intrinsic::smin;
9641 return Intrinsic::smax;
9642 default:
9643 llvm_unreachable("Unexpected SPF");
9644 }
9645}
9646
9648 if (SPF == SPF_SMIN) return SPF_SMAX;
9649 if (SPF == SPF_UMIN) return SPF_UMAX;
9650 if (SPF == SPF_SMAX) return SPF_SMIN;
9651 if (SPF == SPF_UMAX) return SPF_UMIN;
9652 llvm_unreachable("unhandled!");
9653}
9654
9656 switch (MinMaxID) {
9657 case Intrinsic::smax: return Intrinsic::smin;
9658 case Intrinsic::smin: return Intrinsic::smax;
9659 case Intrinsic::umax: return Intrinsic::umin;
9660 case Intrinsic::umin: return Intrinsic::umax;
9661 // Please note that next four intrinsics may produce the same result for
9662 // original and inverted case even if X != Y due to NaN is handled specially.
9663 case Intrinsic::maximum: return Intrinsic::minimum;
9664 case Intrinsic::minimum: return Intrinsic::maximum;
9665 case Intrinsic::maxnum: return Intrinsic::minnum;
9666 case Intrinsic::minnum: return Intrinsic::maxnum;
9667 case Intrinsic::maximumnum:
9668 return Intrinsic::minimumnum;
9669 case Intrinsic::minimumnum:
9670 return Intrinsic::maximumnum;
9671 default: llvm_unreachable("Unexpected intrinsic");
9672 }
9673}
9674
9676 switch (SPF) {
9679 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9680 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9681 default: llvm_unreachable("Unexpected flavor");
9682 }
9683}
9684
9685std::pair<Intrinsic::ID, bool>
9687 // Check if VL contains select instructions that can be folded into a min/max
9688 // vector intrinsic and return the intrinsic if it is possible.
9689 // TODO: Support floating point min/max.
9690 bool AllCmpSingleUse = true;
9691 SelectPatternResult SelectPattern;
9692 SelectPattern.Flavor = SPF_UNKNOWN;
9693 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9694 Value *LHS, *RHS;
9695 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9696 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9697 return false;
9698 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9699 SelectPattern.Flavor != CurrentPattern.Flavor)
9700 return false;
9701 SelectPattern = CurrentPattern;
9702 AllCmpSingleUse &=
9704 return true;
9705 })) {
9706 switch (SelectPattern.Flavor) {
9707 case SPF_SMIN:
9708 return {Intrinsic::smin, AllCmpSingleUse};
9709 case SPF_UMIN:
9710 return {Intrinsic::umin, AllCmpSingleUse};
9711 case SPF_SMAX:
9712 return {Intrinsic::smax, AllCmpSingleUse};
9713 case SPF_UMAX:
9714 return {Intrinsic::umax, AllCmpSingleUse};
9715 case SPF_FMAXNUM:
9716 return {Intrinsic::maxnum, AllCmpSingleUse};
9717 case SPF_FMINNUM:
9718 return {Intrinsic::minnum, AllCmpSingleUse};
9719 default:
9720 llvm_unreachable("unexpected select pattern flavor");
9721 }
9722 }
9723 return {Intrinsic::not_intrinsic, false};
9724}
9725
9726template <typename InstTy>
9727static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9728 Value *&Init, Value *&OtherOp) {
9729 // Handle the case of a simple two-predecessor recurrence PHI.
9730 // There's a lot more that could theoretically be done here, but
9731 // this is sufficient to catch some interesting cases.
9732 // TODO: Expand list -- gep, uadd.sat etc.
9733 if (PN->getNumIncomingValues() != 2)
9734 return false;
9735
9736 for (unsigned I = 0; I != 2; ++I) {
9737 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9738 Operation && Operation->getNumOperands() >= 2) {
9739 Value *LHS = Operation->getOperand(0);
9740 Value *RHS = Operation->getOperand(1);
9741 if (LHS != PN && RHS != PN)
9742 continue;
9743
9744 Inst = Operation;
9745 Init = PN->getIncomingValue(!I);
9746 OtherOp = (LHS == PN) ? RHS : LHS;
9747 return true;
9748 }
9749 }
9750 return false;
9751}
9752
9753template <typename InstTy>
9754static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9755 Value *&Init, Value *&OtherOp0,
9756 Value *&OtherOp1) {
9757 if (PN->getNumIncomingValues() != 2)
9758 return false;
9759
9760 for (unsigned I = 0; I != 2; ++I) {
9761 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9762 Operation && Operation->getNumOperands() >= 3) {
9763 Value *Op0 = Operation->getOperand(0);
9764 Value *Op1 = Operation->getOperand(1);
9765 Value *Op2 = Operation->getOperand(2);
9766
9767 if (Op0 != PN && Op1 != PN && Op2 != PN)
9768 continue;
9769
9770 Inst = Operation;
9771 Init = PN->getIncomingValue(!I);
9772 if (Op0 == PN) {
9773 OtherOp0 = Op1;
9774 OtherOp1 = Op2;
9775 } else if (Op1 == PN) {
9776 OtherOp0 = Op0;
9777 OtherOp1 = Op2;
9778 } else {
9779 OtherOp0 = Op0;
9780 OtherOp1 = Op1;
9781 }
9782 return true;
9783 }
9784 }
9785 return false;
9786}
9788 Value *&Start, Value *&Step) {
9789 // We try to match a recurrence of the form:
9790 // %iv = [Start, %entry], [%iv.next, %backedge]
9791 // %iv.next = binop %iv, Step
9792 // Or:
9793 // %iv = [Start, %entry], [%iv.next, %backedge]
9794 // %iv.next = binop Step, %iv
9795 return matchTwoInputRecurrence(P, BO, Start, Step);
9796}
9797
9799 Value *&Start, Value *&Step) {
9800 BinaryOperator *BO = nullptr;
9801 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9802 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9803}
9804
9806 PHINode *&P, Value *&Init,
9807 Value *&OtherOp) {
9808 // Binary intrinsics only supported for now.
9809 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9810 I->getType() != I->getArgOperand(1)->getType())
9811 return false;
9812
9813 IntrinsicInst *II = nullptr;
9814 P = dyn_cast<PHINode>(I->getArgOperand(0));
9815 if (!P)
9816 P = dyn_cast<PHINode>(I->getArgOperand(1));
9817
9818 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9819}
9820
9822 PHINode *&P, Value *&Init,
9823 Value *&OtherOp0,
9824 Value *&OtherOp1) {
9825 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9826 I->getType() != I->getArgOperand(1)->getType() ||
9827 I->getType() != I->getArgOperand(2)->getType())
9828 return false;
9829 IntrinsicInst *II = nullptr;
9830 P = dyn_cast<PHINode>(I->getArgOperand(0));
9831 if (!P) {
9832 P = dyn_cast<PHINode>(I->getArgOperand(1));
9833 if (!P)
9834 P = dyn_cast<PHINode>(I->getArgOperand(2));
9835 }
9836 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9837 II == I;
9838}
9839
9840/// Return true if "icmp Pred LHS RHS" is always true.
9842 const Value *RHS) {
9843 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9844 return true;
9845
9846 switch (Pred) {
9847 default:
9848 return false;
9849
9850 case CmpInst::ICMP_SLE: {
9851 const APInt *C;
9852
9853 // LHS s<= LHS +_{nsw} C if C >= 0
9854 // LHS s<= LHS | C if C >= 0
9855 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9857 return !C->isNegative();
9858
9859 // LHS s<= smax(LHS, V) for any V
9861 return true;
9862
9863 // smin(RHS, V) s<= RHS for any V
9865 return true;
9866
9867 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9868 const Value *X;
9869 const APInt *CLHS, *CRHS;
9870 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9872 return CLHS->sle(*CRHS);
9873
9874 return false;
9875 }
9876
9877 case CmpInst::ICMP_ULE: {
9878 // LHS u<= LHS +_{nuw} V for any V
9879 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9881 return true;
9882
9883 // LHS u<= LHS | V for any V
9884 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9885 return true;
9886
9887 // LHS u<= umax(LHS, V) for any V
9889 return true;
9890
9891 // RHS >> V u<= RHS for any V
9892 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9893 return true;
9894
9895 // RHS u/ C_ugt_1 u<= RHS
9896 const APInt *C;
9897 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9898 return true;
9899
9900 // RHS & V u<= RHS for any V
9902 return true;
9903
9904 // umin(RHS, V) u<= RHS for any V
9906 return true;
9907
9908 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9909 const Value *X;
9910 const APInt *CLHS, *CRHS;
9911 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9913 return CLHS->ule(*CRHS);
9914
9915 return false;
9916 }
9917 }
9918}
9919
9920/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9921/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9922static std::optional<bool>
9924 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9925 switch (Pred) {
9926 default:
9927 return std::nullopt;
9928
9929 case CmpInst::ICMP_SLT:
9930 case CmpInst::ICMP_SLE:
9931 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9933 return true;
9934 return std::nullopt;
9935
9936 case CmpInst::ICMP_SGT:
9937 case CmpInst::ICMP_SGE:
9938 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9940 return true;
9941 return std::nullopt;
9942
9943 case CmpInst::ICMP_ULT:
9944 case CmpInst::ICMP_ULE:
9945 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9947 return true;
9948 return std::nullopt;
9949
9950 case CmpInst::ICMP_UGT:
9951 case CmpInst::ICMP_UGE:
9952 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9954 return true;
9955 return std::nullopt;
9956 }
9957}
9958
9959/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9960/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9961/// Otherwise, return std::nullopt if we can't infer anything.
9962static std::optional<bool>
9964 CmpPredicate RPred, const ConstantRange &RCR) {
9965 auto CRImpliesPred = [&](ConstantRange CR,
9966 CmpInst::Predicate Pred) -> std::optional<bool> {
9967 // If all true values for lhs and true for rhs, lhs implies rhs
9968 if (CR.icmp(Pred, RCR))
9969 return true;
9970
9971 // If there is no overlap, lhs implies not rhs
9972 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9973 return false;
9974
9975 return std::nullopt;
9976 };
9977 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9978 RPred))
9979 return Res;
9980 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9982 : LPred.dropSameSign();
9984 : RPred.dropSameSign();
9985 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9986 RPred);
9987 }
9988 return std::nullopt;
9989}
9990
9991/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
9992/// is true. Return false if LHS implies RHS is false. Otherwise, return
9993/// std::nullopt if we can't infer anything.
9994static std::optional<bool>
9995isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
9996 CmpPredicate RPred, const Value *R0, const Value *R1,
9997 const DataLayout &DL, bool LHSIsTrue) {
9998 // The rest of the logic assumes the LHS condition is true. If that's not the
9999 // case, invert the predicate to make it so.
10000 if (!LHSIsTrue)
10001 LPred = ICmpInst::getInverseCmpPredicate(LPred);
10002
10003 // We can have non-canonical operands, so try to normalize any common operand
10004 // to L0/R0.
10005 if (L0 == R1) {
10006 std::swap(R0, R1);
10007 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10008 }
10009 if (R0 == L1) {
10010 std::swap(L0, L1);
10011 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10012 }
10013 if (L1 == R1) {
10014 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10015 if (L0 != R0 || match(L0, m_ImmConstant())) {
10016 std::swap(L0, L1);
10017 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10018 std::swap(R0, R1);
10019 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10020 }
10021 }
10022
10023 // See if we can infer anything if operand-0 matches and we have at least one
10024 // constant.
10025 const APInt *Unused;
10026 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10027 // Potential TODO: We could also further use the constant range of L0/R0 to
10028 // further constraint the constant ranges. At the moment this leads to
10029 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10030 // C1` (see discussion: D58633).
10031 SimplifyQuery SQ(DL);
10036
10037 // Even if L1/R1 are not both constant, we can still sometimes deduce
10038 // relationship from a single constant. For example X u> Y implies X != 0.
10039 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10040 return R;
10041 // If both L1/R1 were exact constant ranges and we didn't get anything
10042 // here, we won't be able to deduce this.
10043 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10044 return std::nullopt;
10045 }
10046
10047 // Can we infer anything when the two compares have matching operands?
10048 if (L0 == R0 && L1 == R1)
10049 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10050
10051 // It only really makes sense in the context of signed comparison for "X - Y
10052 // must be positive if X >= Y and no overflow".
10053 // Take SGT as an example: L0:x > L1:y and C >= 0
10054 // ==> R0:(x -nsw y) < R1:(-C) is false
10055 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10056 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10057 SignedLPred == ICmpInst::ICMP_SGE) &&
10058 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10059 if (match(R1, m_NonPositive()) &&
10060 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10061 return false;
10062 }
10063
10064 // Take SLT as an example: L0:x < L1:y and C <= 0
10065 // ==> R0:(x -nsw y) < R1:(-C) is true
10066 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10067 SignedLPred == ICmpInst::ICMP_SLE) &&
10068 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10069 if (match(R1, m_NonNegative()) &&
10070 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10071 return true;
10072 }
10073
10074 // (a - b) pred C -> a != b, if 0 pred C is false
10075 // (ptrtoint(a) - ptrtoint(b)) pred C -> a != b, if 0 pred C is false
10076 Value *A, *B;
10077 if (ICmpInst::isEquality(RPred) && cmpExcludesZero(LPred, L1) &&
10078 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10079 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10084 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10085 }
10086
10087 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10088 if (L0 == R0 &&
10089 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10090 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10091 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10092 return CmpPredicate::getMatching(LPred, RPred).has_value();
10093
10094 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10095 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10096
10097 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10098 // Example: L0 u< 13 => (L0 & 16) == 0
10099 const APInt *LC, *RC, *MaskC;
10100 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10101 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10103 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10104 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10105 return true;
10106 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10107 ConstantRange(*RC)))
10108 return false;
10109 }
10110
10111 return std::nullopt;
10112}
10113
10114/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10115/// is true. Return false if LHS implies RHS is false. Otherwise, return
10116/// std::nullopt if we can't infer anything.
10117static std::optional<bool>
10119 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10120 const DataLayout &DL, bool LHSIsTrue) {
10121 // The rest of the logic assumes the LHS condition is true. If that's not the
10122 // case, invert the predicate to make it so.
10123 if (!LHSIsTrue)
10124 LPred = FCmpInst::getInversePredicate(LPred);
10125
10126 // We can have non-canonical operands, so try to normalize any common operand
10127 // to L0/R0.
10128 if (L0 == R1) {
10129 std::swap(R0, R1);
10130 RPred = FCmpInst::getSwappedPredicate(RPred);
10131 }
10132 if (R0 == L1) {
10133 std::swap(L0, L1);
10134 LPred = FCmpInst::getSwappedPredicate(LPred);
10135 }
10136 if (L1 == R1) {
10137 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10138 if (L0 != R0 || match(L0, m_ImmConstant())) {
10139 std::swap(L0, L1);
10140 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10141 std::swap(R0, R1);
10142 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10143 }
10144 }
10145
10146 // Can we infer anything when the two compares have matching operands?
10147 if (L0 == R0 && L1 == R1) {
10148 if ((LPred & RPred) == LPred)
10149 return true;
10150 if ((LPred & ~RPred) == LPred)
10151 return false;
10152 }
10153
10154 // See if we can infer anything if operand-0 matches and we have at least one
10155 // constant.
10156 const APFloat *L1C, *R1C;
10157 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10158 if (std::optional<ConstantFPRange> DomCR =
10160 if (std::optional<ConstantFPRange> ImpliedCR =
10162 if (ImpliedCR->contains(*DomCR))
10163 return true;
10164 }
10165 if (std::optional<ConstantFPRange> ImpliedCR =
10167 FCmpInst::getInversePredicate(RPred), *R1C)) {
10168 if (ImpliedCR->contains(*DomCR))
10169 return false;
10170 }
10171 }
10172 }
10173
10174 return std::nullopt;
10175}
10176
10177/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10178/// false. Otherwise, return std::nullopt if we can't infer anything. We
10179/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10180/// instruction.
10181static std::optional<bool>
10183 const Value *RHSOp0, const Value *RHSOp1,
10184 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10185 // The LHS must be an 'or', 'and', or a 'select' instruction.
10186 assert((LHS->getOpcode() == Instruction::And ||
10187 LHS->getOpcode() == Instruction::Or ||
10188 LHS->getOpcode() == Instruction::Select) &&
10189 "Expected LHS to be 'and', 'or', or 'select'.");
10190
10191 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10192
10193 // If the result of an 'or' is false, then we know both legs of the 'or' are
10194 // false. Similarly, if the result of an 'and' is true, then we know both
10195 // legs of the 'and' are true.
10196 const Value *ALHS, *ARHS;
10197 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10198 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10199 // FIXME: Make this non-recursion.
10200 if (std::optional<bool> Implication = isImpliedCondition(
10201 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10202 return Implication;
10203 if (std::optional<bool> Implication = isImpliedCondition(
10204 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10205 return Implication;
10206 return std::nullopt;
10207 }
10208 return std::nullopt;
10209}
10210
10211std::optional<bool>
10213 const Value *RHSOp0, const Value *RHSOp1,
10214 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10215 // Bail out when we hit the limit.
10217 return std::nullopt;
10218
10219 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10220 // example.
10221 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10222 return std::nullopt;
10223
10224 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10225 "Expected integer type only!");
10226
10227 // Match not
10228 if (match(LHS, m_Not(m_Value(LHS))))
10229 LHSIsTrue = !LHSIsTrue;
10230
10231 // Both LHS and RHS are icmps.
10232 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10233 CmpPredicate LHSPred;
10234 Value *LHSOp0, *LHSOp1;
10235 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10236 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10237 RHSOp1, DL, LHSIsTrue);
10238 } else {
10239 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10240 "Expected floating point type only!");
10241 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10242 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10243 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10244 DL, LHSIsTrue);
10245 }
10246
10247 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10248 /// the RHS to be an icmp.
10249 /// FIXME: Add support for and/or/select on the RHS.
10250 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10251 if ((LHSI->getOpcode() == Instruction::And ||
10252 LHSI->getOpcode() == Instruction::Or ||
10253 LHSI->getOpcode() == Instruction::Select))
10254 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10255 Depth);
10256 }
10257 return std::nullopt;
10258}
10259
10260std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10261 const DataLayout &DL,
10262 bool LHSIsTrue, unsigned Depth) {
10263 // LHS ==> RHS by definition
10264 if (LHS == RHS)
10265 return LHSIsTrue;
10266
10267 // Match not
10268 bool InvertRHS = false;
10269 if (match(RHS, m_Not(m_Value(RHS)))) {
10270 if (LHS == RHS)
10271 return !LHSIsTrue;
10272 InvertRHS = true;
10273 }
10274
10275 CmpPredicate RHSPred;
10276 Value *RHSOp0, *RHSOp1;
10277 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10278 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10279 LHSIsTrue, Depth))
10280 return InvertRHS ? !*Implied : *Implied;
10281 return std::nullopt;
10282 }
10283 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10284 if (auto Implied = isImpliedCondition(
10285 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10286 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10287 return InvertRHS ? !*Implied : *Implied;
10288 return std::nullopt;
10289 }
10290
10292 return std::nullopt;
10293
10294 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10295 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10296 const Value *RHS1, *RHS2;
10297 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10298 if (std::optional<bool> Imp =
10299 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10300 if (*Imp == true)
10301 return !InvertRHS;
10302 if (std::optional<bool> Imp =
10303 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10304 if (*Imp == true)
10305 return !InvertRHS;
10306 }
10307 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10308 if (std::optional<bool> Imp =
10309 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10310 if (*Imp == false)
10311 return InvertRHS;
10312 if (std::optional<bool> Imp =
10313 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10314 if (*Imp == false)
10315 return InvertRHS;
10316 }
10317
10318 return std::nullopt;
10319}
10320
10321// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10322// condition dominating ContextI or nullptr, if no condition is found.
10323static std::pair<Value *, bool>
10325 if (!ContextI || !ContextI->getParent())
10326 return {nullptr, false};
10327
10328 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10329 // dominator tree (eg, from a SimplifyQuery) instead?
10330 const BasicBlock *ContextBB = ContextI->getParent();
10331 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10332 if (!PredBB)
10333 return {nullptr, false};
10334
10335 // We need a conditional branch in the predecessor.
10336 Value *PredCond;
10337 BasicBlock *TrueBB, *FalseBB;
10338 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10339 return {nullptr, false};
10340
10341 // The branch should get simplified. Don't bother simplifying this condition.
10342 if (TrueBB == FalseBB)
10343 return {nullptr, false};
10344
10345 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10346 "Predecessor block does not point to successor?");
10347
10348 // Is this condition implied by the predecessor condition?
10349 return {PredCond, TrueBB == ContextBB};
10350}
10351
10352std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10353 const Instruction *ContextI,
10354 const DataLayout &DL) {
10355 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10356 auto PredCond = getDomPredecessorCondition(ContextI);
10357 if (PredCond.first)
10358 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10359 return std::nullopt;
10360}
10361
10363 const Value *LHS,
10364 const Value *RHS,
10365 const Instruction *ContextI,
10366 const DataLayout &DL) {
10367 auto PredCond = getDomPredecessorCondition(ContextI);
10368 if (PredCond.first)
10369 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10370 PredCond.second);
10371 return std::nullopt;
10372}
10373
10375 APInt &Upper, const InstrInfoQuery &IIQ,
10376 bool PreferSignedRange) {
10377 unsigned Width = Lower.getBitWidth();
10378 const APInt *C;
10379 switch (BO.getOpcode()) {
10380 case Instruction::Sub:
10381 if (match(BO.getOperand(0), m_APInt(C))) {
10382 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10383 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10384
10385 // If the caller expects a signed compare, then try to use a signed range.
10386 // Otherwise if both no-wraps are set, use the unsigned range because it
10387 // is never larger than the signed range. Example:
10388 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10389 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10390 if (PreferSignedRange && HasNSW && HasNUW)
10391 HasNUW = false;
10392
10393 if (HasNUW) {
10394 // 'sub nuw c, x' produces [0, C].
10395 Upper = *C + 1;
10396 } else if (HasNSW) {
10397 if (C->isNegative()) {
10398 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10400 Upper = *C - APInt::getSignedMaxValue(Width);
10401 } else {
10402 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10403 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10404 Lower = *C - APInt::getSignedMaxValue(Width);
10406 }
10407 }
10408 }
10409 break;
10410 case Instruction::Add:
10411 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10412 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10413 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10414
10415 // If the caller expects a signed compare, then try to use a signed
10416 // range. Otherwise if both no-wraps are set, use the unsigned range
10417 // because it is never larger than the signed range. Example: "add nuw
10418 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10419 if (PreferSignedRange && HasNSW && HasNUW)
10420 HasNUW = false;
10421
10422 if (HasNUW) {
10423 // 'add nuw x, C' produces [C, UINT_MAX].
10424 Lower = *C;
10425 } else if (HasNSW) {
10426 if (C->isNegative()) {
10427 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10429 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10430 } else {
10431 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10432 Lower = APInt::getSignedMinValue(Width) + *C;
10433 Upper = APInt::getSignedMaxValue(Width) + 1;
10434 }
10435 }
10436 }
10437 break;
10438
10439 case Instruction::And:
10440 if (match(BO.getOperand(1), m_APInt(C)))
10441 // 'and x, C' produces [0, C].
10442 Upper = *C + 1;
10443 // X & -X is a power of two or zero. So we can cap the value at max power of
10444 // two.
10445 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10446 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10447 Upper = APInt::getSignedMinValue(Width) + 1;
10448 break;
10449
10450 case Instruction::Or:
10451 if (match(BO.getOperand(1), m_APInt(C)))
10452 // 'or x, C' produces [C, UINT_MAX].
10453 Lower = *C;
10454 break;
10455
10456 case Instruction::AShr:
10457 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10458 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10460 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10461 } else if (match(BO.getOperand(0), m_APInt(C))) {
10462 unsigned ShiftAmount = Width - 1;
10463 if (!C->isZero() && IIQ.isExact(&BO))
10464 ShiftAmount = C->countr_zero();
10465 if (C->isNegative()) {
10466 // 'ashr C, x' produces [C, C >> (Width-1)]
10467 Lower = *C;
10468 Upper = C->ashr(ShiftAmount) + 1;
10469 } else {
10470 // 'ashr C, x' produces [C >> (Width-1), C]
10471 Lower = C->ashr(ShiftAmount);
10472 Upper = *C + 1;
10473 }
10474 }
10475 break;
10476
10477 case Instruction::LShr:
10478 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10479 // 'lshr x, C' produces [0, UINT_MAX >> C].
10480 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10481 } else if (match(BO.getOperand(0), m_APInt(C))) {
10482 // 'lshr C, x' produces [C >> (Width-1), C].
10483 unsigned ShiftAmount = Width - 1;
10484 if (!C->isZero() && IIQ.isExact(&BO))
10485 ShiftAmount = C->countr_zero();
10486 Lower = C->lshr(ShiftAmount);
10487 Upper = *C + 1;
10488 }
10489 break;
10490
10491 case Instruction::Shl:
10492 if (match(BO.getOperand(0), m_APInt(C))) {
10493 if (IIQ.hasNoUnsignedWrap(&BO)) {
10494 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10495 Lower = *C;
10496 Upper = Lower.shl(Lower.countl_zero()) + 1;
10497 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10498 if (C->isNegative()) {
10499 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10500 unsigned ShiftAmount = C->countl_one() - 1;
10501 Lower = C->shl(ShiftAmount);
10502 Upper = *C + 1;
10503 } else {
10504 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10505 unsigned ShiftAmount = C->countl_zero() - 1;
10506 Lower = *C;
10507 Upper = C->shl(ShiftAmount) + 1;
10508 }
10509 } else {
10510 // If lowbit is set, value can never be zero.
10511 if ((*C)[0])
10512 Lower = APInt::getOneBitSet(Width, 0);
10513 // If we are shifting a constant the largest it can be is if the longest
10514 // sequence of consecutive ones is shifted to the highbits (breaking
10515 // ties for which sequence is higher). At the moment we take a liberal
10516 // upper bound on this by just popcounting the constant.
10517 // TODO: There may be a bitwise trick for it longest/highest
10518 // consecutative sequence of ones (naive method is O(Width) loop).
10519 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10520 }
10521 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10522 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10523 }
10524 break;
10525
10526 case Instruction::SDiv:
10527 if (match(BO.getOperand(1), m_APInt(C))) {
10528 APInt IntMin = APInt::getSignedMinValue(Width);
10529 APInt IntMax = APInt::getSignedMaxValue(Width);
10530 if (C->isAllOnes()) {
10531 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10532 // where C != -1 and C != 0 and C != 1
10533 Lower = IntMin + 1;
10534 Upper = IntMax + 1;
10535 } else if (C->countl_zero() < Width - 1) {
10536 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10537 // where C != -1 and C != 0 and C != 1
10538 Lower = IntMin.sdiv(*C);
10539 Upper = IntMax.sdiv(*C);
10540 if (Lower.sgt(Upper))
10542 Upper = Upper + 1;
10543 assert(Upper != Lower && "Upper part of range has wrapped!");
10544 }
10545 } else if (match(BO.getOperand(0), m_APInt(C))) {
10546 if (C->isMinSignedValue()) {
10547 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10548 Lower = *C;
10549 Upper = Lower.lshr(1) + 1;
10550 } else {
10551 // 'sdiv C, x' produces [-|C|, |C|].
10552 Upper = C->abs() + 1;
10553 Lower = (-Upper) + 1;
10554 }
10555 }
10556 break;
10557
10558 case Instruction::UDiv:
10559 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10560 // 'udiv x, C' produces [0, UINT_MAX / C].
10561 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10562 } else if (match(BO.getOperand(0), m_APInt(C))) {
10563 // 'udiv C, x' produces [0, C].
10564 Upper = *C + 1;
10565 }
10566 break;
10567
10568 case Instruction::SRem:
10569 if (match(BO.getOperand(1), m_APInt(C))) {
10570 // 'srem x, C' produces (-|C|, |C|).
10571 Upper = C->abs();
10572 Lower = (-Upper) + 1;
10573 } else if (match(BO.getOperand(0), m_APInt(C))) {
10574 if (C->isNegative()) {
10575 // 'srem -|C|, x' produces [-|C|, 0].
10576 Upper = 1;
10577 Lower = *C;
10578 } else {
10579 // 'srem |C|, x' produces [0, |C|].
10580 Upper = *C + 1;
10581 }
10582 }
10583 break;
10584
10585 case Instruction::URem:
10586 if (match(BO.getOperand(1), m_APInt(C)))
10587 // 'urem x, C' produces [0, C).
10588 Upper = *C;
10589 else if (match(BO.getOperand(0), m_APInt(C)))
10590 // 'urem C, x' produces [0, C].
10591 Upper = *C + 1;
10592 break;
10593
10594 default:
10595 break;
10596 }
10597}
10598
10600 bool UseInstrInfo) {
10601 unsigned Width = II.getType()->getScalarSizeInBits();
10602 const APInt *C;
10603 switch (II.getIntrinsicID()) {
10604 case Intrinsic::ctlz:
10605 case Intrinsic::cttz: {
10606 APInt Upper(Width, Width);
10607 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10608 Upper += 1;
10609 // Maximum of set/clear bits is the bit width.
10611 }
10612 case Intrinsic::ctpop:
10613 // Maximum of set/clear bits is the bit width.
10615 APInt(Width, Width) + 1);
10616 case Intrinsic::uadd_sat:
10617 // uadd.sat(x, C) produces [C, UINT_MAX].
10618 if (match(II.getOperand(0), m_APInt(C)) ||
10619 match(II.getOperand(1), m_APInt(C)))
10621 break;
10622 case Intrinsic::sadd_sat:
10623 if (match(II.getOperand(0), m_APInt(C)) ||
10624 match(II.getOperand(1), m_APInt(C))) {
10625 if (C->isNegative())
10626 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10628 APInt::getSignedMaxValue(Width) + *C +
10629 1);
10630
10631 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10633 APInt::getSignedMaxValue(Width) + 1);
10634 }
10635 break;
10636 case Intrinsic::usub_sat:
10637 // usub.sat(C, x) produces [0, C].
10638 if (match(II.getOperand(0), m_APInt(C)))
10639 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10640
10641 // usub.sat(x, C) produces [0, UINT_MAX - C].
10642 if (match(II.getOperand(1), m_APInt(C)))
10644 APInt::getMaxValue(Width) - *C + 1);
10645 break;
10646 case Intrinsic::ssub_sat:
10647 if (match(II.getOperand(0), m_APInt(C))) {
10648 if (C->isNegative())
10649 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10651 *C - APInt::getSignedMinValue(Width) +
10652 1);
10653
10654 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10656 APInt::getSignedMaxValue(Width) + 1);
10657 } else if (match(II.getOperand(1), m_APInt(C))) {
10658 if (C->isNegative())
10659 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10661 APInt::getSignedMaxValue(Width) + 1);
10662
10663 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10665 APInt::getSignedMaxValue(Width) - *C +
10666 1);
10667 }
10668 break;
10669 case Intrinsic::umin:
10670 case Intrinsic::umax:
10671 case Intrinsic::smin:
10672 case Intrinsic::smax:
10673 if (!match(II.getOperand(0), m_APInt(C)) &&
10674 !match(II.getOperand(1), m_APInt(C)))
10675 break;
10676
10677 switch (II.getIntrinsicID()) {
10678 case Intrinsic::umin:
10679 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10680 case Intrinsic::umax:
10682 case Intrinsic::smin:
10684 *C + 1);
10685 case Intrinsic::smax:
10687 APInt::getSignedMaxValue(Width) + 1);
10688 default:
10689 llvm_unreachable("Must be min/max intrinsic");
10690 }
10691 break;
10692 case Intrinsic::abs:
10693 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10694 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10695 if (match(II.getOperand(1), m_One()))
10697 APInt::getSignedMaxValue(Width) + 1);
10698
10700 APInt::getSignedMinValue(Width) + 1);
10701 case Intrinsic::vscale:
10702 if (!II.getParent() || !II.getFunction())
10703 break;
10704 return getVScaleRange(II.getFunction(), Width);
10705 case Intrinsic::read_register:
10706 case Intrinsic::read_volatile_register: {
10707 const Module *M = II.getModule();
10708 if (!M || !M->getTargetTriple().isRISCV())
10709 break;
10710 if (II.getFunction() && isReadVLENB(II))
10711 return getRISCVVLENBRange(II, Width);
10712 break;
10713 }
10714 default:
10715 break;
10716 }
10717
10718 return ConstantRange::getFull(Width);
10719}
10720
10722 const InstrInfoQuery &IIQ) {
10723 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10724 const Value *LHS = nullptr, *RHS = nullptr;
10726 if (R.Flavor == SPF_UNKNOWN)
10727 return ConstantRange::getFull(BitWidth);
10728
10729 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10730 // If the negation part of the abs (in RHS) has the NSW flag,
10731 // then the result of abs(X) is [0..SIGNED_MAX],
10732 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10733 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10737
10740 }
10741
10742 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10743 // The result of -abs(X) is <= 0.
10745 APInt(BitWidth, 1));
10746 }
10747
10748 const APInt *C;
10749 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10750 return ConstantRange::getFull(BitWidth);
10751
10752 switch (R.Flavor) {
10753 case SPF_UMIN:
10755 case SPF_UMAX:
10757 case SPF_SMIN:
10759 *C + 1);
10760 case SPF_SMAX:
10763 default:
10764 return ConstantRange::getFull(BitWidth);
10765 }
10766}
10767
10769 // The maximum representable value of a half is 65504. For floats the maximum
10770 // value is 3.4e38 which requires roughly 129 bits.
10771 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10772 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10773 return;
10774 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10775 Lower = APInt(BitWidth, -65504, true);
10776 Upper = APInt(BitWidth, 65505);
10777 }
10778
10779 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10780 // For a fptoui the lower limit is left as 0.
10781 Upper = APInt(BitWidth, 65505);
10782 }
10783}
10784
10786 const SimplifyQuery &SQ,
10787 unsigned Depth) {
10788 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10789
10791 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10792
10793 if (auto *C = dyn_cast<Constant>(V))
10794 return C->toConstantRange();
10795
10796 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10797 ConstantRange CR = ConstantRange::getFull(BitWidth);
10798 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10799 APInt Lower = APInt(BitWidth, 0);
10800 APInt Upper = APInt(BitWidth, 0);
10801 // TODO: Return ConstantRange.
10802 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10804 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10806 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10807 ConstantRange CRTrue =
10808 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10809 ConstantRange CRFalse =
10810 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10811 CR = CRTrue.unionWith(CRFalse);
10813 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10814 ConstantRange SrcCR =
10815 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10816 CR = SrcCR.truncate(BitWidth);
10817 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10818 ConstantRange SrcCR =
10819 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10820 CR = SrcCR.zeroExtend(BitWidth);
10821 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10822 ConstantRange SrcCR =
10823 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10824 CR = SrcCR.signExtend(BitWidth);
10825 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10826 APInt Lower = APInt(BitWidth, 0);
10827 APInt Upper = APInt(BitWidth, 0);
10828 // TODO: Return ConstantRange.
10831 } else if (const auto *A = dyn_cast<Argument>(V))
10832 if (std::optional<ConstantRange> Range = A->getRange())
10833 CR = *Range;
10834
10835 if (auto *I = dyn_cast<Instruction>(V)) {
10836 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10838
10839 Value *FrexpSrc;
10840 if (const auto *CB = dyn_cast<CallBase>(V)) {
10841 if (std::optional<ConstantRange> Range = CB->getRange())
10842 CR = CR.intersectWith(*Range);
10844 m_Value(FrexpSrc))))) {
10845 const fltSemantics &FltSem =
10846 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10847 // It should be possible to implement this for any type, but this logic
10848 // only computes the range assuming standard subnormal handling.
10849 if (APFloat::isIEEELikeFP(FltSem)) {
10851 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10852
10853 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10854 // constrain its range when the source can be neither.
10855 if (KnownSrc.isKnownNeverInfOrNaN()) {
10856 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10857
10858 // Offset to find the true minimum exponent value for a denormal.
10859 if (!KnownSrc.isKnownNeverSubnormal())
10860 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10861
10862 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10863
10864 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10866
10867 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10868 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10869
10870 MinExp = std::max(AdjustedMin, MinExp);
10871 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10872 MaxExp);
10873
10875 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10876 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10877 /*isSigned=*/true));
10878 }
10879 }
10880 }
10881 }
10882
10883 if (SQ.CtxI && SQ.AC) {
10884 // Try to restrict the range based on information from assumptions.
10885 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10886 if (!AssumeVH)
10887 continue;
10888 CallInst *I = cast<CallInst>(AssumeVH);
10889 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10890 "Got assumption for the wrong function!");
10891 assert(I->getIntrinsicID() == Intrinsic::assume &&
10892 "must be an assume intrinsic");
10893
10894 if (!isValidAssumeForContext(I, SQ))
10895 continue;
10896 Value *Arg = I->getArgOperand(0);
10897 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10898 // Currently we just use information from comparisons.
10899 if (!Cmp || Cmp->getOperand(0) != V)
10900 continue;
10901 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10902 ConstantRange RHS =
10903 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10904 SQ.getWithInstruction(I), Depth + 1);
10905 CR = CR.intersectWith(
10906 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10907 }
10908 }
10909
10910 return CR;
10911}
10912
10913static void
10915 function_ref<void(Value *)> InsertAffected) {
10916 assert(V != nullptr);
10917 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10918 InsertAffected(V);
10919 } else if (auto *I = dyn_cast<Instruction>(V)) {
10920 InsertAffected(V);
10921
10922 // Peek through unary operators to find the source of the condition.
10923 Value *Op;
10925 m_Trunc(m_Value(Op))))) {
10927 InsertAffected(Op);
10928 }
10929 }
10930}
10931
10933 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10934 auto AddAffected = [&InsertAffected](Value *V) {
10935 addValueAffectedByCondition(V, InsertAffected);
10936 };
10937
10938 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10939 if (IsAssume) {
10940 AddAffected(LHS);
10941 AddAffected(RHS);
10942 } else if (match(RHS, m_Constant()))
10943 AddAffected(LHS);
10944 };
10945
10946 SmallVector<Value *, 8> Worklist;
10948 Worklist.push_back(Cond);
10949 while (!Worklist.empty()) {
10950 Value *V = Worklist.pop_back_val();
10951 if (!Visited.insert(V).second)
10952 continue;
10953
10954 CmpPredicate Pred;
10955 Value *A, *B, *X;
10956
10957 if (IsAssume) {
10958 AddAffected(V);
10959 if (match(V, m_Not(m_Value(X))))
10960 AddAffected(X);
10961 }
10962
10963 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10964 // assume(A && B) is split to -> assume(A); assume(B);
10965 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10966 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10967 // enough information to be worth handling (intersection of information as
10968 // opposed to union).
10969 if (!IsAssume) {
10970 Worklist.push_back(A);
10971 Worklist.push_back(B);
10972 }
10973 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10974 bool HasRHSC = match(B, m_ConstantInt());
10975 if (ICmpInst::isEquality(Pred)) {
10976 AddAffected(A);
10977 if (IsAssume)
10978 AddAffected(B);
10979 if (HasRHSC) {
10980 Value *Y;
10981 // (X << C) or (X >>_s C) or (X >>_u C).
10982 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10983 AddAffected(X);
10984 // (X & C) or (X | C).
10985 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10986 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10987 AddAffected(X);
10988 AddAffected(Y);
10989 }
10990 // X - Y
10991 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
10992 AddAffected(X);
10993 AddAffected(Y);
10994 }
10995 }
10996 } else {
10997 AddCmpOperands(A, B);
10998 if (HasRHSC) {
10999 Value *Y;
11000 // Handle (A + C1) u< C2, which is the canonical form of
11001 // A > C3 && A < C4.
11003 AddAffected(X);
11004 // X - Y pred C, which implies X != Y if 0 pred C is false.
11005 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11006 AddAffected(X);
11007 AddAffected(Y);
11008 }
11009
11010 if (ICmpInst::isUnsigned(Pred)) {
11011 // X & Y u> C -> X >u C && Y >u C
11012 // X | Y u< C -> X u< C && Y u< C
11013 // X nuw+ Y u< C -> X u< C && Y u< C
11014 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11015 match(A, m_Or(m_Value(X), m_Value(Y))) ||
11016 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
11017 AddAffected(X);
11018 AddAffected(Y);
11019 }
11020 }
11021 }
11022
11023 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11024 // by computeKnownFPClass().
11026 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11027 InsertAffected(X);
11028 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11029 InsertAffected(X);
11030 }
11031 }
11032
11033 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11034 Value *SquareOp = nullptr;
11035 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11036 AddAffected(SquareOp);
11037 };
11038 AddNuwSquareOperand(A);
11039 AddNuwSquareOperand(B);
11040
11041 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11042 AddAffected(X);
11043 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11044 AddCmpOperands(A, B);
11045
11046 // fcmp fneg(x), y
11047 // fcmp fabs(x), y
11048 // fcmp fneg(fabs(x)), y
11049 if (match(A, m_FNeg(m_Value(A))))
11050 AddAffected(A);
11051 if (match(A, m_FAbs(m_Value(A))))
11052 AddAffected(A);
11053
11055 m_Value()))) {
11056 // Handle patterns that computeKnownFPClass() support.
11057 AddAffected(A);
11058 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11059 // Assume is checked here as X is already added above for assumes in
11060 // addValueAffectedByCondition
11061 AddAffected(X);
11062 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11063 // Assume is checked here to avoid issues with ephemeral values
11064 Worklist.push_back(X);
11065 }
11066 }
11067}
11068
11070 // (X >> C) or/add (X & mask(C) != 0)
11071 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11072 if (BO->getOpcode() == Instruction::Add ||
11073 BO->getOpcode() == Instruction::Or) {
11074 const Value *X;
11075 const APInt *C1, *C2;
11076 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11080 m_Zero())))) &&
11081 C2->popcount() == C1->getZExtValue())
11082 return X;
11083 }
11084 }
11085 return nullptr;
11086}
11087
11089 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11090}
11091
11094 unsigned MaxCount, bool AllowUndefOrPoison) {
11097 auto Push = [&](const Value *V) -> bool {
11098 Constant *C;
11099 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11100 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11101 return false;
11102 // Check existence first to avoid unnecessary allocations.
11103 if (Constants.contains(C))
11104 return true;
11105 if (Constants.size() == MaxCount)
11106 return false;
11107 Constants.insert(C);
11108 return true;
11109 }
11110
11111 if (auto *Inst = dyn_cast<Instruction>(V)) {
11112 if (Visited.insert(Inst).second)
11113 Worklist.push_back(Inst);
11114 return true;
11115 }
11116 return false;
11117 };
11118 if (!Push(V))
11119 return false;
11120 while (!Worklist.empty()) {
11121 const Instruction *CurInst = Worklist.pop_back_val();
11122 switch (CurInst->getOpcode()) {
11123 case Instruction::Select:
11124 if (!Push(CurInst->getOperand(1)))
11125 return false;
11126 if (!Push(CurInst->getOperand(2)))
11127 return false;
11128 break;
11129 case Instruction::PHI:
11130 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11131 // Fast path for recurrence PHI.
11132 if (IncomingValue == CurInst)
11133 continue;
11134 if (!Push(IncomingValue))
11135 return false;
11136 }
11137 break;
11138 default:
11139 return false;
11140 }
11141 }
11142 return true;
11143}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static const Instruction * safeCtxI(const Value *V, const Instruction *CtxI)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static bool isNonZeroAddrPlusOffset(const SimplifyQuery &Q, Value *X, Value *Y)
Return true if "addr(P) + Off" cannot be zero.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match non-obvious integer minimum and maximum sequences.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static bool onlyUsedByLifetimeMarkersOrDroppableInstsHelper(const Value *V, bool AllowLifetime, bool AllowDroppable)
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CtxI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void 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:368
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:343
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:364
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:339
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:335
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:372
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:360
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:385
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:376
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:6166
LLVM_READONLY int getExactLog2Abs() const
Definition APFloat.h:1639
bool isFinite() const
Definition APFloat.h:1588
static APFloat getLargest(const fltSemantics &Sem, bool Negative=false)
Returns the largest finite number in the given semantics.
Definition APFloat.h:1242
bool isInteger() const
Definition APFloat.h:1600
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt umul_ov(const APInt &RHS, bool &Overflow) const
Definition APInt.cpp:2009
LLVM_ABI APInt udiv(const APInt &RHS) const
Unsigned division operation.
Definition APInt.cpp:1602
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
void clearBit(unsigned BitPosition)
Set a given bit to 0.
Definition APInt.h:1426
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Definition APInt.h:419
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setHighBits(unsigned hiBits)
Set the top hiBits bits.
Definition APInt.h:1411
unsigned popcount() const
Count the number of bits set.
Definition APInt.h:1690
void setBitsFrom(unsigned loBit)
Set the top bits starting from loBit.
Definition APInt.h:1405
static APInt getMaxValue(unsigned numBits)
Gets maximum unsigned value of APInt for specific bit width.
Definition APInt.h:202
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
unsigned ceilLogBase2() const
Definition APInt.h:1784
bool sgt(const APInt &RHS) const
Signed greater than comparison.
Definition APInt.h:1205
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition APInt.h:1134
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
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.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ Offset
Definition DWP.cpp:577
@ Length
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
BundleAttr getBundleAttrFromOBU(OperandBundleUse OBU)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
const Value * getLoadStorePointerOperand(const Value *V)
A helper function that returns the pointer operand of a load or store instruction.
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI 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 const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:450
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI 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 bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI 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 Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:246
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
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...
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI AssumeAlignInfo getAssumeAlignInfo(OperandBundleUse)
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition Alignment.h:202
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:267
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 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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass ceil(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ceil.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static LLVM_ABI KnownFPClass fmuladd(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmuladd.
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 atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass 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())
static LLVM_ABI KnownFPClass fmuladd_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmuladd squared, squared, addend.
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for rounding intrinsics (rint, nearbyint, round, roundeven).
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.
static LLVM_ABI KnownFPClass trunc(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for trunc.
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 log(const KnownFPClass &Src, DenormalMode Mode, bool IsMultiUnitFPType)
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass floor(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for floor.
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 DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const Instruction * CtxI
const Function * getFunction() const
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041