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
3233static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3234 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3235 bool NUW, unsigned Depth) {
3236 // (X + (X != 0)) is non zero
3237 if (matchOpWithOpEqZero(X, Y))
3238 return true;
3239
3240 if (NUW)
3241 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3242 isKnownNonZero(X, DemandedElts, Q, Depth);
3243
3244 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3245 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3246
3247 // If X and Y are both non-negative (as signed values) then their sum is not
3248 // zero unless both X and Y are zero.
3249 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3250 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3251 isKnownNonZero(X, DemandedElts, Q, Depth))
3252 return true;
3253
3254 // If X and Y are both negative (as signed values) then their sum is not
3255 // zero unless both X and Y equal INT_MIN.
3256 if (XKnown.isNegative() && YKnown.isNegative()) {
3258 // The sign bit of X is set. If some other bit is set then X is not equal
3259 // to INT_MIN.
3260 if (XKnown.One.intersects(Mask))
3261 return true;
3262 // The sign bit of Y is set. If some other bit is set then Y is not equal
3263 // to INT_MIN.
3264 if (YKnown.One.intersects(Mask))
3265 return true;
3266 }
3267
3268 // The sum of a non-negative number and a power of two is not zero.
3269 if (XKnown.isNonNegative() &&
3270 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3271 return true;
3272 if (YKnown.isNonNegative() &&
3273 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3274 return true;
3275
3276 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3277}
3278
3279static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3280 unsigned BitWidth, Value *X, Value *Y,
3281 unsigned Depth) {
3282 // (X - (X != 0)) is non zero
3283 // ((X != 0) - X) is non zero
3284 if (matchOpWithOpEqZero(X, Y))
3285 return true;
3286
3287 // TODO: Move this case into isKnownNonEqual().
3288 if (auto *C = dyn_cast<Constant>(X))
3289 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3290 return true;
3291
3292 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3293}
3294
3295static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3296 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3297 bool NUW, unsigned Depth) {
3298 // If X and Y are non-zero then so is X * Y as long as the multiplication
3299 // does not overflow.
3300 if (NSW || NUW)
3301 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3302 isKnownNonZero(Y, DemandedElts, Q, Depth);
3303
3304 // If either X or Y is odd, then if the other is non-zero the result can't
3305 // be zero.
3306 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3307 if (XKnown.One[0])
3308 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3309
3310 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3311 if (YKnown.One[0])
3312 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3313
3314 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3315 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3316 // the lowest known One of X and Y. If they are non-zero, the result
3317 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3318 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3319 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3320 BitWidth;
3321}
3322
3323static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3324 const SimplifyQuery &Q, const KnownBits &KnownVal,
3325 unsigned Depth) {
3326 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3327 switch (I->getOpcode()) {
3328 case Instruction::Shl:
3329 return Lhs.shl(Rhs);
3330 case Instruction::LShr:
3331 return Lhs.lshr(Rhs);
3332 case Instruction::AShr:
3333 return Lhs.ashr(Rhs);
3334 default:
3335 llvm_unreachable("Unknown Shift Opcode");
3336 }
3337 };
3338
3339 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3340 switch (I->getOpcode()) {
3341 case Instruction::Shl:
3342 return Lhs.lshr(Rhs);
3343 case Instruction::LShr:
3344 case Instruction::AShr:
3345 return Lhs.shl(Rhs);
3346 default:
3347 llvm_unreachable("Unknown Shift Opcode");
3348 }
3349 };
3350
3351 if (KnownVal.isUnknown())
3352 return false;
3353
3354 KnownBits KnownCnt =
3355 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3356 APInt MaxShift = KnownCnt.getMaxValue();
3357 unsigned NumBits = KnownVal.getBitWidth();
3358 if (MaxShift.uge(NumBits))
3359 return false;
3360
3361 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3362 return true;
3363
3364 // If all of the bits shifted out are known to be zero, and Val is known
3365 // non-zero then at least one non-zero bit must remain.
3366 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3367 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3368 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3369 return true;
3370
3371 return false;
3372}
3373
3375 const APInt &DemandedElts,
3376 const SimplifyQuery &Q, unsigned Depth) {
3377 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3378 switch (I->getOpcode()) {
3379 case Instruction::Alloca:
3380 // Alloca never returns null, malloc might.
3381 return I->getType()->getPointerAddressSpace() == 0;
3382 case Instruction::GetElementPtr:
3383 if (I->getType()->isPointerTy())
3385 break;
3386 case Instruction::BitCast: {
3387 // We need to be a bit careful here. We can only peek through the bitcast
3388 // if the scalar size of elements in the operand are smaller than and a
3389 // multiple of the size they are casting too. Take three cases:
3390 //
3391 // 1) Unsafe:
3392 // bitcast <2 x i16> %NonZero to <4 x i8>
3393 //
3394 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3395 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3396 // guranteed (imagine just sign bit set in the 2 i16 elements).
3397 //
3398 // 2) Unsafe:
3399 // bitcast <4 x i3> %NonZero to <3 x i4>
3400 //
3401 // Even though the scalar size of the src (`i3`) is smaller than the
3402 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3403 // its possible for the `3 x i4` elements to be zero because there are
3404 // some elements in the destination that don't contain any full src
3405 // element.
3406 //
3407 // 3) Safe:
3408 // bitcast <4 x i8> %NonZero to <2 x i16>
3409 //
3410 // This is always safe as non-zero in the 4 i8 elements implies
3411 // non-zero in the combination of any two adjacent ones. Since i8 is a
3412 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3413 // This all implies the 2 i16 elements are non-zero.
3414 Type *FromTy = I->getOperand(0)->getType();
3415 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3416 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3417 return isKnownNonZero(I->getOperand(0), Q, Depth);
3418 } break;
3419 case Instruction::IntToPtr:
3420 // Note that we have to take special care to avoid looking through
3421 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3422 // as casts that can alter the value, e.g., AddrSpaceCasts.
3423 if (!isa<ScalableVectorType>(I->getType()) &&
3424 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3425 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3426 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3427 break;
3428 case Instruction::PtrToAddr:
3429 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3430 // so we can directly forward.
3431 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3432 case Instruction::PtrToInt:
3433 // For inttoptr, make sure the result size is >= the address size. If the
3434 // address is non-zero, any larger value is also non-zero.
3435 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3436 I->getType()->getScalarSizeInBits())
3437 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3438 break;
3439 case Instruction::Trunc:
3440 // nuw/nsw trunc preserves zero/non-zero status of input.
3441 if (auto *TI = dyn_cast<TruncInst>(I))
3442 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3443 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3444 break;
3445
3446 // Iff x - y != 0, then x ^ y != 0
3447 // Therefore we can do the same exact checks
3448 case Instruction::Xor:
3449 case Instruction::Sub:
3450 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3451 I->getOperand(1), Depth);
3452 case Instruction::Or:
3453 // (X | (X != 0)) is non zero
3454 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3455 return true;
3456 // X | Y != 0 if X != Y.
3457 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3458 Depth))
3459 return true;
3460 // X | Y != 0 if X != 0 or Y != 0.
3461 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3462 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3463 case Instruction::SExt:
3464 case Instruction::ZExt:
3465 // ext X != 0 if X != 0.
3466 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3467
3468 case Instruction::Shl: {
3469 // shl nsw/nuw can't remove any non-zero bits.
3471 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3472 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3473
3474 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3475 // if the lowest bit is shifted off the end.
3477 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3478 if (Known.One[0])
3479 return true;
3480
3481 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3482 }
3483 case Instruction::LShr:
3484 case Instruction::AShr: {
3485 // shr exact can only shift out zero bits.
3487 if (BO->isExact())
3488 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3489
3490 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3491 // defined if the sign bit is shifted off the end.
3493 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3494 if (Known.isNegative())
3495 return true;
3496
3497 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3498 // position >= C, because the sum >= max(A, B).
3499 Value *A, *B;
3500 const APInt *C;
3501 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3502 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3503 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3504 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3505 if (!KnownA.One.lshr(*C).isZero())
3506 return true;
3507 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3508 if (!KnownB.One.lshr(*C).isZero())
3509 return true;
3510 }
3511
3512 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3513 }
3514 case Instruction::UDiv:
3515 case Instruction::SDiv: {
3516 // X / Y
3517 // div exact can only produce a zero if the dividend is zero.
3518 if (cast<PossiblyExactOperator>(I)->isExact())
3519 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3520
3521 KnownBits XKnown =
3522 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3523 // If X is fully unknown we won't be able to figure anything out so don't
3524 // both computing knownbits for Y.
3525 if (XKnown.isUnknown())
3526 return false;
3527
3528 KnownBits YKnown =
3529 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3530 if (I->getOpcode() == Instruction::SDiv) {
3531 // For signed division need to compare abs value of the operands.
3532 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3533 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3534 }
3535 // If X u>= Y then div is non zero (0/0 is UB).
3536 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3537 // If X is total unknown or X u< Y we won't be able to prove non-zero
3538 // with compute known bits so just return early.
3539 return XUgeY && *XUgeY;
3540 }
3541 case Instruction::Add: {
3542 // X + Y.
3543
3544 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3545 // non-zero.
3547 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3548 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3549 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3550 }
3551 case Instruction::Mul: {
3553 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3554 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3555 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3556 }
3557 case Instruction::Select: {
3558 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3559
3560 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3561 // then see if the select condition implies the arm is non-zero. For example
3562 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3563 // dominated by `X != 0`.
3564 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3565 Value *Op;
3566 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3567 // Op is trivially non-zero.
3568 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3569 return true;
3570
3571 // The condition of the select dominates the true/false arm. Check if the
3572 // condition implies that a given arm is non-zero.
3573 Value *X;
3574 CmpPredicate Pred;
3575 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3576 return false;
3577
3578 if (!IsTrueArm)
3579 Pred = ICmpInst::getInversePredicate(Pred);
3580
3581 return cmpExcludesZero(Pred, X);
3582 };
3583
3584 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3585 SelectArmIsNonZero(/* IsTrueArm */ false))
3586 return true;
3587 break;
3588 }
3589 case Instruction::PHI: {
3590 auto *PN = cast<PHINode>(I);
3592 return true;
3593
3594 // Check if all incoming values are non-zero using recursion.
3596 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3597 return llvm::all_of(PN->operands(), [&](const Use &U) {
3598 if (U.get() == PN)
3599 return true;
3600 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3601 // Check if the branch on the phi excludes zero.
3602 CmpPredicate Pred;
3603 Value *X;
3604 BasicBlock *TrueSucc, *FalseSucc;
3605 if (match(RecQ.CtxI,
3606 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3607 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3608 // Check for cases of duplicate successors.
3609 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3610 // If we're using the false successor, invert the predicate.
3611 if (FalseSucc == PN->getParent())
3612 Pred = CmpInst::getInversePredicate(Pred);
3613 if (cmpExcludesZero(Pred, X))
3614 return true;
3615 }
3616 }
3617 // Finally recurse on the edge and check it directly.
3618 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3619 });
3620 }
3621 case Instruction::InsertElement: {
3622 if (isa<ScalableVectorType>(I->getType()))
3623 break;
3624
3625 const Value *Vec = I->getOperand(0);
3626 const Value *Elt = I->getOperand(1);
3627 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3628
3629 unsigned NumElts = DemandedElts.getBitWidth();
3630 APInt DemandedVecElts = DemandedElts;
3631 bool SkipElt = false;
3632 // If we know the index we are inserting too, clear it from Vec check.
3633 if (CIdx && CIdx->getValue().ult(NumElts)) {
3634 DemandedVecElts.clearBit(CIdx->getZExtValue());
3635 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3636 }
3637
3638 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3639 // are non-zero.
3640 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3641 (DemandedVecElts.isZero() ||
3642 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3643 }
3644 case Instruction::ExtractElement:
3645 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3646 const Value *Vec = EEI->getVectorOperand();
3647 const Value *Idx = EEI->getIndexOperand();
3648 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3649 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3650 unsigned NumElts = VecTy->getNumElements();
3651 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3652 if (CIdx && CIdx->getValue().ult(NumElts))
3653 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3654 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3655 }
3656 }
3657 break;
3658 case Instruction::ShuffleVector: {
3659 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3660 if (!Shuf)
3661 break;
3662 APInt DemandedLHS, DemandedRHS;
3663 // For undef elements, we don't know anything about the common state of
3664 // the shuffle result.
3665 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3666 break;
3667 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3668 return (DemandedRHS.isZero() ||
3669 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3670 (DemandedLHS.isZero() ||
3671 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3672 }
3673 case Instruction::Freeze:
3674 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3675 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3676 Depth);
3677 case Instruction::Load: {
3678 auto *LI = cast<LoadInst>(I);
3679 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3680 // is never null.
3681 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3682 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3683 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3684 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3685 return true;
3686 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3688 }
3689
3690 // No need to fall through to computeKnownBits as range metadata is already
3691 // handled in isKnownNonZero.
3692 return false;
3693 }
3694 case Instruction::ExtractValue: {
3695 const WithOverflowInst *WO;
3697 switch (WO->getBinaryOp()) {
3698 default:
3699 break;
3700 case Instruction::Add:
3701 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3702 WO->getArgOperand(1),
3703 /*NSW=*/false,
3704 /*NUW=*/false, Depth);
3705 case Instruction::Sub:
3706 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3707 WO->getArgOperand(1), Depth);
3708 case Instruction::Mul:
3709 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3710 WO->getArgOperand(1),
3711 /*NSW=*/false, /*NUW=*/false, Depth);
3712 break;
3713 }
3714 }
3715 break;
3716 }
3717 case Instruction::Call:
3718 case Instruction::Invoke: {
3719 const auto *Call = cast<CallBase>(I);
3720 if (I->getType()->isPointerTy()) {
3721 if (Call->isReturnNonNull())
3722 return true;
3723 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3724 Call, /*MustPreserveOffset=*/true))
3725 return isKnownNonZero(RP, Q, Depth);
3726 } else {
3727 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3729 if (std::optional<ConstantRange> Range = Call->getRange()) {
3730 const APInt ZeroValue(Range->getBitWidth(), 0);
3731 if (!Range->contains(ZeroValue))
3732 return true;
3733 }
3734 if (const Value *RV = Call->getReturnedArgOperand())
3735 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3736 return true;
3737 }
3738
3739 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3740 switch (II->getIntrinsicID()) {
3741 case Intrinsic::sshl_sat:
3742 case Intrinsic::ushl_sat:
3743 case Intrinsic::abs:
3744 case Intrinsic::bitreverse:
3745 case Intrinsic::bswap:
3746 case Intrinsic::ctpop:
3747 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3748 // NB: We don't do usub_sat here as in any case we can prove its
3749 // non-zero, we will fold it to `sub nuw` in InstCombine.
3750 case Intrinsic::ssub_sat:
3751 // For most types, if x != y then ssub.sat x, y != 0. But
3752 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3753 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3754 if (BitWidth == 1)
3755 return false;
3756 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3757 II->getArgOperand(1), Depth);
3758 case Intrinsic::sadd_sat:
3759 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3760 II->getArgOperand(1),
3761 /*NSW=*/true, /* NUW=*/false, Depth);
3762 // Vec reverse preserves zero/non-zero status from input vec.
3763 case Intrinsic::vector_reverse:
3764 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3765 Q, Depth);
3766 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3767 case Intrinsic::vector_reduce_or:
3768 case Intrinsic::vector_reduce_umax:
3769 case Intrinsic::vector_reduce_umin:
3770 case Intrinsic::vector_reduce_smax:
3771 case Intrinsic::vector_reduce_smin:
3772 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3773 case Intrinsic::umax:
3774 case Intrinsic::uadd_sat:
3775 // umax(X, (X != 0)) is non zero
3776 // X +usat (X != 0) is non zero
3777 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3778 return true;
3779
3780 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3781 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3782 case Intrinsic::smax: {
3783 // If either arg is strictly positive the result is non-zero. Otherwise
3784 // the result is non-zero if both ops are non-zero.
3785 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3786 const KnownBits &OpKnown) {
3787 if (!OpNonZero.has_value())
3788 OpNonZero = OpKnown.isNonZero() ||
3789 isKnownNonZero(Op, DemandedElts, Q, Depth);
3790 return *OpNonZero;
3791 };
3792 // Avoid re-computing isKnownNonZero.
3793 std::optional<bool> Op0NonZero, Op1NonZero;
3794 KnownBits Op1Known =
3795 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3796 if (Op1Known.isNonNegative() &&
3797 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3798 return true;
3799 KnownBits Op0Known =
3800 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3801 if (Op0Known.isNonNegative() &&
3802 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3803 return true;
3804 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3805 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3806 }
3807 case Intrinsic::smin: {
3808 // If either arg is negative the result is non-zero. Otherwise
3809 // the result is non-zero if both ops are non-zero.
3810 KnownBits Op1Known =
3811 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3812 if (Op1Known.isNegative())
3813 return true;
3814 KnownBits Op0Known =
3815 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3816 if (Op0Known.isNegative())
3817 return true;
3818
3819 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3820 return true;
3821 }
3822 [[fallthrough]];
3823 case Intrinsic::umin:
3824 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3825 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3826 case Intrinsic::cttz:
3827 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3828 .Zero[0];
3829 case Intrinsic::ctlz:
3830 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3831 .isNonNegative();
3832 case Intrinsic::fshr:
3833 case Intrinsic::fshl:
3834 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3835 if (II->getArgOperand(0) == II->getArgOperand(1))
3836 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3837 break;
3838 case Intrinsic::vscale:
3839 return true;
3840 case Intrinsic::experimental_get_vector_length:
3841 return isKnownNonZero(I->getOperand(0), Q, Depth);
3842 default:
3843 break;
3844 }
3845 break;
3846 }
3847
3848 return false;
3849 }
3850 }
3851
3853 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3854 return Known.One != 0;
3855}
3856
3857/// Return true if the given value is known to be non-zero when defined. For
3858/// vectors, return true if every demanded element is known to be non-zero when
3859/// defined. For pointers, if the context instruction and dominator tree are
3860/// specified, perform context-sensitive analysis and return true if the
3861/// pointer couldn't possibly be null at the specified instruction.
3862/// Supports values with integer or pointer type and vectors of integers.
3863bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3864 const SimplifyQuery &Q, unsigned Depth) {
3865 Type *Ty = V->getType();
3866
3867#ifndef NDEBUG
3868 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3869
3870 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3871 assert(
3872 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3873 "DemandedElt width should equal the fixed vector number of elements");
3874 } else {
3875 assert(DemandedElts == APInt(1, 1) &&
3876 "DemandedElt width should be 1 for scalars");
3877 }
3878#endif
3879
3880 if (auto *C = dyn_cast<Constant>(V)) {
3881 if (C->isNullValue())
3882 return false;
3883 if (isa<ConstantInt>(C))
3884 // Must be non-zero due to null test above.
3885 return true;
3886
3887 // For constant vectors, check that all elements are poison or known
3888 // non-zero to determine that the whole vector is known non-zero.
3889 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3890 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3891 if (!DemandedElts[i])
3892 continue;
3893 Constant *Elt = C->getAggregateElement(i);
3894 if (!Elt || Elt->isNullValue())
3895 return false;
3896 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3897 return false;
3898 }
3899 return true;
3900 }
3901
3902 // Constant ptrauth can be null, iff the base pointer can be.
3903 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3904 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3905
3906 // A global variable in address space 0 is non null unless extern weak
3907 // or an absolute symbol reference. Other address spaces may have null as a
3908 // valid address for a global, so we can't assume anything.
3909 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3910 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3911 GV->getType()->getAddressSpace() == 0)
3912 return true;
3913 }
3914
3915 // For constant expressions, fall through to the Operator code below.
3916 if (!isa<ConstantExpr>(V))
3917 return false;
3918 }
3919
3920 if (const auto *A = dyn_cast<Argument>(V))
3921 if (std::optional<ConstantRange> Range = A->getRange()) {
3922 const APInt ZeroValue(Range->getBitWidth(), 0);
3923 if (!Range->contains(ZeroValue))
3924 return true;
3925 }
3926
3927 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3928 return true;
3929
3930 // Some of the tests below are recursive, so bail out if we hit the limit.
3932 return false;
3933
3934 // Check for pointer simplifications.
3935
3936 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3937 // A byval, inalloca may not be null in a non-default addres space. A
3938 // nonnull argument is assumed never 0.
3939 if (const Argument *A = dyn_cast<Argument>(V)) {
3940 if (((A->hasPassPointeeByValueCopyAttr() &&
3941 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3942 A->hasNonNullAttr()))
3943 return true;
3944 }
3945 }
3946
3947 if (const auto *I = dyn_cast<Operator>(V))
3948 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3949 return true;
3950
3951 if (!isa<Constant>(V) &&
3953 return true;
3954
3955 if (const Value *Stripped = stripNullTest(V))
3956 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3957
3958 return false;
3959}
3960
3962 unsigned Depth) {
3963 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3964 APInt DemandedElts =
3965 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3966 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3967}
3968
3969/// If the pair of operators are the same invertible function, return the
3970/// the operands of the function corresponding to each input. Otherwise,
3971/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3972/// every input value to exactly one output value. This is equivalent to
3973/// saying that Op1 and Op2 are equal exactly when the specified pair of
3974/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3975static std::optional<std::pair<Value*, Value*>>
3977 const Operator *Op2) {
3978 if (Op1->getOpcode() != Op2->getOpcode())
3979 return std::nullopt;
3980
3981 auto getOperands = [&](unsigned OpNum) -> auto {
3982 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3983 };
3984
3985 switch (Op1->getOpcode()) {
3986 default:
3987 break;
3988 case Instruction::Or:
3989 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3990 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3991 break;
3992 [[fallthrough]];
3993 case Instruction::Xor:
3994 case Instruction::Add: {
3995 Value *Other;
3996 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3997 return std::make_pair(Op1->getOperand(1), Other);
3998 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3999 return std::make_pair(Op1->getOperand(0), Other);
4000 break;
4001 }
4002 case Instruction::Sub:
4003 if (Op1->getOperand(0) == Op2->getOperand(0))
4004 return getOperands(1);
4005 if (Op1->getOperand(1) == Op2->getOperand(1))
4006 return getOperands(0);
4007 break;
4008 case Instruction::Mul: {
4009 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4010 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4011 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4012 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4013 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4014 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4015 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4016 break;
4017
4018 // Assume operand order has been canonicalized
4019 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4020 isa<ConstantInt>(Op1->getOperand(1)) &&
4021 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4022 return getOperands(0);
4023 break;
4024 }
4025 case Instruction::Shl: {
4026 // Same as multiplies, with the difference that we don't need to check
4027 // for a non-zero multiply. Shifts always multiply by non-zero.
4028 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4029 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4030 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4031 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4032 break;
4033
4034 if (Op1->getOperand(1) == Op2->getOperand(1))
4035 return getOperands(0);
4036 break;
4037 }
4038 case Instruction::AShr:
4039 case Instruction::LShr: {
4040 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4041 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4042 if (!PEO1->isExact() || !PEO2->isExact())
4043 break;
4044
4045 if (Op1->getOperand(1) == Op2->getOperand(1))
4046 return getOperands(0);
4047 break;
4048 }
4049 case Instruction::SExt:
4050 case Instruction::ZExt:
4051 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4052 return getOperands(0);
4053 break;
4054 case Instruction::PHI: {
4055 const PHINode *PN1 = cast<PHINode>(Op1);
4056 const PHINode *PN2 = cast<PHINode>(Op2);
4057
4058 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4059 // are a single invertible function of the start values? Note that repeated
4060 // application of an invertible function is also invertible
4061 BinaryOperator *BO1 = nullptr;
4062 Value *Start1 = nullptr, *Step1 = nullptr;
4063 BinaryOperator *BO2 = nullptr;
4064 Value *Start2 = nullptr, *Step2 = nullptr;
4065 if (PN1->getParent() != PN2->getParent() ||
4066 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4067 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4068 break;
4069
4071 cast<Operator>(BO2));
4072 if (!Values)
4073 break;
4074
4075 // We have to be careful of mutually defined recurrences here. Ex:
4076 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4077 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4078 // The invertibility of these is complicated, and not worth reasoning
4079 // about (yet?).
4080 if (Values->first != PN1 || Values->second != PN2)
4081 break;
4082
4083 return std::make_pair(Start1, Start2);
4084 }
4085 }
4086 return std::nullopt;
4087}
4088
4089/// Return true if V1 == (binop V2, X), where X is known non-zero.
4090/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4091/// implies V2 != V1.
4092static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4093 const APInt &DemandedElts,
4094 const SimplifyQuery &Q, unsigned Depth) {
4096 if (!BO)
4097 return false;
4098 switch (BO->getOpcode()) {
4099 default:
4100 break;
4101 case Instruction::Or:
4102 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4103 break;
4104 [[fallthrough]];
4105 case Instruction::Xor:
4106 case Instruction::Add:
4107 Value *Op = nullptr;
4108 if (V2 == BO->getOperand(0))
4109 Op = BO->getOperand(1);
4110 else if (V2 == BO->getOperand(1))
4111 Op = BO->getOperand(0);
4112 else
4113 return false;
4114 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4115 }
4116 return false;
4117}
4118
4119/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4120/// the multiplication is nuw or nsw.
4121static bool isNonEqualMul(const Value *V1, const Value *V2,
4122 const APInt &DemandedElts, const SimplifyQuery &Q,
4123 unsigned Depth) {
4124 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4125 const APInt *C;
4126 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4127 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4128 !C->isZero() && !C->isOne() &&
4129 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4130 }
4131 return false;
4132}
4133
4134/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4135/// the shift is nuw or nsw.
4136static bool isNonEqualShl(const Value *V1, const Value *V2,
4137 const APInt &DemandedElts, const SimplifyQuery &Q,
4138 unsigned Depth) {
4139 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4140 const APInt *C;
4141 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4142 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4143 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4144 }
4145 return false;
4146}
4147
4148static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4149 const APInt &DemandedElts, const SimplifyQuery &Q,
4150 unsigned Depth) {
4151 // Check two PHIs are in same block.
4152 if (PN1->getParent() != PN2->getParent())
4153 return false;
4154
4156 bool UsedFullRecursion = false;
4157 for (const BasicBlock *IncomBB : PN1->blocks()) {
4158 if (!VisitedBBs.insert(IncomBB).second)
4159 continue; // Don't reprocess blocks that we have dealt with already.
4160 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4161 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4162 const APInt *C1, *C2;
4163 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4164 continue;
4165
4166 // Only one pair of phi operands is allowed for full recursion.
4167 if (UsedFullRecursion)
4168 return false;
4169
4171 RecQ.CtxI = IncomBB->getTerminator();
4172 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4173 return false;
4174 UsedFullRecursion = true;
4175 }
4176 return true;
4177}
4178
4179static bool isNonEqualSelect(const Value *V1, const Value *V2,
4180 const APInt &DemandedElts, const SimplifyQuery &Q,
4181 unsigned Depth) {
4182 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4183 if (!SI1)
4184 return false;
4185
4186 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4187 const Value *Cond1 = SI1->getCondition();
4188 const Value *Cond2 = SI2->getCondition();
4189 if (Cond1 == Cond2)
4190 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4191 DemandedElts, Q, Depth + 1) &&
4192 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4193 DemandedElts, Q, Depth + 1);
4194 }
4195 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4196 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4197}
4198
4199// Check to see if A is both a GEP and is the incoming value for a PHI in the
4200// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4201// one of them being the recursive GEP A and the other a ptr at same base and at
4202// the same/higher offset than B we are only incrementing the pointer further in
4203// loop if offset of recursive GEP is greater than 0.
4205 const SimplifyQuery &Q) {
4206 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4207 return false;
4208
4209 auto *GEPA = dyn_cast<GEPOperator>(A);
4210 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4211 return false;
4212
4213 // Handle 2 incoming PHI values with one being a recursive GEP.
4214 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4215 if (!PN || PN->getNumIncomingValues() != 2)
4216 return false;
4217
4218 // Search for the recursive GEP as an incoming operand, and record that as
4219 // Step.
4220 Value *Start = nullptr;
4221 Value *Step = const_cast<Value *>(A);
4222 if (PN->getIncomingValue(0) == Step)
4223 Start = PN->getIncomingValue(1);
4224 else if (PN->getIncomingValue(1) == Step)
4225 Start = PN->getIncomingValue(0);
4226 else
4227 return false;
4228
4229 // Other incoming node base should match the B base.
4230 // StartOffset >= OffsetB && StepOffset > 0?
4231 // StartOffset <= OffsetB && StepOffset < 0?
4232 // Is non-equal if above are true.
4233 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4234 // optimisation to inbounds GEPs only.
4235 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4236 APInt StartOffset(IndexWidth, 0);
4237 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4238 APInt StepOffset(IndexWidth, 0);
4239 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4240
4241 // Check if Base Pointer of Step matches the PHI.
4242 if (Step != PN)
4243 return false;
4244 APInt OffsetB(IndexWidth, 0);
4245 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4246 return Start == B &&
4247 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4248 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4249}
4250
4251static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4252 const SimplifyQuery &Q, unsigned Depth) {
4253 if (!Q.CtxI)
4254 return false;
4255
4256 // Try to infer NonEqual based on information from dominating conditions.
4257 if (Q.DC && Q.DT) {
4258 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4259 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4260 Value *Cond = BI->getCondition();
4261 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4262 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4264 /*LHSIsTrue=*/true, Depth)
4265 .value_or(false))
4266 return true;
4267
4268 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4269 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4271 /*LHSIsTrue=*/false, Depth)
4272 .value_or(false))
4273 return true;
4274 }
4275
4276 return false;
4277 };
4278
4279 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4280 IsKnownNonEqualFromDominatingCondition(V2))
4281 return true;
4282 }
4283
4284 if (!Q.AC)
4285 return false;
4286
4287 // Try to infer NonEqual based on information from assumptions.
4288 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4289 if (!AssumeVH)
4290 continue;
4291 CallInst *I = cast<CallInst>(AssumeVH);
4292
4293 assert(I->getFunction() == Q.CtxI->getFunction() &&
4294 "Got assumption for the wrong function!");
4295 assert(I->getIntrinsicID() == Intrinsic::assume &&
4296 "must be an assume intrinsic");
4297
4298 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4299 /*LHSIsTrue=*/true, Depth)
4300 .value_or(false) &&
4302 return true;
4303 }
4304
4305 return false;
4306}
4307
4308static bool isNonEqualURem(const Value *X, const Value *Rem,
4309 const SimplifyQuery &Q) {
4310 const Value *Y;
4311 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4312 return false;
4313
4314 // For a defined urem, X != X urem Y exactly when X u>= Y.
4315 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4317 return true;
4318
4319 std::optional<bool> Implied =
4321 return Implied && *Implied;
4322}
4323
4324/// Return true if it is known that V1 != V2.
4325static bool isKnownNonEqual(const Value *V1, const Value *V2,
4326 const APInt &DemandedElts, const SimplifyQuery &Q,
4327 unsigned Depth) {
4328 if (V1 == V2)
4329 return false;
4330 if (V1->getType() != V2->getType())
4331 // We can't look through casts yet.
4332 return false;
4333
4335 return false;
4336
4337 // See if we can recurse through (exactly one of) our operands. This
4338 // requires our operation be 1-to-1 and map every input value to exactly
4339 // one output value. Such an operation is invertible.
4340 auto *O1 = dyn_cast<Operator>(V1);
4341 auto *O2 = dyn_cast<Operator>(V2);
4342 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4343 if (auto Values = getInvertibleOperands(O1, O2))
4344 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4345 Depth + 1);
4346
4347 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4348 const PHINode *PN2 = cast<PHINode>(V2);
4349 // FIXME: This is missing a generalization to handle the case where one is
4350 // a PHI and another one isn't.
4351 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4352 return true;
4353 };
4354 }
4355
4356 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4357 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4358 return true;
4359
4360 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4361 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4362 return true;
4363
4364 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4365 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4366 return true;
4367
4368 if (V1->getType()->isIntOrIntVectorTy()) {
4369 // Are any known bits in V1 contradictory to known bits in V2? If V1
4370 // has a known zero where V2 has a known one, they must not be equal.
4371 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4372 if (!Known1.isUnknown()) {
4373 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4374 if (Known1.Zero.intersects(Known2.One) ||
4375 Known2.Zero.intersects(Known1.One))
4376 return true;
4377 }
4378 }
4379
4380 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4381 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4382 return true;
4383
4386 return true;
4387
4388 Value *A, *B;
4389 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4390 // Check PtrToInt type matches the pointer size.
4391 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4393 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4394
4395 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4396 return true;
4397
4398 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4399 return true;
4400
4401 return false;
4402}
4403
4404/// For vector constants, loop over the elements and find the constant with the
4405/// minimum number of sign bits. Return 0 if the value is not a vector constant
4406/// or if any element was not analyzed; otherwise, return the count for the
4407/// element with the minimum number of sign bits.
4409 const APInt &DemandedElts,
4410 unsigned TyBits) {
4411 const auto *CV = dyn_cast<Constant>(V);
4412 if (!CV || !isa<FixedVectorType>(CV->getType()))
4413 return 0;
4414
4415 unsigned MinSignBits = TyBits;
4416 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4417 for (unsigned i = 0; i != NumElts; ++i) {
4418 if (!DemandedElts[i])
4419 continue;
4420 // If we find a non-ConstantInt, bail out.
4421 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4422 if (!Elt)
4423 return 0;
4424
4425 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4426 }
4427
4428 return MinSignBits;
4429}
4430
4431static unsigned ComputeNumSignBitsImpl(const Value *V,
4432 const APInt &DemandedElts,
4433 const SimplifyQuery &Q, unsigned Depth);
4434
4435static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4436 const SimplifyQuery &Q, unsigned Depth) {
4437 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4438 assert(Result > 0 && "At least one sign bit needs to be present!");
4439 return Result;
4440}
4441
4442/// Return the number of times the sign bit of the register is replicated into
4443/// the other bits. We know that at least 1 bit is always equal to the sign bit
4444/// (itself), but other cases can give us information. For example, immediately
4445/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4446/// other, so we return 3. For vectors, return the number of sign bits for the
4447/// vector element with the minimum number of known sign bits of the demanded
4448/// elements in the vector specified by DemandedElts.
4449static unsigned ComputeNumSignBitsImpl(const Value *V,
4450 const APInt &DemandedElts,
4451 const SimplifyQuery &Q, unsigned Depth) {
4452 Type *Ty = V->getType();
4453#ifndef NDEBUG
4454 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4455
4456 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4457 assert(
4458 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4459 "DemandedElt width should equal the fixed vector number of elements");
4460 } else {
4461 assert(DemandedElts == APInt(1, 1) &&
4462 "DemandedElt width should be 1 for scalars");
4463 }
4464#endif
4465
4466 // We return the minimum number of sign bits that are guaranteed to be present
4467 // in V, so for undef we have to conservatively return 1. We don't have the
4468 // same behavior for poison though -- that's a FIXME today.
4469
4470 Type *ScalarTy = Ty->getScalarType();
4471 unsigned TyBits = ScalarTy->isPointerTy() ?
4472 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4473 Q.DL.getTypeSizeInBits(ScalarTy);
4474
4475 unsigned Tmp, Tmp2;
4476 unsigned FirstAnswer = 1;
4477
4478 // Note that ConstantInt is handled by the general computeKnownBits case
4479 // below.
4480
4482 return 1;
4483
4484 if (auto *U = dyn_cast<Operator>(V)) {
4485 switch (Operator::getOpcode(V)) {
4486 default: break;
4487 case Instruction::BitCast: {
4488 Value *Src = U->getOperand(0);
4489 Type *SrcTy = Src->getType();
4490
4491 // Skip if the source type is not an integer or integer vector type
4492 // This ensures we only process integer-like types
4493 if (!SrcTy->isIntOrIntVectorTy())
4494 break;
4495
4496 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4497
4498 // Bitcast 'large element' scalar/vector to 'small element' vector.
4499 if ((SrcBits % TyBits) != 0)
4500 break;
4501
4502 // Only proceed if the destination type is a fixed-size vector
4503 if (isa<FixedVectorType>(Ty)) {
4504 // Fast case - sign splat can be simply split across the small elements.
4505 // This works for both vector and scalar sources
4506 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4507 if (Tmp == SrcBits)
4508 return TyBits;
4509 }
4510 break;
4511 }
4512 case Instruction::SExt:
4513 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4514 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4515 Tmp;
4516
4517 case Instruction::SDiv: {
4518 const APInt *Denominator;
4519 // sdiv X, C -> adds log(C) sign bits.
4520 if (match(U->getOperand(1), m_APInt(Denominator))) {
4521
4522 // Ignore non-positive denominator.
4523 if (!Denominator->isStrictlyPositive())
4524 break;
4525
4526 // Calculate the incoming numerator bits.
4527 unsigned NumBits =
4528 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4529
4530 // Add floor(log(C)) bits to the numerator bits.
4531 return std::min(TyBits, NumBits + Denominator->logBase2());
4532 }
4533 break;
4534 }
4535
4536 case Instruction::SRem: {
4537 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4538
4539 const APInt *Denominator;
4540 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4541 // positive constant. This let us put a lower bound on the number of sign
4542 // bits.
4543 if (match(U->getOperand(1), m_APInt(Denominator))) {
4544
4545 // Ignore non-positive denominator.
4546 if (Denominator->isStrictlyPositive()) {
4547 // Calculate the leading sign bit constraints by examining the
4548 // denominator. Given that the denominator is positive, there are two
4549 // cases:
4550 //
4551 // 1. The numerator is positive. The result range is [0,C) and
4552 // [0,C) u< (1 << ceilLogBase2(C)).
4553 //
4554 // 2. The numerator is negative. Then the result range is (-C,0] and
4555 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4556 //
4557 // Thus a lower bound on the number of sign bits is `TyBits -
4558 // ceilLogBase2(C)`.
4559
4560 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4561 Tmp = std::max(Tmp, ResBits);
4562 }
4563 }
4564 return Tmp;
4565 }
4566
4567 case Instruction::AShr: {
4568 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4569 // ashr X, C -> adds C sign bits. Vectors too.
4570 const APInt *ShAmt;
4571 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4572 if (ShAmt->uge(TyBits))
4573 break; // Bad shift.
4574 unsigned ShAmtLimited = ShAmt->getZExtValue();
4575 Tmp += ShAmtLimited;
4576 if (Tmp > TyBits) Tmp = TyBits;
4577 }
4578 return Tmp;
4579 }
4580 case Instruction::Shl: {
4581 const APInt *ShAmt;
4582 Value *X = nullptr;
4583 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4584 // shl destroys sign bits.
4585 if (ShAmt->uge(TyBits))
4586 break; // Bad shift.
4587 // We can look through a zext (more or less treating it as a sext) if
4588 // all extended bits are shifted out.
4589 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4590 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4591 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4592 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4593 } else
4594 Tmp =
4595 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4596 if (ShAmt->uge(Tmp))
4597 break; // Shifted all sign bits out.
4598 Tmp2 = ShAmt->getZExtValue();
4599 return Tmp - Tmp2;
4600 }
4601 break;
4602 }
4603 case Instruction::And:
4604 case Instruction::Or:
4605 case Instruction::Xor: // NOT is handled here.
4606 // Logical binary ops preserve the number of sign bits at the worst.
4607 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4608 if (Tmp != 1) {
4609 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4610 FirstAnswer = std::min(Tmp, Tmp2);
4611 // We computed what we know about the sign bits as our first
4612 // answer. Now proceed to the generic code that uses
4613 // computeKnownBits, and pick whichever answer is better.
4614 }
4615 break;
4616
4617 case Instruction::Select: {
4618 // If we have a clamp pattern, we know that the number of sign bits will
4619 // be the minimum of the clamp min/max range.
4620 const Value *X;
4621 const APInt *CLow, *CHigh;
4622 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4623 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4624
4625 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4626 if (Tmp == 1)
4627 break;
4628 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4629 return std::min(Tmp, Tmp2);
4630 }
4631
4632 case Instruction::Add:
4633 // Add can have at most one carry bit. Thus we know that the output
4634 // is, at worst, one more bit than the inputs.
4635 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4636 if (Tmp == 1) break;
4637
4638 // Special case decrementing a value (ADD X, -1):
4639 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4640 if (CRHS->isAllOnesValue()) {
4641 KnownBits Known(TyBits);
4642 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4643
4644 // If the input is known to be 0 or 1, the output is 0/-1, which is
4645 // all sign bits set.
4646 if ((Known.Zero | 1).isAllOnes())
4647 return TyBits;
4648
4649 // If we are subtracting one from a positive number, there is no carry
4650 // out of the result.
4651 if (Known.isNonNegative())
4652 return Tmp;
4653 }
4654
4655 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4656 if (Tmp2 == 1)
4657 break;
4658 return std::min(Tmp, Tmp2) - 1;
4659
4660 case Instruction::Sub:
4661 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4662 if (Tmp2 == 1)
4663 break;
4664
4665 // Handle NEG.
4666 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4667 if (CLHS->isNullValue()) {
4668 KnownBits Known(TyBits);
4669 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4670 // If the input is known to be 0 or 1, the output is 0/-1, which is
4671 // all sign bits set.
4672 if ((Known.Zero | 1).isAllOnes())
4673 return TyBits;
4674
4675 // If the input is known to be positive (the sign bit is known clear),
4676 // the output of the NEG has the same number of sign bits as the
4677 // input.
4678 if (Known.isNonNegative())
4679 return Tmp2;
4680
4681 // Otherwise, we treat this like a SUB.
4682 }
4683
4684 // Sub can have at most one carry bit. Thus we know that the output
4685 // is, at worst, one more bit than the inputs.
4686 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4687 if (Tmp == 1)
4688 break;
4689 return std::min(Tmp, Tmp2) - 1;
4690
4691 case Instruction::Mul: {
4692 // The output of the Mul can be at most twice the valid bits in the
4693 // inputs.
4694 unsigned SignBitsOp0 =
4695 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4696 if (SignBitsOp0 == 1)
4697 break;
4698 unsigned SignBitsOp1 =
4699 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4700 if (SignBitsOp1 == 1)
4701 break;
4702 unsigned OutValidBits =
4703 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4704 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4705 }
4706
4707 case Instruction::PHI: {
4708 const PHINode *PN = cast<PHINode>(U);
4709 unsigned NumIncomingValues = PN->getNumIncomingValues();
4710 // Don't analyze large in-degree PHIs.
4711 if (NumIncomingValues > 4) break;
4712 // Unreachable blocks may have zero-operand PHI nodes.
4713 if (NumIncomingValues == 0) break;
4714
4715 // Take the minimum of all incoming values. This can't infinitely loop
4716 // because of our depth threshold.
4718 Tmp = TyBits;
4719 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4720 if (Tmp == 1) return Tmp;
4721 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4722 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4723 DemandedElts, RecQ, Depth + 1));
4724 }
4725 return Tmp;
4726 }
4727
4728 case Instruction::Trunc: {
4729 // If the input contained enough sign bits that some remain after the
4730 // truncation, then we can make use of that. Otherwise we don't know
4731 // anything.
4732 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4733 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4734 if (Tmp > (OperandTyBits - TyBits))
4735 return Tmp - (OperandTyBits - TyBits);
4736
4737 return 1;
4738 }
4739
4740 case Instruction::ExtractElement:
4741 // Look through extract element. At the moment we keep this simple and
4742 // skip tracking the specific element. But at least we might find
4743 // information valid for all elements of the vector (for example if vector
4744 // is sign extended, shifted, etc).
4745 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4746
4747 case Instruction::ShuffleVector: {
4748 // Collect the minimum number of sign bits that are shared by every vector
4749 // element referenced by the shuffle.
4750 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4751 if (!Shuf) {
4752 // FIXME: Add support for shufflevector constant expressions.
4753 return 1;
4754 }
4755 APInt DemandedLHS, DemandedRHS;
4756 // For undef elements, we don't know anything about the common state of
4757 // the shuffle result.
4758 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4759 return 1;
4760 Tmp = std::numeric_limits<unsigned>::max();
4761 if (!!DemandedLHS) {
4762 const Value *LHS = Shuf->getOperand(0);
4763 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4764 }
4765 // If we don't know anything, early out and try computeKnownBits
4766 // fall-back.
4767 if (Tmp == 1)
4768 break;
4769 if (!!DemandedRHS) {
4770 const Value *RHS = Shuf->getOperand(1);
4771 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4772 Tmp = std::min(Tmp, Tmp2);
4773 }
4774 // If we don't know anything, early out and try computeKnownBits
4775 // fall-back.
4776 if (Tmp == 1)
4777 break;
4778 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4779 return Tmp;
4780 }
4781 case Instruction::Call: {
4782 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4783 switch (II->getIntrinsicID()) {
4784 default:
4785 break;
4786 case Intrinsic::abs:
4787 Tmp =
4788 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4789 if (Tmp == 1)
4790 break;
4791
4792 // Absolute value reduces number of sign bits by at most 1.
4793 return Tmp - 1;
4794 case Intrinsic::smin:
4795 case Intrinsic::smax: {
4796 const APInt *CLow, *CHigh;
4797 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4798 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4799 }
4800 }
4801 }
4802 }
4803 }
4804 }
4805
4806 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4807 // use this information.
4808
4809 // If we can examine all elements of a vector constant successfully, we're
4810 // done (we can't do any better than that). If not, keep trying.
4811 if (unsigned VecSignBits =
4812 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4813 return VecSignBits;
4814
4815 KnownBits Known(TyBits);
4816 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4817
4818 // If we know that the sign bit is either zero or one, determine the number of
4819 // identical bits in the top of the input value.
4820 return std::max(FirstAnswer, Known.countMinSignBits());
4821}
4822
4824 const TargetLibraryInfo *TLI) {
4825 const Function *F = CB.getCalledFunction();
4826 if (!F)
4828
4829 if (F->isIntrinsic())
4830 return F->getIntrinsicID();
4831
4832 // We are going to infer semantics of a library function based on mapping it
4833 // to an LLVM intrinsic. Check that the library function is available from
4834 // this callbase and in this environment.
4835 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4837
4838 LibFunc Func = TLI->getLibFunc(CB);
4839 if (Func == NotLibFunc)
4841
4842 switch (Func) {
4843 default:
4844 break;
4845 case LibFunc_sin:
4846 case LibFunc_sinf:
4847 case LibFunc_sinl:
4848 return Intrinsic::sin;
4849 case LibFunc_cos:
4850 case LibFunc_cosf:
4851 case LibFunc_cosl:
4852 return Intrinsic::cos;
4853 case LibFunc_tan:
4854 case LibFunc_tanf:
4855 case LibFunc_tanl:
4856 return Intrinsic::tan;
4857 case LibFunc_asin:
4858 case LibFunc_asinf:
4859 case LibFunc_asinl:
4860 return Intrinsic::asin;
4861 case LibFunc_acos:
4862 case LibFunc_acosf:
4863 case LibFunc_acosl:
4864 return Intrinsic::acos;
4865 case LibFunc_atan:
4866 case LibFunc_atanf:
4867 case LibFunc_atanl:
4868 return Intrinsic::atan;
4869 case LibFunc_atan2:
4870 case LibFunc_atan2f:
4871 case LibFunc_atan2l:
4872 return Intrinsic::atan2;
4873 case LibFunc_sinh:
4874 case LibFunc_sinhf:
4875 case LibFunc_sinhl:
4876 return Intrinsic::sinh;
4877 case LibFunc_cosh:
4878 case LibFunc_coshf:
4879 case LibFunc_coshl:
4880 return Intrinsic::cosh;
4881 case LibFunc_tanh:
4882 case LibFunc_tanhf:
4883 case LibFunc_tanhl:
4884 return Intrinsic::tanh;
4885 case LibFunc_exp:
4886 case LibFunc_expf:
4887 case LibFunc_expl:
4888 return Intrinsic::exp;
4889 case LibFunc_exp2:
4890 case LibFunc_exp2f:
4891 case LibFunc_exp2l:
4892 return Intrinsic::exp2;
4893 case LibFunc_exp10:
4894 case LibFunc_exp10f:
4895 case LibFunc_exp10l:
4896 return Intrinsic::exp10;
4897 case LibFunc_log:
4898 case LibFunc_logf:
4899 case LibFunc_logl:
4900 return Intrinsic::log;
4901 case LibFunc_log10:
4902 case LibFunc_log10f:
4903 case LibFunc_log10l:
4904 return Intrinsic::log10;
4905 case LibFunc_log2:
4906 case LibFunc_log2f:
4907 case LibFunc_log2l:
4908 return Intrinsic::log2;
4909 case LibFunc_fabs:
4910 case LibFunc_fabsf:
4911 case LibFunc_fabsl:
4912 return Intrinsic::fabs;
4913 case LibFunc_fmin:
4914 case LibFunc_fminf:
4915 case LibFunc_fminl:
4916 return Intrinsic::minnum;
4917 case LibFunc_fmax:
4918 case LibFunc_fmaxf:
4919 case LibFunc_fmaxl:
4920 return Intrinsic::maxnum;
4921 case LibFunc_copysign:
4922 case LibFunc_copysignf:
4923 case LibFunc_copysignl:
4924 return Intrinsic::copysign;
4925 case LibFunc_floor:
4926 case LibFunc_floorf:
4927 case LibFunc_floorl:
4928 return Intrinsic::floor;
4929 case LibFunc_ceil:
4930 case LibFunc_ceilf:
4931 case LibFunc_ceill:
4932 return Intrinsic::ceil;
4933 case LibFunc_trunc:
4934 case LibFunc_truncf:
4935 case LibFunc_truncl:
4936 return Intrinsic::trunc;
4937 case LibFunc_rint:
4938 case LibFunc_rintf:
4939 case LibFunc_rintl:
4940 return Intrinsic::rint;
4941 case LibFunc_nearbyint:
4942 case LibFunc_nearbyintf:
4943 case LibFunc_nearbyintl:
4944 return Intrinsic::nearbyint;
4945 case LibFunc_round:
4946 case LibFunc_roundf:
4947 case LibFunc_roundl:
4948 return Intrinsic::round;
4949 case LibFunc_roundeven:
4950 case LibFunc_roundevenf:
4951 case LibFunc_roundevenl:
4952 return Intrinsic::roundeven;
4953 case LibFunc_pow:
4954 case LibFunc_powf:
4955 case LibFunc_powl:
4956 return Intrinsic::pow;
4957 case LibFunc_sqrt:
4958 case LibFunc_sqrtf:
4959 case LibFunc_sqrtl:
4960 return Intrinsic::sqrt;
4961 }
4962
4964}
4965
4966/// Given an exploded icmp instruction, return true if the comparison only
4967/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4968/// the result of the comparison is true when the input value is signed.
4970 bool &TrueIfSigned) {
4971 switch (Pred) {
4972 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4973 TrueIfSigned = true;
4974 return RHS.isZero();
4975 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4976 TrueIfSigned = true;
4977 return RHS.isAllOnes();
4978 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4979 TrueIfSigned = false;
4980 return RHS.isAllOnes();
4981 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4982 TrueIfSigned = false;
4983 return RHS.isZero();
4984 case ICmpInst::ICMP_UGT:
4985 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4986 TrueIfSigned = true;
4987 return RHS.isMaxSignedValue();
4988 case ICmpInst::ICMP_UGE:
4989 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4990 TrueIfSigned = true;
4991 return RHS.isMinSignedValue();
4992 case ICmpInst::ICMP_ULT:
4993 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4994 TrueIfSigned = false;
4995 return RHS.isMinSignedValue();
4996 case ICmpInst::ICMP_ULE:
4997 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4998 TrueIfSigned = false;
4999 return RHS.isMaxSignedValue();
5000 default:
5001 return false;
5002 }
5003}
5004
5006 bool CondIsTrue,
5007 const Instruction *CtxI,
5008 KnownFPClass &KnownFromContext,
5009 unsigned Depth = 0) {
5010 Value *A, *B;
5012 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
5013 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
5014 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
5015 Depth + 1);
5016 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
5017 Depth + 1);
5018 return;
5019 }
5021 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
5022 Depth + 1);
5023 return;
5024 }
5025 CmpPredicate Pred;
5026 Value *LHS;
5027 uint64_t ClassVal = 0;
5028 const APFloat *CRHS;
5029 const APInt *RHS;
5030 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5031 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5032 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
5033 LHS != V);
5034 if (CmpVal == V)
5035 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5037 m_Specific(V), m_ConstantInt(ClassVal)))) {
5038 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5039 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5040 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5041 m_APInt(RHS)))) {
5042 bool TrueIfSigned;
5043 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5044 return;
5045 if (TrueIfSigned == CondIsTrue)
5046 KnownFromContext.signBitMustBeOne();
5047 else
5048 KnownFromContext.signBitMustBeZero();
5049 }
5050}
5051
5052/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5053/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5054/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5055/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5056/// exponent range is [-149, -2], but the 0 edge case is above this range).
5057static std::tuple<int, int, int>
5059 if (!Q.CtxI || !Q.DC || !Q.DT)
5061
5062 // Intersect the bounds implied by every dominating condition, keeping the
5063 // tightest maximum. A value may participate in multiple compares
5064 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5065 int MaxExp = APFloat::IEK_Inf;
5066 int MaxExpNonZero = APFloat::IEK_Inf;
5067
5068 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5069 CmpPredicate Pred;
5070 const APFloat *LimitC;
5071 if (!match(BI->getCondition(),
5072 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5073 continue;
5074
5075 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5076 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5077 continue;
5078
5079 // If fabs(x) <= K, implies the exponent min exp range.
5080 // if fabs(x) >= K, swap the successor
5081 bool IsLessEqual =
5082 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5083 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5084 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5085
5086 bool KnownStrictlyLess =
5087 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5088 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5089
5090 BasicBlockEdge Edge1(BI->getParent(),
5091 BI->getSuccessor(IsLessEqual ? 0 : 1));
5092 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5093 // frexp returns an exponent one greater than ilogb.
5094 int Exp = ilogb(*LimitC) + 1;
5095
5096 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5097 // exponent drops by one when K is exact power of two.
5098 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5099 --Exp;
5100
5101 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5102 // may exclude.
5103
5104 // TODO: Figure out lower bound to detect no-underflow.
5105 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5106 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5107 }
5108 }
5109
5110 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5111}
5112
5114 const SimplifyQuery &Q) {
5115 KnownFPClass KnownFromContext;
5116
5117 if (Q.CC && Q.CC->AffectedValues.contains(V))
5119 KnownFromContext);
5120
5121 if (!Q.CtxI)
5122 return KnownFromContext;
5123
5124 if (Q.DC && Q.DT) {
5125 // Handle dominating conditions.
5126 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5127 Value *Cond = BI->getCondition();
5128
5129 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5130 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5131 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5132 KnownFromContext);
5133
5134 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5135 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5136 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5137 KnownFromContext);
5138 }
5139 }
5140
5141 if (!Q.AC)
5142 return KnownFromContext;
5143
5144 // Try to restrict the floating-point classes based on information from
5145 // assumptions.
5146 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5147 if (!AssumeVH)
5148 continue;
5149 CallInst *I = cast<CallInst>(AssumeVH);
5150
5151 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5152 "Got assumption for the wrong function!");
5153 assert(I->getIntrinsicID() == Intrinsic::assume &&
5154 "must be an assume intrinsic");
5155
5156 if (!isValidAssumeForContext(I, Q))
5157 continue;
5158
5159 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5160 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5161 }
5162
5163 return KnownFromContext;
5164}
5165
5167 Value *Arm, bool Invert,
5168 const SimplifyQuery &SQ,
5169 unsigned Depth) {
5170
5171 KnownFPClass KnownSrc;
5173 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5174 Depth + 1);
5175 KnownSrc = KnownSrc.unionWith(Known);
5176 if (KnownSrc.isUnknown())
5177 return;
5178
5179 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5180 Known = KnownSrc;
5181}
5182
5183void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5184 FPClassTest InterestedClasses, KnownFPClass &Known,
5185 const SimplifyQuery &Q, unsigned Depth);
5186
5188 FPClassTest InterestedClasses,
5189 const SimplifyQuery &Q, unsigned Depth) {
5190 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5191 APInt DemandedElts =
5192 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5193 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5194}
5195
5197 const APInt &DemandedElts,
5198 FPClassTest InterestedClasses,
5200 const SimplifyQuery &Q,
5201 unsigned Depth) {
5202 if ((InterestedClasses &
5204 return;
5205
5206 KnownFPClass KnownSrc;
5207 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5208 KnownSrc, Q, Depth + 1);
5209 Known = KnownFPClass::fptrunc(KnownSrc);
5210}
5211
5213 switch (IID) {
5214 case Intrinsic::minimum:
5216 case Intrinsic::maximum:
5218 case Intrinsic::minimumnum:
5220 case Intrinsic::maximumnum:
5222 case Intrinsic::minnum:
5224 case Intrinsic::maxnum:
5226 default:
5227 llvm_unreachable("not a floating-point min-max intrinsic");
5228 }
5229}
5230
5231/// \return true if this is a floating point value that is known to have a
5232/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5233static bool isAbsoluteValueULEOne(const Value *V) {
5234 // TODO: Handle frexp
5235 // TODO: Other rounding intrinsics?
5236 // TODO: Try computeKnownExponentRangeFromContext
5237
5238 // fabs(x - floor(x)) <= 1
5239 const Value *SubFloorX;
5240 if (match(V, m_FSub(m_Value(SubFloorX),
5242 return true;
5243
5246}
5247
5248void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5249 FPClassTest InterestedClasses, KnownFPClass &Known,
5250 const SimplifyQuery &Q, unsigned Depth) {
5251 assert(Known.isUnknown() && "should not be called with known information");
5252
5253 if (!DemandedElts) {
5254 // No demanded elts, better to assume we don't know anything.
5255 Known.resetAll();
5256 return;
5257 }
5258
5259 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5260
5261 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5262 Known = KnownFPClass(CFP->getValueAPF());
5263 return;
5264 }
5265
5267 Known.setKnownFPClasses(fcPosZero);
5268 Known.setSignBit(false);
5269 return;
5270 }
5271
5272 if (isa<PoisonValue>(V)) {
5273 Known.setKnownFPClasses(fcNone);
5274 Known.setSignBit(false);
5275 return;
5276 }
5277
5278 // Try to handle fixed width vector constants
5279 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5280 const Constant *CV = dyn_cast<Constant>(V);
5281 if (VFVTy && CV) {
5282 Known.setKnownFPClasses(fcNone);
5283 bool SignBitAllZero = true;
5284 bool SignBitAllOne = true;
5285
5286 // For vectors, verify that each element is not NaN.
5287 unsigned NumElts = VFVTy->getNumElements();
5288 for (unsigned i = 0; i != NumElts; ++i) {
5289 if (!DemandedElts[i])
5290 continue;
5291
5292 Constant *Elt = CV->getAggregateElement(i);
5293 if (!Elt) {
5294 Known = KnownFPClass();
5295 return;
5296 }
5297 if (isa<PoisonValue>(Elt))
5298 continue;
5299 auto *CElt = dyn_cast<ConstantFP>(Elt);
5300 if (!CElt) {
5301 Known = KnownFPClass();
5302 return;
5303 }
5304
5305 const APFloat &C = CElt->getValueAPF();
5306 Known.setKnownFPClasses(Known.getKnownFPClasses() | C.classify());
5307 if (C.isNegative())
5308 SignBitAllZero = false;
5309 else
5310 SignBitAllOne = false;
5311 }
5312 if (SignBitAllOne != SignBitAllZero)
5313 Known.setSignBit(SignBitAllOne);
5314 return;
5315 }
5316
5317 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5318 Known.setKnownFPClasses(fcNone);
5319 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5320 Known |= CDS->getElementAsAPFloat(I).classify();
5321 return;
5322 }
5323
5324 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5325 // TODO: Handle complex aggregates
5326 Known.setKnownFPClasses(fcNone);
5327 for (const Use &Op : CA->operands()) {
5328 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5329 if (!CFP) {
5330 Known = KnownFPClass();
5331 return;
5332 }
5333
5334 Known |= CFP->getValueAPF().classify();
5335 }
5336
5337 return;
5338 }
5339
5340 FPClassTest KnownNotFromFlags = fcNone;
5341 if (const auto *CB = dyn_cast<CallBase>(V))
5342 KnownNotFromFlags |= CB->getRetNoFPClass();
5343 else if (const auto *Arg = dyn_cast<Argument>(V))
5344 KnownNotFromFlags |= Arg->getNoFPClass();
5345
5346 const Operator *Op = dyn_cast<Operator>(V);
5348 if (FPOp->hasNoNaNs())
5349 KnownNotFromFlags |= fcNan;
5350 if (FPOp->hasNoInfs())
5351 KnownNotFromFlags |= fcInf;
5352 }
5353
5354 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5355 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5356
5357 // We no longer need to find out about these bits from inputs if we can
5358 // assume this from flags/attributes.
5359 InterestedClasses &= ~KnownNotFromFlags;
5360
5361 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5362 Known.knownNot(KnownNotFromFlags);
5363 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5364 if (*AssumedClasses.getSignBit())
5365 Known.signBitMustBeOne();
5366 else
5367 Known.signBitMustBeZero();
5368 }
5369 });
5370
5371 if (!Op)
5372 return;
5373
5374 // All recursive calls that increase depth must come after this.
5376 return;
5377
5378 const unsigned Opc = Op->getOpcode();
5379 switch (Opc) {
5380 case Instruction::FNeg: {
5381 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5382 Known, Q, Depth + 1);
5383 Known.fneg();
5384 break;
5385 }
5386 case Instruction::Select: {
5387 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5388 KnownFPClass Res;
5389 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5390 Depth + 1);
5391 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5392 Depth);
5393 return Res;
5394 };
5395 // Only known if known in both the LHS and RHS.
5396 Known =
5397 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5398 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5399 break;
5400 }
5401 case Instruction::Load: {
5402 const MDNode *NoFPClass =
5403 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5404 if (!NoFPClass)
5405 break;
5406
5407 ConstantInt *MaskVal =
5409 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5410 break;
5411 }
5412 case Instruction::Call: {
5413 const CallInst *II = cast<CallInst>(Op);
5414 const Intrinsic::ID IID = II->getIntrinsicID();
5415 switch (IID) {
5416 case Intrinsic::fabs: {
5417 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5418 // If we only care about the sign bit we don't need to inspect the
5419 // operand.
5420 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5421 InterestedClasses, Known, Q, Depth + 1);
5422 }
5423
5424 Known.fabs();
5425 break;
5426 }
5427 case Intrinsic::copysign: {
5428 KnownFPClass KnownSign;
5429
5430 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5431 Known, Q, Depth + 1);
5432 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5433 KnownSign, Q, Depth + 1);
5434 Known.copysign(KnownSign);
5435 break;
5436 }
5437 case Intrinsic::fma:
5438 case Intrinsic::fmuladd: {
5439 if ((InterestedClasses & fcNegative) == fcNone)
5440 break;
5441
5442 // FIXME: This should check isGuaranteedNotToBeUndef
5443 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5444 KnownFPClass KnownSrc, KnownAddend;
5445 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5446 InterestedClasses, KnownAddend, Q, Depth + 1);
5447 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5448 InterestedClasses, KnownSrc, Q, Depth + 1);
5449
5450 const Function *F = II->getFunction();
5451 const fltSemantics &FltSem =
5452 II->getType()->getScalarType()->getFltSemantics();
5454 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5455
5456 if (KnownNotFromFlags & fcNan) {
5457 KnownSrc.knownNot(fcNan);
5458 KnownAddend.knownNot(fcNan);
5459 }
5460
5461 if (KnownNotFromFlags & fcInf) {
5462 KnownSrc.knownNot(fcInf);
5463 KnownAddend.knownNot(fcInf);
5464 }
5465
5466 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5467 break;
5468 }
5469
5470 KnownFPClass KnownSrc[3];
5471 for (int I = 0; I != 3; ++I) {
5472 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5473 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5474 if (KnownSrc[I].isUnknown())
5475 return;
5476
5477 if (KnownNotFromFlags & fcNan)
5478 KnownSrc[I].knownNot(fcNan);
5479 if (KnownNotFromFlags & fcInf)
5480 KnownSrc[I].knownNot(fcInf);
5481 }
5482
5483 const Function *F = II->getFunction();
5484 const fltSemantics &FltSem =
5485 II->getType()->getScalarType()->getFltSemantics();
5487 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5488 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5489 break;
5490 }
5491 case Intrinsic::sqrt:
5492 case Intrinsic::experimental_constrained_sqrt: {
5493 KnownFPClass KnownSrc;
5494 FPClassTest InterestedSrcs = InterestedClasses;
5495 if (InterestedClasses & fcNan)
5496 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5497
5498 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5499 KnownSrc, Q, Depth + 1);
5500
5502
5503 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5504 if (!HasNSZ) {
5505 const Function *F = II->getFunction();
5506 const fltSemantics &FltSem =
5507 II->getType()->getScalarType()->getFltSemantics();
5508 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5509 }
5510
5511 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5512 if (HasNSZ)
5513 Known.knownNot(fcNegZero);
5514
5515 break;
5516 }
5517 case Intrinsic::sin: {
5518 KnownFPClass KnownSrc;
5519 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5520 KnownSrc, Q, Depth + 1);
5521 Known = KnownFPClass::sin(KnownSrc);
5522 break;
5523 }
5524 case Intrinsic::cos: {
5525 KnownFPClass KnownSrc;
5526 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5527 KnownSrc, Q, Depth + 1);
5528 Known = KnownFPClass::cos(KnownSrc);
5529 break;
5530 }
5531 case Intrinsic::tan: {
5532 KnownFPClass KnownSrc;
5533 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5534 KnownSrc, Q, Depth + 1);
5535 Known = KnownFPClass::tan(KnownSrc);
5536 break;
5537 }
5538 case Intrinsic::sinh: {
5539 KnownFPClass KnownSrc;
5540 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5541 KnownSrc, Q, Depth + 1);
5542 Known = KnownFPClass::sinh(KnownSrc);
5543 break;
5544 }
5545 case Intrinsic::cosh: {
5546 KnownFPClass KnownSrc;
5547 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5548 KnownSrc, Q, Depth + 1);
5549 Known = KnownFPClass::cosh(KnownSrc);
5550 break;
5551 }
5552 case Intrinsic::tanh: {
5553 KnownFPClass KnownSrc;
5554 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5555 KnownSrc, Q, Depth + 1);
5556 Known = KnownFPClass::tanh(KnownSrc);
5557 break;
5558 }
5559 case Intrinsic::asin: {
5560 KnownFPClass KnownSrc;
5561 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5562 KnownSrc, Q, Depth + 1);
5563 Known = KnownFPClass::asin(KnownSrc);
5564 break;
5565 }
5566 case Intrinsic::acos: {
5567 KnownFPClass KnownSrc;
5568 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5569 KnownSrc, Q, Depth + 1);
5570 Known = KnownFPClass::acos(KnownSrc);
5571 break;
5572 }
5573 case Intrinsic::atan: {
5574 KnownFPClass KnownSrc;
5575 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5576 KnownSrc, Q, Depth + 1);
5577 Known = KnownFPClass::atan(KnownSrc);
5578 break;
5579 }
5580 case Intrinsic::atan2: {
5581 FPClassTest InterestedY = InterestedClasses;
5582 FPClassTest InterestedX = InterestedClasses;
5583
5584 // We can rule out negative values if y cannot have a negative value.
5585 if ((InterestedClasses & fcNegFinite) != fcNone)
5586 InterestedY |= fcNegative;
5587
5588 // We can rule out positive values if y cannot have a positive value.
5589 if ((InterestedClasses & fcPosFinite) != fcNone)
5590 InterestedY |= fcPositive | fcNegSubnormal;
5591
5592 // We can rule out zero and subnormal if x cannot have a positive value.
5593 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5594 InterestedX |= fcPositive | fcNegSubnormal;
5595
5596 KnownFPClass KnownY, KnownX;
5597 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5598 KnownY, Q, Depth + 1);
5599 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5600 KnownX, Q, Depth + 1);
5601
5602 const Function *F = II->getFunction();
5604 F ? F->getDenormalMode(
5605 II->getType()->getScalarType()->getFltSemantics())
5607 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5608 break;
5609 }
5610 case Intrinsic::maxnum:
5611 case Intrinsic::minnum:
5612 case Intrinsic::minimum:
5613 case Intrinsic::maximum:
5614 case Intrinsic::minimumnum:
5615 case Intrinsic::maximumnum: {
5616 KnownFPClass KnownLHS, KnownRHS;
5617 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5618 KnownLHS, Q, Depth + 1);
5619 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5620 KnownRHS, Q, Depth + 1);
5621
5622 const Function *F = II->getFunction();
5623
5625 F ? F->getDenormalMode(
5626 II->getType()->getScalarType()->getFltSemantics())
5628
5629 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5630 Mode);
5631 break;
5632 }
5633 case Intrinsic::canonicalize: {
5634 KnownFPClass KnownSrc;
5635 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5636 KnownSrc, Q, Depth + 1);
5637
5638 const Function *F = II->getFunction();
5639 DenormalMode DenormMode =
5640 F ? F->getDenormalMode(
5641 II->getType()->getScalarType()->getFltSemantics())
5643 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5644 break;
5645 }
5646 case Intrinsic::vector_reduce_fmax:
5647 case Intrinsic::vector_reduce_fmin:
5648 case Intrinsic::vector_reduce_fmaximum:
5649 case Intrinsic::vector_reduce_fminimum:
5650 case Intrinsic::vector_reduce_fmaximumnum:
5651 case Intrinsic::vector_reduce_fminimumnum: {
5652 // reduce min/max will choose an element from one of the vector elements,
5653 // so we can infer and class information that is common to all elements.
5654 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5655 InterestedClasses, Q, Depth + 1);
5656 // Can only propagate sign if output is never NaN.
5657 if (!Known.isKnownNeverNaN())
5658 Known.setSignBit(std::nullopt);
5659 break;
5660 }
5661 // reverse preserves all characteristics of the input vec's element.
5662 case Intrinsic::vector_reverse:
5664 II->getArgOperand(0), DemandedElts.reverseBits(),
5665 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5666 break;
5667 case Intrinsic::trunc:
5668 case Intrinsic::floor:
5669 case Intrinsic::ceil:
5670 case Intrinsic::rint:
5671 case Intrinsic::nearbyint:
5672 case Intrinsic::round:
5673 case Intrinsic::roundeven: {
5674 KnownFPClass KnownSrc;
5675 FPClassTest InterestedSrcs = InterestedClasses;
5676
5677 // Negative round ups towards zero produce negative zero.
5678 if (InterestedSrcs & fcNegFinite)
5679 InterestedSrcs |= fcNegFinite;
5680
5681 // Negative subnormals may flush to positive zero.
5682 if (InterestedSrcs & fcPosFinite)
5683 InterestedSrcs |= fcPosFinite | fcNegSubnormal;
5684
5685 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5686 KnownSrc, Q, Depth + 1);
5687
5688 const Function *F = II->getFunction();
5690 F ? F->getDenormalMode(
5691 II->getType()->getScalarType()->getFltSemantics())
5693 const bool IsMultiUnitFPType =
5694 V->getType()->getScalarType()->isMultiUnitFPType();
5695
5696 const bool IsTrunc = IID == Intrinsic::trunc;
5697 Known = KnownFPClass::roundToIntegral(KnownSrc, IsTrunc,
5698 IsMultiUnitFPType, Mode);
5699 break;
5700 }
5701 case Intrinsic::exp:
5702 case Intrinsic::exp2:
5703 case Intrinsic::exp10:
5704 case Intrinsic::amdgcn_exp2: {
5705 KnownFPClass KnownSrc;
5706 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5707 KnownSrc, Q, Depth + 1);
5708
5709 Known = KnownFPClass::exp(KnownSrc);
5710
5711 Type *EltTy = II->getType()->getScalarType();
5712 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5713 Known.knownNot(fcSubnormal);
5714
5715 break;
5716 }
5717 case Intrinsic::fptrunc_round: {
5718 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5719 Q, Depth);
5720 break;
5721 }
5722 case Intrinsic::log:
5723 case Intrinsic::log10:
5724 case Intrinsic::log2:
5725 case Intrinsic::experimental_constrained_log:
5726 case Intrinsic::experimental_constrained_log10:
5727 case Intrinsic::experimental_constrained_log2:
5728 case Intrinsic::amdgcn_log: {
5729 FPClassTest InterestedSrcs = fcNone;
5730
5731 // log(negative) produces NaN.
5732 if ((InterestedClasses & fcNan) != fcNone)
5733 InterestedSrcs |= fcNan | fcNegative;
5734
5735 // log(logical-zero) produces negative infinity.
5736 if ((InterestedClasses & fcNegInf) != fcNone)
5737 InterestedSrcs |= fcZero | fcSubnormal;
5738
5739 // log(x) < -0.0 if x < +1.0
5740 if ((InterestedClasses & fcNegNormal) != fcNone)
5741 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5742
5743 // log(x) >= +0.0 if x >= +1.0
5744 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5745 InterestedSrcs |= fcPosNormal;
5746
5747 // log(x) is positive infinity iff x is positive infinity.
5748 if ((InterestedClasses & fcPosInf) != fcNone)
5749 InterestedSrcs |= fcPosInf;
5750
5751 KnownFPClass KnownSrc;
5752 if (InterestedSrcs != fcNone)
5753 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5754 KnownSrc, Q, Depth + 1);
5755 const Function *F = II->getFunction();
5757 F ? F->getDenormalMode(
5758 II->getType()->getScalarType()->getFltSemantics())
5760 const bool IsMultiUnitFPType =
5761 V->getType()->getScalarType()->isMultiUnitFPType();
5762 Known = KnownFPClass::log(KnownSrc, Mode, IsMultiUnitFPType);
5763 break;
5764 }
5765 case Intrinsic::pow: {
5766 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5767 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5768 if (!WantNaN && !WantNegative)
5769 break;
5770
5771 FPClassTest InterestedLHS = fcNone;
5772 FPClassTest InterestedRHS = fcNone;
5773 if (WantNaN) {
5774 // pow may return NaN if one of the arguments is NaN. NaN may also be
5775 // produced from a negative, non-zero finite base and a non-integer
5776 // exponent.
5777 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5778 InterestedRHS |= fcNan;
5779 }
5780 if (WantNegative) {
5781 // A negative value is returned when a negative base is raised to an odd
5782 // integer power. Only normal values can be odd integers.
5783 InterestedLHS |= fcNegative;
5784 InterestedRHS |= fcNormal;
5785 }
5786
5787 KnownFPClass KnownLHS;
5788 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5789 KnownLHS, Q, Depth + 1);
5790
5791 // If the LHS is unknown, then querying the RHS is only useful for rare
5792 // edge cases.
5793 if (KnownLHS.isUnknown())
5794 break;
5795
5796 KnownFPClass KnownRHS;
5797 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5798 KnownRHS, Q, Depth + 1);
5799 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5800 break;
5801 }
5802 case Intrinsic::powi: {
5803 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5804 break;
5805
5806 // The exponent is always a scalar, even when raising a vector to a power.
5807 const Value *Exp = II->getArgOperand(1);
5808 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5809 KnownBits ExponentKnownBits(BitWidth);
5810 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5811
5812 FPClassTest InterestedSrcs = fcNone;
5813 if (InterestedClasses & fcNan)
5814 InterestedSrcs |= fcNan;
5815 if (!ExponentKnownBits.isZero()) {
5816 if (InterestedClasses & fcInf)
5817 InterestedSrcs |= fcFinite | fcInf;
5818 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5819 InterestedSrcs |= fcNegative;
5820 }
5821
5822 KnownFPClass KnownSrc;
5823 if (InterestedSrcs != fcNone)
5824 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5825 KnownSrc, Q, Depth + 1);
5826
5827 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5828 break;
5829 }
5830 case Intrinsic::ldexp: {
5831 KnownFPClass KnownSrc;
5832 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5833 KnownSrc, Q, Depth + 1);
5834 // Can refine inf/zero handling based on the exponent operand.
5835 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5836
5837 const Value *ExpArg = II->getArgOperand(1);
5838 ConstantRange ExpKnownRange =
5839 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5840 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5841 : ConstantRange::getFull(
5842 ExpArg->getType()->getScalarSizeInBits());
5843
5844 const fltSemantics &Flt =
5845 II->getType()->getScalarType()->getFltSemantics();
5846
5847 const Function *F = II->getFunction();
5849 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5850
5851 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5852 ExpKnownRange.getSignedMax(), Flt, Mode);
5853 break;
5854 }
5855 case Intrinsic::arithmetic_fence: {
5856 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5857 Known, Q, Depth + 1);
5858 break;
5859 }
5860 case Intrinsic::experimental_constrained_sitofp:
5861 case Intrinsic::experimental_constrained_uitofp:
5862 // Cannot produce nan
5863 Known.knownNot(fcNan);
5864
5865 // sitofp and uitofp turn into +0.0 for zero.
5866 Known.knownNot(fcNegZero);
5867
5868 // Integers cannot be subnormal
5869 Known.knownNot(fcSubnormal);
5870
5871 if (IID == Intrinsic::experimental_constrained_uitofp)
5872 Known.signBitMustBeZero();
5873
5874 // TODO: Copy inf handling from instructions
5875 break;
5876
5877 case Intrinsic::amdgcn_fract: {
5878 Known.knownNot(fcInf);
5879
5880 if (InterestedClasses & fcNan) {
5881 KnownFPClass KnownSrc;
5882 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5883 InterestedClasses, KnownSrc, Q, Depth + 1);
5884
5885 if (KnownSrc.isKnownNeverInfOrNaN())
5886 Known.knownNot(fcNan);
5887 else if (KnownSrc.isKnownNever(fcSNan))
5888 Known.knownNot(fcSNan);
5889 }
5890
5891 break;
5892 }
5893 case Intrinsic::amdgcn_rcp: {
5894 KnownFPClass KnownSrc;
5895 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5896 KnownSrc, Q, Depth + 1);
5897
5898 Known.propagateNonNaN(KnownSrc);
5899
5900 Type *EltTy = II->getType()->getScalarType();
5901
5902 // f32 denormal always flushed.
5903 if (EltTy->isFloatTy()) {
5904 Known.knownNot(fcSubnormal);
5905 KnownSrc.knownNot(fcSubnormal);
5906 }
5907
5908 if (KnownSrc.isKnownNever(fcNegative))
5909 Known.knownNot(fcNegative);
5910 if (KnownSrc.isKnownNever(fcPositive))
5911 Known.knownNot(fcPositive);
5912
5913 if (const Function *F = II->getFunction()) {
5914 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5915 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5916 Known.knownNot(fcPosInf);
5917 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5918 Known.knownNot(fcNegInf);
5919 }
5920
5921 break;
5922 }
5923 case Intrinsic::amdgcn_rsq: {
5924 KnownFPClass KnownSrc;
5925 // The only negative value that can be returned is -inf for -0 inputs.
5927
5928 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5929 KnownSrc, Q, Depth + 1);
5930
5931 // Negative -> nan
5932 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5933 Known.knownNot(fcNan);
5934 else if (KnownSrc.isKnownNever(fcSNan))
5935 Known.knownNot(fcSNan);
5936
5937 // +inf -> +0
5938 if (KnownSrc.isKnownNeverPosInfinity())
5939 Known.knownNot(fcPosZero);
5940
5941 Type *EltTy = II->getType()->getScalarType();
5942
5943 // f32 denormal always flushed.
5944 if (EltTy->isFloatTy())
5945 Known.knownNot(fcPosSubnormal);
5946
5947 if (const Function *F = II->getFunction()) {
5948 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5949
5950 // -0 -> -inf
5951 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5952 Known.knownNot(fcNegInf);
5953
5954 // +0 -> +inf
5955 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5956 Known.knownNot(fcPosInf);
5957 }
5958
5959 break;
5960 }
5961 case Intrinsic::amdgcn_trig_preop: {
5962 // Always returns a value [0, 1)
5963 Known.knownNot(fcNan | fcInf | fcNegative);
5964 break;
5965 }
5966 case Intrinsic::convert_from_arbitrary_fp: {
5967 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5968 StringRef FormatStr = cast<MDString>(MD)->getString();
5969
5970 const fltSemantics *SrcSemantics =
5972 if (!SrcSemantics)
5973 break;
5974
5975 const fltSemantics DstSemantics =
5976 II->getType()->getScalarType()->getFltSemantics();
5977
5978 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5979 Known.knownNot(fcNan);
5980
5981 // fcInf can only be cleared if the source format has no Inf encoding
5982 // and the dst max exp can accommodate src max exp.
5983 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5984 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5985 APFloat::semanticsMaxExponent(DstSemantics))
5986 Known.knownNot(fcInf);
5987
5988 // Check and clear all neg flags for formats that do not have signed
5989 // representation.
5990 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5991 Known.knownNot(fcNegative);
5992
5993 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5994 // zero.
5995 if (!APFloat::semanticsHasZero(*SrcSemantics))
5996 Known.knownNot(fcZero);
5997 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5998 Known.knownNot(fcNegZero);
5999
6000 // If src lands normally in dest, the result can never be subnormal.
6001 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6002 Known.knownNot(fcSubnormal);
6003 break;
6004 }
6005 default:
6006 break;
6007 }
6008
6009 break;
6010 }
6011 case Instruction::FAdd:
6012 case Instruction::FSub: {
6013 KnownFPClass KnownLHS, KnownRHS;
6014 bool WantNegative =
6015 Op->getOpcode() == Instruction::FAdd &&
6016 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
6017 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6018 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
6019
6020 if (!WantNaN && !WantNegative && !WantNegZero)
6021 break;
6022
6023 FPClassTest InterestedSrcs = InterestedClasses;
6024 if (WantNegative)
6025 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
6026 if (InterestedClasses & fcNan)
6027 InterestedSrcs |= fcInf;
6028 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
6029 KnownRHS, Q, Depth + 1);
6030
6031 // Special case fadd x, x, which is the canonical form of fmul x, 2.
6032 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
6033 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
6034 Depth + 1);
6035 if (Self)
6036 KnownLHS = KnownRHS;
6037
6038 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
6039 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
6040 WantNegZero || Opc == Instruction::FSub) {
6041
6042 // FIXME: Context function should always be passed in separately
6043 const Function *F = cast<Instruction>(Op)->getFunction();
6044 const fltSemantics &FltSem =
6045 Op->getType()->getScalarType()->getFltSemantics();
6047 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6048
6049 if (Self && Opc == Instruction::FAdd) {
6050 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6051 } else {
6052 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6053 // there's no point.
6054
6055 if (!Self) {
6056 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6057 KnownLHS, Q, Depth + 1);
6058 }
6059
6060 Known = Opc == Instruction::FAdd
6061 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6062 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6063 }
6064 }
6065
6066 break;
6067 }
6068 case Instruction::FMul: {
6069 const Function *F = cast<Instruction>(Op)->getFunction();
6071 F ? F->getDenormalMode(
6072 Op->getType()->getScalarType()->getFltSemantics())
6074
6075 Value *LHS = Op->getOperand(0);
6076 Value *RHS = Op->getOperand(1);
6077 // X * X is always non-negative or a NaN.
6078 // FIXME: Should check isGuaranteedNotToBeUndef
6079 if (LHS == RHS) {
6080 KnownFPClass KnownSrc;
6081 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6082 Depth + 1);
6083 Known = KnownFPClass::square(KnownSrc, Mode);
6084 break;
6085 }
6086
6087 KnownFPClass KnownLHS, KnownRHS;
6088
6089 const APFloat *CRHS;
6090 if (match(RHS, m_APFloat(CRHS))) {
6091 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6092 Depth + 1);
6093 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6094 } else {
6095 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6096 Depth + 1);
6097 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6098 // additional not-nan if the addend is known-not negative infinity if the
6099 // multiply is known-not infinity.
6100
6101 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6102 Depth + 1);
6103 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6104 }
6105
6106 /// Propgate no-infs if the other source is known smaller than one, such
6107 /// that this cannot introduce overflow.
6108 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6109 Known.knownNot(fcInf);
6110 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6111 Known.knownNot(fcInf);
6112
6113 break;
6114 }
6115 case Instruction::FDiv: {
6116 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6117
6118 const Function *F = cast<Instruction>(Op)->getFunction();
6119 const fltSemantics &FltSem =
6120 Op->getType()->getScalarType()->getFltSemantics();
6122 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6123
6124 if (Op->getOperand(0) == Op->getOperand(1) &&
6125 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6126 // X / X is always exactly 1.0 or a NaN.
6127 Known.setKnownFPClasses(fcNan | fcPosNormal);
6128
6129 if (!WantNan)
6130 break;
6131
6132 KnownFPClass KnownSrc;
6133 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6134 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6135 Depth + 1);
6136
6137 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6138 break;
6139 }
6140
6141 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6142 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6143 if (!WantNan && !WantNegative && !WantPositive)
6144 break;
6145
6146 KnownFPClass KnownLHS, KnownRHS;
6147 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6148 Q, Depth + 1);
6149
6150 bool KnowSomethingUseful =
6151 KnownRHS.isKnownNeverNaN() ||
6154
6155 if (KnowSomethingUseful)
6156 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6157 Q, Depth + 1);
6158
6159 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6160 break;
6161 }
6162 case Instruction::FRem: {
6163 FPClassTest InterestedLHS = fcNone;
6164 FPClassTest InterestedRHS = fcNone;
6165
6166 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
6167 if (InterestedClasses & fcNan) {
6168 InterestedLHS |= fcNan | fcInf;
6169 InterestedRHS |= fcNan | fcZero | fcSubnormal;
6170 }
6171
6172 // The sign for frem is the same as the first operand.
6173 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
6174 InterestedLHS |= fcPosNormal | fcPosSubnormal;
6175 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
6176 InterestedLHS |= fcNegNormal | fcNegSubnormal;
6177
6178 // A negative zero result requires a negative finite first operand.
6179 if (InterestedClasses & fcNegZero)
6180 InterestedLHS |= fcNegFinite;
6181
6182 // A positive zero result can additionally come from a negative finite
6183 // result being flushed to positive zero.
6184 if (InterestedClasses & fcPosZero)
6185 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
6186
6187 const Function *F = cast<Instruction>(Op)->getFunction();
6189 F ? F->getDenormalMode(
6190 Op->getType()->getScalarType()->getFltSemantics())
6192
6193 if (Op->getOperand(0) == Op->getOperand(1) &&
6194 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6195 // X % X is always exactly [+-]0.0 or a NaN.
6196 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
6197 KnownFPClass KnownSrc;
6198 if (InterestedSrcs != fcNone)
6199 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6200 KnownSrc, Q, Depth + 1);
6201 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6202 break;
6203 }
6204
6205 KnownFPClass KnownLHS;
6206 if (InterestedLHS != fcNone)
6207 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedLHS,
6208 KnownLHS, Q, Depth + 1);
6209
6210 KnownFPClass KnownRHS;
6211 // RHS is only useful for refining NaN classes.
6212 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
6213 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
6214 KnownRHS, Q, Depth + 1);
6215
6216 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6217
6218 break;
6219 }
6220 case Instruction::FPExt: {
6221 KnownFPClass KnownSrc;
6222 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6223 KnownSrc, Q, Depth + 1);
6224
6225 const fltSemantics &DstTy =
6226 Op->getType()->getScalarType()->getFltSemantics();
6227 const fltSemantics &SrcTy =
6228 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6229
6230 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6231 break;
6232 }
6233 case Instruction::FPTrunc: {
6234 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6235 Depth);
6236 break;
6237 }
6238 case Instruction::SIToFP:
6239 case Instruction::UIToFP: {
6240 // Cannot produce nan
6241 Known.knownNot(fcNan);
6242
6243 // Integers cannot be subnormal
6244 Known.knownNot(fcSubnormal);
6245
6246 // sitofp and uitofp turn into +0.0 for zero.
6247 Known.knownNot(fcNegZero);
6248
6249 // UIToFP is always non-negative regardless of known bits.
6250 if (Op->getOpcode() == Instruction::UIToFP)
6251 Known.signBitMustBeZero();
6252
6253 // Only compute known bits if we can learn something useful from them.
6254 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6255 break;
6256
6257 KnownBits IntKnown =
6258 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6259
6260 // If the integer is non-zero, the result cannot be +0.0
6261 if (IntKnown.isNonZero())
6262 Known.knownNot(fcPosZero);
6263
6264 if (Op->getOpcode() == Instruction::SIToFP) {
6265 // If the signed integer is known non-negative, the result is
6266 // non-negative. If the signed integer is known negative, the result is
6267 // negative.
6268 if (IntKnown.isNonNegative()) {
6269 Known.signBitMustBeZero();
6270 } else if (IntKnown.isNegative()) {
6271 Known.signBitMustBeOne();
6272 }
6273 }
6274
6275 // Guard kept for ilogb()
6276 if (InterestedClasses & fcInf) {
6277 // Get width of largest magnitude integer known.
6278 // This still works for a signed minimum value because the largest FP
6279 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6280 int IntSize = IntKnown.getBitWidth();
6281 if (Op->getOpcode() == Instruction::UIToFP)
6282 IntSize -= IntKnown.countMinLeadingZeros();
6283 else if (Op->getOpcode() == Instruction::SIToFP)
6284 IntSize -= IntKnown.countMinSignBits();
6285
6286 // If the exponent of the largest finite FP value can hold the largest
6287 // integer, the result of the cast must be finite.
6288 Type *FPTy = Op->getType()->getScalarType();
6289 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6290 Known.knownNot(fcInf);
6291 }
6292
6293 break;
6294 }
6295 case Instruction::ExtractElement: {
6296 // Look through extract element. If the index is non-constant or
6297 // out-of-range demand all elements, otherwise just the extracted element.
6298 const Value *Vec = Op->getOperand(0);
6299
6300 APInt DemandedVecElts;
6301 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6302 unsigned NumElts = VecTy->getNumElements();
6303 DemandedVecElts = APInt::getAllOnes(NumElts);
6304 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6305 if (CIdx && CIdx->getValue().ult(NumElts))
6306 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6307 } else {
6308 DemandedVecElts = APInt(1, 1);
6309 }
6310
6311 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6312 Q, Depth + 1);
6313 }
6314 case Instruction::InsertElement: {
6315 if (isa<ScalableVectorType>(Op->getType()))
6316 return;
6317
6318 const Value *Vec = Op->getOperand(0);
6319 const Value *Elt = Op->getOperand(1);
6320 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6321 unsigned NumElts = DemandedElts.getBitWidth();
6322 APInt DemandedVecElts = DemandedElts;
6323 bool NeedsElt = true;
6324 // If we know the index we are inserting to, clear it from Vec check.
6325 if (CIdx && CIdx->getValue().ult(NumElts)) {
6326 DemandedVecElts.clearBit(CIdx->getZExtValue());
6327 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6328 }
6329
6330 // Do we demand the inserted element?
6331 if (NeedsElt) {
6332 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6333 // If we don't know any bits, early out.
6334 if (Known.isUnknown())
6335 break;
6336 } else {
6337 Known.setKnownFPClasses(fcNone);
6338 }
6339
6340 // Do we need anymore elements from Vec?
6341 if (!DemandedVecElts.isZero()) {
6342 KnownFPClass Known2;
6343 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6344 Depth + 1);
6345 Known |= Known2;
6346 }
6347
6348 break;
6349 }
6350 case Instruction::ShuffleVector: {
6351 // Handle vector splat idiom
6352 if (Value *Splat = getSplatValue(V)) {
6353 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6354 break;
6355 }
6356
6357 // For undef elements, we don't know anything about the common state of
6358 // the shuffle result.
6359 APInt DemandedLHS, DemandedRHS;
6360 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6361 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6362 return;
6363
6364 if (!!DemandedLHS) {
6365 const Value *LHS = Shuf->getOperand(0);
6366 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6367 Depth + 1);
6368
6369 // If we don't know any bits, early out.
6370 if (Known.isUnknown())
6371 break;
6372 } else {
6373 Known.setKnownFPClasses(fcNone);
6374 }
6375
6376 if (!!DemandedRHS) {
6377 KnownFPClass Known2;
6378 const Value *RHS = Shuf->getOperand(1);
6379 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6380 Depth + 1);
6381 Known |= Known2;
6382 }
6383
6384 break;
6385 }
6386 case Instruction::ExtractValue: {
6387 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6388 ArrayRef<unsigned> Indices = Extract->getIndices();
6389 const Value *Src = Extract->getAggregateOperand();
6390 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6391 Indices[0] == 0) {
6392 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6393 switch (II->getIntrinsicID()) {
6394 case Intrinsic::frexp: {
6395 FPClassTest InterestedSrcs = InterestedClasses;
6396
6397 // Positive subnormals and negative subnormals could become positive
6398 // zero.
6399 if (InterestedClasses & fcPosZero)
6400 InterestedSrcs |= fcSubnormal;
6401
6402 // Negative subnormals could become negative zero.
6403 if (InterestedClasses & fcNegZero)
6404 InterestedSrcs |= fcNegSubnormal;
6405
6406 if (InterestedClasses & fcPosNormal)
6407 InterestedSrcs |= fcPosSubnormal;
6408
6409 if (InterestedClasses & fcNegNormal)
6410 InterestedSrcs |= fcNegSubnormal;
6411
6412 KnownFPClass KnownSrc;
6413 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6414 InterestedSrcs, KnownSrc, Q, Depth + 1);
6415
6416 const Function *F = cast<Instruction>(Op)->getFunction();
6417 const fltSemantics &FltSem =
6418 Op->getType()->getScalarType()->getFltSemantics();
6419
6421 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6422 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6423 return;
6424 }
6425 default:
6426 break;
6427 }
6428 }
6429 }
6430
6431 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6432 Depth + 1);
6433 break;
6434 }
6435 case Instruction::PHI: {
6436 const PHINode *P = cast<PHINode>(Op);
6437 // Unreachable blocks may have zero-operand PHI nodes.
6438 if (P->getNumIncomingValues() == 0)
6439 break;
6440
6441 // Otherwise take the unions of the known bit sets of the operands,
6442 // taking conservative care to avoid excessive recursion.
6443 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6444
6445 if (Depth < PhiRecursionLimit) {
6446 // Skip if every incoming value references to ourself.
6447 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6448 break;
6449
6450 bool First = true;
6451
6452 for (const Use &U : P->operands()) {
6453 Value *IncValue;
6454 Instruction *CtxI;
6455 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6456 // Skip direct self references.
6457 if (IncValue == P)
6458 continue;
6459
6460 KnownFPClass KnownSrc;
6461 // Recurse, but cap the recursion to two levels, because we don't want
6462 // to waste time spinning around in loops. We need at least depth 2 to
6463 // detect known sign bits.
6464 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6466 PhiRecursionLimit);
6467
6468 if (First) {
6469 Known = KnownSrc;
6470 First = false;
6471 } else {
6472 Known |= KnownSrc;
6473 }
6474
6475 if (Known.getKnownFPClasses() == fcAllFlags)
6476 break;
6477 }
6478 }
6479
6480 // Look for the case of a for loop which has a positive
6481 // initial value and is incremented by a squared value.
6482 // This will propagate sign information out of such loops.
6483 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6484 break;
6485 for (unsigned I = 0; I < 2; I++) {
6486 Value *RecurValue = P->getIncomingValue(1 - I);
6488 if (!II)
6489 continue;
6490 Value *R, *L, *Init;
6491 PHINode *PN;
6493 PN == P) {
6494 switch (II->getIntrinsicID()) {
6495 case Intrinsic::fma:
6496 case Intrinsic::fmuladd: {
6497 KnownFPClass KnownStart;
6498 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6499 Q, Depth + 1);
6500 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6501 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6503 break;
6504 }
6505 }
6506 }
6507 }
6508 break;
6509 }
6510 case Instruction::BitCast: {
6511 const Value *Src;
6512 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6513 !Src->getType()->isIntOrIntVectorTy())
6514 break;
6515
6516 const Type *Ty = Op->getType();
6517
6518 Value *CastLHS, *CastRHS;
6519
6520 // Match bitcast(umax(bitcast(a), bitcast(b)))
6521 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6522 m_BitCast(m_Value(CastRHS)))) &&
6523 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6524 KnownFPClass KnownLHS, KnownRHS;
6525 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6526 Depth + 1);
6527 if (!KnownRHS.isUnknown()) {
6528 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6529 Q, Depth + 1);
6530 Known = KnownLHS | KnownRHS;
6531 }
6532
6533 return;
6534 }
6535
6536 const Type *EltTy = Ty->getScalarType();
6537 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6538 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6539
6541 break;
6542 }
6543 default:
6544 break;
6545 }
6546}
6547
6549 const APInt &DemandedElts,
6550 FPClassTest InterestedClasses,
6551 const SimplifyQuery &SQ,
6552 unsigned Depth) {
6553 KnownFPClass KnownClasses;
6554 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6555 Depth);
6556 return KnownClasses;
6557}
6558
6560 FPClassTest InterestedClasses,
6561 const SimplifyQuery &SQ,
6562 unsigned Depth) {
6564 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6565 return Known;
6566}
6567
6569 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6570 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6571 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6572 return computeKnownFPClass(V, InterestedClasses,
6573 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6574 Depth);
6575}
6576
6578llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6579 FastMathFlags FMF, FPClassTest InterestedClasses,
6580 const SimplifyQuery &SQ, unsigned Depth) {
6581 if (FMF.noNaNs())
6582 InterestedClasses &= ~fcNan;
6583 if (FMF.noInfs())
6584 InterestedClasses &= ~fcInf;
6585
6586 KnownFPClass Result =
6587 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6588
6589 if (FMF.noNaNs())
6590 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6591 if (FMF.noInfs())
6592 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6593 return Result;
6594}
6595
6597 FPClassTest InterestedClasses,
6598 const SimplifyQuery &SQ,
6599 unsigned Depth) {
6600 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6601 APInt DemandedElts =
6602 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6603 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6604 Depth);
6605}
6606
6608 unsigned Depth) {
6610 return Known.isKnownNeverNegZero();
6611}
6612
6614 unsigned Depth) {
6617 return Known.cannotBeOrderedLessThanZero();
6618}
6619
6621 unsigned Depth) {
6623 return Known.isKnownNeverInfinity();
6624}
6625
6626/// Return true if the floating-point value can never contain a NaN or infinity.
6628 unsigned Depth) {
6630 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6631}
6632
6633/// Return true if the floating-point scalar value is not a NaN or if the
6634/// floating-point vector value has no NaN elements. Return false if a value
6635/// could ever be NaN.
6637 unsigned Depth) {
6639 return Known.isKnownNeverNaN();
6640}
6641
6642/// Return false if we can prove that the specified FP value's sign bit is 0.
6643/// Return true if we can prove that the specified FP value's sign bit is 1.
6644/// Otherwise return std::nullopt.
6645std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6646 const SimplifyQuery &SQ,
6647 unsigned Depth) {
6649 return Known.getSignBit();
6650}
6651
6653 auto *User = cast<Instruction>(U.getUser());
6654 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6655 if (FPOp->hasNoSignedZeros())
6656 return true;
6657 }
6658
6659 switch (User->getOpcode()) {
6660 case Instruction::FPToSI:
6661 case Instruction::FPToUI:
6662 return true;
6663 case Instruction::FCmp:
6664 // fcmp treats both positive and negative zero as equal.
6665 return true;
6666 case Instruction::Call:
6667 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6668 switch (II->getIntrinsicID()) {
6669 case Intrinsic::fabs:
6670 return true;
6671 case Intrinsic::copysign:
6672 return U.getOperandNo() == 0;
6673 case Intrinsic::is_fpclass: {
6674 auto Test =
6675 static_cast<FPClassTest>(
6676 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6679 }
6680 default:
6681 return false;
6682 }
6683 }
6684 return false;
6685 default:
6686 return false;
6687 }
6688}
6689
6691 auto *User = cast<Instruction>(U.getUser());
6692 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6693 if (FPOp->hasNoNaNs())
6694 return true;
6695 }
6696
6697 switch (User->getOpcode()) {
6698 case Instruction::FPToSI:
6699 case Instruction::FPToUI:
6700 return true;
6701 // Proper FP math operations ignore the sign bit of NaN.
6702 case Instruction::FAdd:
6703 case Instruction::FSub:
6704 case Instruction::FMul:
6705 case Instruction::FDiv:
6706 case Instruction::FRem:
6707 case Instruction::FPTrunc:
6708 case Instruction::FPExt:
6709 case Instruction::FCmp:
6710 return true;
6711 // Bitwise FP operations should preserve the sign bit of NaN.
6712 case Instruction::FNeg:
6713 case Instruction::Select:
6714 case Instruction::PHI:
6715 return false;
6716 case Instruction::Ret:
6717 return User->getFunction()->getAttributes().getRetNoFPClass() &
6719 case Instruction::Call:
6720 case Instruction::Invoke: {
6721 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6722 switch (II->getIntrinsicID()) {
6723 case Intrinsic::fabs:
6724 return true;
6725 case Intrinsic::copysign:
6726 return U.getOperandNo() == 0;
6727 // Other proper FP math intrinsics ignore the sign bit of NaN.
6728 case Intrinsic::maxnum:
6729 case Intrinsic::minnum:
6730 case Intrinsic::maximum:
6731 case Intrinsic::minimum:
6732 case Intrinsic::maximumnum:
6733 case Intrinsic::minimumnum:
6734 case Intrinsic::canonicalize:
6735 case Intrinsic::fma:
6736 case Intrinsic::fmuladd:
6737 case Intrinsic::sqrt:
6738 case Intrinsic::pow:
6739 case Intrinsic::powi:
6740 case Intrinsic::fptoui_sat:
6741 case Intrinsic::fptosi_sat:
6742 case Intrinsic::is_fpclass:
6743 return true;
6744 default:
6745 return false;
6746 }
6747 }
6748
6749 FPClassTest NoFPClass =
6750 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6751 return NoFPClass & FPClassTest::fcNan;
6752 }
6753 default:
6754 return false;
6755 }
6756}
6757
6759 FastMathFlags FMF) {
6760 if (isa<PoisonValue>(V))
6761 return true;
6762 if (isa<UndefValue>(V))
6763 return false;
6764
6765 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6766 return true;
6767
6769 if (!I)
6770 return false;
6771
6772 switch (I->getOpcode()) {
6773 case Instruction::SIToFP:
6774 case Instruction::UIToFP:
6775 // TODO: Could check nofpclass(inf) on incoming argument
6776 if (FMF.noInfs())
6777 return true;
6778
6779 // Need to check int size cannot produce infinity, which computeKnownFPClass
6780 // knows how to do already.
6781 return isKnownNeverInfinity(I, SQ);
6782 case Instruction::Call: {
6783 const CallInst *CI = cast<CallInst>(I);
6784 switch (CI->getIntrinsicID()) {
6785 case Intrinsic::trunc:
6786 case Intrinsic::floor:
6787 case Intrinsic::ceil:
6788 case Intrinsic::rint:
6789 case Intrinsic::nearbyint:
6790 case Intrinsic::round:
6791 case Intrinsic::roundeven:
6792 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6793 default:
6794 break;
6795 }
6796
6797 break;
6798 }
6799 default:
6800 break;
6801 }
6802
6803 return false;
6804}
6805
6807
6808 // All byte-wide stores are splatable, even of arbitrary variables.
6809 if (V->getType()->isIntegerTy(8))
6810 return V;
6811
6812 LLVMContext &Ctx = V->getContext();
6813
6814 // Undef don't care.
6815 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6816 if (isa<UndefValue>(V))
6817 return UndefInt8;
6818
6819 // Return poison for zero-sized type.
6820 if (DL.getTypeStoreSize(V->getType()).isZero())
6821 return PoisonValue::get(Type::getInt8Ty(Ctx));
6822
6824 if (!C) {
6825 // Conceptually, we could handle things like:
6826 // %a = zext i8 %X to i16
6827 // %b = shl i16 %a, 8
6828 // %c = or i16 %a, %b
6829 // but until there is an example that actually needs this, it doesn't seem
6830 // worth worrying about.
6831 return nullptr;
6832 }
6833
6834 // Handle 'null' ConstantArrayZero etc.
6835 if (C->isNullValue())
6837
6838 // Constant floating-point values can be handled as integer values if the
6839 // corresponding integer value is "byteable". An important case is 0.0.
6840 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6841 Type *ScalarTy = CFP->getType()->getScalarType();
6842 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6843 return isBytewiseValue(
6844 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6845
6846 // Don't handle long double formats, which have strange constraints.
6847 return nullptr;
6848 }
6849
6850 // We can handle constant integers that are multiple of 8 bits.
6851 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6852 if (CI->getBitWidth() % 8 == 0) {
6853 if (!CI->getValue().isSplat(8))
6854 return nullptr;
6855 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6856 }
6857 }
6858
6859 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6860 if (CE->getOpcode() == Instruction::IntToPtr) {
6861 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6862 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6864 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6865 return isBytewiseValue(Op, DL);
6866 }
6867 }
6868 }
6869
6870 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6871 if (LHS == RHS)
6872 return LHS;
6873 if (!LHS || !RHS)
6874 return nullptr;
6875 if (LHS == UndefInt8)
6876 return RHS;
6877 if (RHS == UndefInt8)
6878 return LHS;
6879 return nullptr;
6880 };
6881
6883 Value *Val = UndefInt8;
6884 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6885 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6886 return nullptr;
6887 return Val;
6888 }
6889
6891 Value *Val = UndefInt8;
6892 for (Value *Op : C->operands())
6893 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6894 return nullptr;
6895 return Val;
6896 }
6897
6898 // Don't try to handle the handful of other constants.
6899 return nullptr;
6900}
6901
6902// This is the recursive version of BuildSubAggregate. It takes a few different
6903// arguments. Idxs is the index within the nested struct From that we are
6904// looking at now (which is of type IndexedType). IdxSkip is the number of
6905// indices from Idxs that should be left out when inserting into the resulting
6906// struct. To is the result struct built so far, new insertvalue instructions
6907// build on that.
6908static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6910 unsigned IdxSkip,
6911 BasicBlock::iterator InsertBefore) {
6912 StructType *STy = dyn_cast<StructType>(IndexedType);
6913 if (STy) {
6914 // Save the original To argument so we can modify it
6915 Value *OrigTo = To;
6916 // General case, the type indexed by Idxs is a struct
6917 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6918 // Process each struct element recursively
6919 Idxs.push_back(i);
6920 Value *PrevTo = To;
6921 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6922 InsertBefore);
6923 Idxs.pop_back();
6924 if (!To) {
6925 // Couldn't find any inserted value for this index? Cleanup
6926 while (PrevTo != OrigTo) {
6928 PrevTo = Del->getAggregateOperand();
6929 Del->eraseFromParent();
6930 }
6931 // Stop processing elements
6932 break;
6933 }
6934 }
6935 // If we successfully found a value for each of our subaggregates
6936 if (To)
6937 return To;
6938 }
6939 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6940 // the struct's elements had a value that was inserted directly. In the latter
6941 // case, perhaps we can't determine each of the subelements individually, but
6942 // we might be able to find the complete struct somewhere.
6943
6944 // Find the value that is at that particular spot
6945 Value *V = FindInsertedValue(From, Idxs);
6946
6947 if (!V)
6948 return nullptr;
6949
6950 // Insert the value in the new (sub) aggregate
6951 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6952 InsertBefore);
6953}
6954
6955// This helper takes a nested struct and extracts a part of it (which is again a
6956// struct) into a new value. For example, given the struct:
6957// { a, { b, { c, d }, e } }
6958// and the indices "1, 1" this returns
6959// { c, d }.
6960//
6961// It does this by inserting an insertvalue for each element in the resulting
6962// struct, as opposed to just inserting a single struct. This will only work if
6963// each of the elements of the substruct are known (ie, inserted into From by an
6964// insertvalue instruction somewhere).
6965//
6966// All inserted insertvalue instructions are inserted before InsertBefore
6968 BasicBlock::iterator InsertBefore) {
6969 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6970 idx_range);
6971 Value *To = PoisonValue::get(IndexedType);
6972 SmallVector<unsigned, 10> Idxs(idx_range);
6973 unsigned IdxSkip = Idxs.size();
6974
6975 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6976}
6977
6978/// Given an aggregate and a sequence of indices, see if the scalar value
6979/// indexed is already around as a register, for example if it was inserted
6980/// directly into the aggregate.
6981///
6982/// If InsertBefore is not null, this function will duplicate (modified)
6983/// insertvalues when a part of a nested struct is extracted.
6984Value *
6986 std::optional<BasicBlock::iterator> InsertBefore) {
6987 // Nothing to index? Just return V then (this is useful at the end of our
6988 // recursion).
6989 if (idx_range.empty())
6990 return V;
6991 // We have indices, so V should have an indexable type.
6992 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6993 "Not looking at a struct or array?");
6994 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6995 "Invalid indices for type?");
6996
6997 if (Constant *C = dyn_cast<Constant>(V)) {
6998 C = C->getAggregateElement(idx_range[0]);
6999 if (!C) return nullptr;
7000 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
7001 }
7002
7004 // Loop the indices for the insertvalue instruction in parallel with the
7005 // requested indices
7006 const unsigned *req_idx = idx_range.begin();
7007 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7008 i != e; ++i, ++req_idx) {
7009 if (req_idx == idx_range.end()) {
7010 // We can't handle this without inserting insertvalues
7011 if (!InsertBefore)
7012 return nullptr;
7013
7014 // The requested index identifies a part of a nested aggregate. Handle
7015 // this specially. For example,
7016 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7017 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7018 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7019 // This can be changed into
7020 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7021 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7022 // which allows the unused 0,0 element from the nested struct to be
7023 // removed.
7024 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7025 *InsertBefore);
7026 }
7027
7028 // This insert value inserts something else than what we are looking for.
7029 // See if the (aggregate) value inserted into has the value we are
7030 // looking for, then.
7031 if (*req_idx != *i)
7032 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7033 InsertBefore);
7034 }
7035 // If we end up here, the indices of the insertvalue match with those
7036 // requested (though possibly only partially). Now we recursively look at
7037 // the inserted value, passing any remaining indices.
7038 return FindInsertedValue(I->getInsertedValueOperand(),
7039 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7040 }
7041
7043 // If we're extracting a value from an aggregate that was extracted from
7044 // something else, we can extract from that something else directly instead.
7045 // However, we will need to chain I's indices with the requested indices.
7046
7047 // Calculate the number of indices required
7048 unsigned size = I->getNumIndices() + idx_range.size();
7049 // Allocate some space to put the new indices in
7051 Idxs.reserve(size);
7052 // Add indices from the extract value instruction
7053 Idxs.append(I->idx_begin(), I->idx_end());
7054
7055 // Add requested indices
7056 Idxs.append(idx_range.begin(), idx_range.end());
7057
7058 assert(Idxs.size() == size
7059 && "Number of indices added not correct?");
7060
7061 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7062 }
7063 // Otherwise, we don't know (such as, extracting from a function return value
7064 // or load instruction)
7065 return nullptr;
7066}
7067
7068// If V refers to an initialized global constant, set Slice either to
7069// its initializer if the size of its elements equals ElementSize, or,
7070// for ElementSize == 8, to its representation as an array of unsiged
7071// char. Return true on success.
7072// Offset is in the unit "nr of ElementSize sized elements".
7075 unsigned ElementSize, uint64_t Offset) {
7076 assert(V && "V should not be null.");
7077 assert((ElementSize % 8) == 0 &&
7078 "ElementSize expected to be a multiple of the size of a byte.");
7079 unsigned ElementSizeInBytes = ElementSize / 8;
7080
7081 // Drill down into the pointer expression V, ignoring any intervening
7082 // casts, and determine the identity of the object it references along
7083 // with the cumulative byte offset into it.
7084 const GlobalVariable *GV =
7086 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7087 // Fail if V is not based on constant global object.
7088 return false;
7089
7090 const DataLayout &DL = GV->getDataLayout();
7091 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7092
7094 /*AllowNonInbounds*/ true))
7095 // Fail if a constant offset could not be determined.
7096 return false;
7097
7098 uint64_t StartIdx = Off.getLimitedValue();
7099 if (StartIdx == UINT64_MAX)
7100 // Fail if the constant offset is excessive.
7101 return false;
7102
7103 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7104 // elements. Simply bail out if that isn't possible.
7105 if ((StartIdx % ElementSizeInBytes) != 0)
7106 return false;
7107
7108 Offset += StartIdx / ElementSizeInBytes;
7109 ConstantDataArray *Array = nullptr;
7110 ArrayType *ArrayTy = nullptr;
7111
7112 if (GV->getInitializer()->isNullValue()) {
7113 Type *GVTy = GV->getValueType();
7114 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7115 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7116
7117 Slice.Array = nullptr;
7118 Slice.Offset = 0;
7119 // Return an empty Slice for undersized constants to let callers
7120 // transform even undefined library calls into simpler, well-defined
7121 // expressions. This is preferable to making the calls although it
7122 // prevents sanitizers from detecting such calls.
7123 Slice.Length = Length < Offset ? 0 : Length - Offset;
7124 return true;
7125 }
7126
7127 auto *Init = const_cast<Constant *>(GV->getInitializer());
7128 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7129 Type *InitElTy = ArrayInit->getElementType();
7130 if (InitElTy->isIntegerTy(ElementSize)) {
7131 // If Init is an initializer for an array of the expected type
7132 // and size, use it as is.
7133 Array = ArrayInit;
7134 ArrayTy = ArrayInit->getType();
7135 }
7136 }
7137
7138 if (!Array) {
7139 if (ElementSize != 8)
7140 // TODO: Handle conversions to larger integral types.
7141 return false;
7142
7143 // Otherwise extract the portion of the initializer starting
7144 // at Offset as an array of bytes, and reset Offset.
7146 if (!Init)
7147 return false;
7148
7149 Offset = 0;
7151 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7152 }
7153
7154 uint64_t NumElts = ArrayTy->getArrayNumElements();
7155 if (Offset > NumElts)
7156 return false;
7157
7158 Slice.Array = Array;
7159 Slice.Offset = Offset;
7160 Slice.Length = NumElts - Offset;
7161 return true;
7162}
7163
7164/// Extract bytes from the initializer of the constant array V, which need
7165/// not be a nul-terminated string. On success, store the bytes in Str and
7166/// return true. When TrimAtNul is set, Str will contain only the bytes up
7167/// to but not including the first nul. Return false on failure.
7169 bool TrimAtNul) {
7171 if (!getConstantDataArrayInfo(V, Slice, 8))
7172 return false;
7173
7174 if (Slice.Array == nullptr) {
7175 if (TrimAtNul) {
7176 // Return a nul-terminated string even for an empty Slice. This is
7177 // safe because all existing SimplifyLibcalls callers require string
7178 // arguments and the behavior of the functions they fold is undefined
7179 // otherwise. Folding the calls this way is preferable to making
7180 // the undefined library calls, even though it prevents sanitizers
7181 // from reporting such calls.
7182 Str = StringRef();
7183 return true;
7184 }
7185 if (Slice.Length == 1) {
7186 Str = StringRef("", 1);
7187 return true;
7188 }
7189 // We cannot instantiate a StringRef as we do not have an appropriate string
7190 // of 0s at hand.
7191 return false;
7192 }
7193
7194 // Start out with the entire array in the StringRef.
7195 Str = Slice.Array->getAsString();
7196 // Skip over 'offset' bytes.
7197 Str = Str.substr(Slice.Offset);
7198
7199 if (TrimAtNul) {
7200 // Trim off the \0 and anything after it. If the array is not nul
7201 // terminated, we just return the whole end of string. The client may know
7202 // some other way that the string is length-bound.
7203 Str = Str.substr(0, Str.find('\0'));
7204 }
7205 return true;
7206}
7207
7208// These next two are very similar to the above, but also look through PHI
7209// nodes.
7210// TODO: See if we can integrate these two together.
7211
7212/// If we can compute the length of the string pointed to by
7213/// the specified pointer, return 'len+1'. If we can't, return 0.
7216 unsigned CharSize) {
7217 // Look through noop bitcast instructions.
7218 V = V->stripPointerCasts();
7219
7220 // If this is a PHI node, there are two cases: either we have already seen it
7221 // or we haven't.
7222 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7223 if (!PHIs.insert(PN).second)
7224 return ~0ULL; // already in the set.
7225
7226 // If it was new, see if all the input strings are the same length.
7227 uint64_t LenSoFar = ~0ULL;
7228 for (Value *IncValue : PN->incoming_values()) {
7229 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7230 if (Len == 0) return 0; // Unknown length -> unknown.
7231
7232 if (Len == ~0ULL) continue;
7233
7234 if (Len != LenSoFar && LenSoFar != ~0ULL)
7235 return 0; // Disagree -> unknown.
7236 LenSoFar = Len;
7237 }
7238
7239 // Success, all agree.
7240 return LenSoFar;
7241 }
7242
7243 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7244 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7245 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7246 if (Len1 == 0) return 0;
7247 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7248 if (Len2 == 0) return 0;
7249 if (Len1 == ~0ULL) return Len2;
7250 if (Len2 == ~0ULL) return Len1;
7251 if (Len1 != Len2) return 0;
7252 return Len1;
7253 }
7254
7255 // Otherwise, see if we can read the string.
7257 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7258 return 0;
7259
7260 if (Slice.Array == nullptr)
7261 // Zeroinitializer (including an empty one).
7262 return 1;
7263
7264 // Search for the first nul character. Return a conservative result even
7265 // when there is no nul. This is safe since otherwise the string function
7266 // being folded such as strlen is undefined, and can be preferable to
7267 // making the undefined library call.
7268 unsigned NullIndex = 0;
7269 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7270 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7271 break;
7272 }
7273
7274 return NullIndex + 1;
7275}
7276
7277/// If we can compute the length of the string pointed to by
7278/// the specified pointer, return 'len+1'. If we can't, return 0.
7279uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7280 if (!V->getType()->isPointerTy())
7281 return 0;
7282
7284 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7285 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7286 // an empty string as a length.
7287 return Len == ~0ULL ? 1 : Len;
7288}
7289
7290const Value *
7292 bool MustPreserveOffset,
7293 bool MustPreserveProvenance) {
7294 assert(Call &&
7295 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7296 if (const Value *RV = Call->getReturnedArgOperand())
7297 return RV;
7298 // This can be used only as a aliasing property.
7300 Call, MustPreserveOffset, MustPreserveProvenance))
7301 return Call->getArgOperand(0);
7302 return nullptr;
7303}
7304
7306 const CallBase *Call, bool MustPreserveOffset,
7307 bool MustPreserveProvenance) {
7308 switch (Call->getIntrinsicID()) {
7309 case Intrinsic::launder_invariant_group:
7310 case Intrinsic::aarch64_irg:
7311 case Intrinsic::aarch64_tagp:
7312 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7313 // input pointer (and thus preserves the byte offset, which is the property
7314 // the MustPreserveOffset flag selects). However, it will not necessarily
7315 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7316 // descriptor", which has "all loads return 0, all stores are dropped"
7317 // semantics. Given the context of this intrinsic list, no one should be
7318 // relying on such a strict bit-exact null mapping (and, at time of
7319 // writing, they are not), but we document this fact out of an abundance
7320 // of caution.
7321 case Intrinsic::amdgcn_make_buffer_rsrc:
7322 return !MustPreserveProvenance;
7323 case Intrinsic::ptrmask:
7324 return !MustPreserveOffset;
7325 case Intrinsic::threadlocal_address:
7326 // The underlying variable changes with thread ID. The Thread ID may change
7327 // at coroutine suspend points.
7328 return !Call->getParent()->getParent()->isPresplitCoroutine();
7329 default:
7330 return false;
7331 }
7332}
7333
7334/// \p PN defines a loop-variant pointer to an object. Check if the
7335/// previous iteration of the loop was referring to the same object as \p PN.
7337 const LoopInfo *LI) {
7338 // Find the loop-defined value.
7339 Loop *L = LI->getLoopFor(PN->getParent());
7340 if (PN->getNumIncomingValues() != 2)
7341 return true;
7342
7343 // Find the value from previous iteration.
7344 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7345 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7346 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7347 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7348 return true;
7349
7350 // If a new pointer is loaded in the loop, the pointer references a different
7351 // object in every iteration. E.g.:
7352 // for (i)
7353 // int *p = a[i];
7354 // ...
7355 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7356 if (!L->isLoopInvariant(Load->getPointerOperand()))
7357 return false;
7358 return true;
7359}
7360
7361const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7362 bool MustPreserveProvenance) {
7363 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7364 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7365 const Value *PtrOp = GEP->getPointerOperand();
7366 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7367 return V;
7368 V = PtrOp;
7369 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7370 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7371 Value *NewV = cast<Operator>(V)->getOperand(0);
7372 if (!NewV->getType()->isPointerTy())
7373 return V;
7374 V = NewV;
7375 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7376 if (GA->isInterposable())
7377 return V;
7378 V = GA->getAliasee();
7379 } else {
7380 if (auto *PHI = dyn_cast<PHINode>(V)) {
7381 // Look through single-arg phi nodes created by LCSSA.
7382 if (PHI->getNumIncomingValues() == 1) {
7383 V = PHI->getIncomingValue(0);
7384 continue;
7385 }
7386 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7387 // CaptureTracking can know about special capturing properties of some
7388 // intrinsics like launder.invariant.group, that can't be expressed with
7389 // the attributes, but have properties like returning aliasing pointer.
7390 // Because some analysis may assume that nocaptured pointer is not
7391 // returned from some special intrinsic (because function would have to
7392 // be marked with returns attribute), it is crucial to use this function
7393 // because it should be in sync with CaptureTracking. Not using it may
7394 // cause weird miscompilations where 2 aliasing pointers are assumed to
7395 // noalias.
7397 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7398 V = RP;
7399 continue;
7400 }
7401 }
7402
7403 return V;
7404 }
7405 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7406 }
7407 return V;
7408}
7409
7412 const LoopInfo *LI, unsigned MaxLookup) {
7415 Worklist.push_back(V);
7416 do {
7417 const Value *P = Worklist.pop_back_val();
7418 P = getUnderlyingObject(P, MaxLookup);
7419
7420 if (!Visited.insert(P).second)
7421 continue;
7422
7423 if (auto *SI = dyn_cast<SelectInst>(P)) {
7424 Worklist.push_back(SI->getTrueValue());
7425 Worklist.push_back(SI->getFalseValue());
7426 continue;
7427 }
7428
7429 if (auto *PN = dyn_cast<PHINode>(P)) {
7430 // If this PHI changes the underlying object in every iteration of the
7431 // loop, don't look through it. Consider:
7432 // int **A;
7433 // for (i) {
7434 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7435 // Curr = A[i];
7436 // *Prev, *Curr;
7437 //
7438 // Prev is tracking Curr one iteration behind so they refer to different
7439 // underlying objects.
7440 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7442 append_range(Worklist, PN->incoming_values());
7443 else
7444 Objects.push_back(P);
7445 continue;
7446 }
7447
7448 Objects.push_back(P);
7449 } while (!Worklist.empty());
7450}
7451
7453 bool MustPreserveProvenance) {
7454 const unsigned MaxVisited = 8;
7455
7458 Worklist.push_back(V);
7459 const Value *Object = nullptr;
7460 // Used as fallback if we can't find a common underlying object through
7461 // recursion.
7462 bool First = true;
7463 const Value *FirstObject =
7464 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7465 do {
7466 const Value *P = Worklist.pop_back_val();
7467 P = First ? FirstObject
7469 MustPreserveProvenance);
7470 First = false;
7471
7472 if (!Visited.insert(P).second)
7473 continue;
7474
7475 if (Visited.size() == MaxVisited)
7476 return FirstObject;
7477
7478 if (auto *SI = dyn_cast<SelectInst>(P)) {
7479 Worklist.push_back(SI->getTrueValue());
7480 Worklist.push_back(SI->getFalseValue());
7481 continue;
7482 }
7483
7484 if (auto *PN = dyn_cast<PHINode>(P)) {
7485 append_range(Worklist, PN->incoming_values());
7486 continue;
7487 }
7488
7489 if (!Object)
7490 Object = P;
7491 else if (Object != P)
7492 return FirstObject;
7493 } while (!Worklist.empty());
7494
7495 return Object ? Object : FirstObject;
7496}
7497
7498/// This is the function that does the work of looking through basic
7499/// ptrtoint+arithmetic+inttoptr sequences.
7500static const Value *getUnderlyingObjectFromInt(const Value *V) {
7501 do {
7502 if (const Operator *U = dyn_cast<Operator>(V)) {
7503 // If we find a ptrtoint, we can transfer control back to the
7504 // regular getUnderlyingObjectFromInt.
7505 if (U->getOpcode() == Instruction::PtrToInt)
7506 return U->getOperand(0);
7507 // If we find an add of a constant, a multiplied value, or a phi, it's
7508 // likely that the other operand will lead us to the base
7509 // object. We don't have to worry about the case where the
7510 // object address is somehow being computed by the multiply,
7511 // because our callers only care when the result is an
7512 // identifiable object.
7513 if (U->getOpcode() != Instruction::Add ||
7514 (!isa<ConstantInt>(U->getOperand(1)) &&
7515 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7516 !isa<PHINode>(U->getOperand(1))))
7517 return V;
7518 V = U->getOperand(0);
7519 } else {
7520 return V;
7521 }
7522 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7523 } while (true);
7524}
7525
7526/// This is a wrapper around getUnderlyingObjects and adds support for basic
7527/// ptrtoint+arithmetic+inttoptr sequences.
7528/// It returns false if unidentified object is found in getUnderlyingObjects.
7530 SmallVectorImpl<Value *> &Objects) {
7532 SmallVector<const Value *, 4> Working(1, V);
7533 bool AllObjectsIdentified = true;
7534 do {
7535 V = Working.pop_back_val();
7536
7538 getUnderlyingObjects(V, Objs);
7539
7540 for (const Value *V : Objs) {
7541 if (!Visited.insert(V).second)
7542 continue;
7543 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7544 const Value *O =
7545 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7546 if (O->getType()->isPointerTy()) {
7547 Working.push_back(O);
7548 continue;
7549 }
7550 }
7551 AllObjectsIdentified &= isIdentifiedObject(V);
7552 Objects.push_back(const_cast<Value *>(V));
7553 }
7554 } while (!Working.empty());
7555 return AllObjectsIdentified;
7556}
7557
7559 AllocaInst *Result = nullptr;
7561 SmallVector<Value *, 4> Worklist;
7562
7563 auto AddWork = [&](Value *V) {
7564 if (Visited.insert(V).second)
7565 Worklist.push_back(V);
7566 };
7567
7568 AddWork(V);
7569 do {
7570 V = Worklist.pop_back_val();
7571 assert(Visited.count(V));
7572
7573 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7574 if (Result && Result != AI)
7575 return nullptr;
7576 Result = AI;
7577 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7578 AddWork(CI->getOperand(0));
7579 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7580 for (Value *IncValue : PN->incoming_values())
7581 AddWork(IncValue);
7582 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7583 AddWork(SI->getTrueValue());
7584 AddWork(SI->getFalseValue());
7586 if (OffsetZero && !GEP->hasAllZeroIndices())
7587 return nullptr;
7588 AddWork(GEP->getPointerOperand());
7589 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7590 Value *Returned = CB->getReturnedArgOperand();
7591 if (Returned)
7592 AddWork(Returned);
7593 else
7594 return nullptr;
7595 } else {
7596 return nullptr;
7597 }
7598 } while (!Worklist.empty());
7599
7600 return Result;
7601}
7602
7604 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7605 for (const User *U : V->users()) {
7607 if (!II)
7608 return false;
7609
7610 if (AllowLifetime && II->isLifetimeStartOrEnd())
7611 continue;
7612
7613 if (AllowDroppable && II->isDroppable())
7614 continue;
7615
7616 return false;
7617 }
7618 return true;
7619}
7620
7623 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7624}
7627 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7628}
7629
7631 if (auto *II = dyn_cast<IntrinsicInst>(I))
7632 return isTriviallyVectorizable(II->getIntrinsicID());
7633 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7634 return (!Shuffle || Shuffle->isSelect()) &&
7636}
7637
7639 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7640 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7641 bool IgnoreUBImplyingAttrs) {
7642 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7643 AC, DT, TLI, UseVariableInfo,
7644 IgnoreUBImplyingAttrs);
7645}
7646
7648 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7649 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7650 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7651#ifndef NDEBUG
7652 if (Inst->getOpcode() != Opcode) {
7653 // Check that the operands are actually compatible with the Opcode override.
7654 auto hasEqualReturnAndLeadingOperandTypes =
7655 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7656 if (Inst->getNumOperands() < NumLeadingOperands)
7657 return false;
7658 const Type *ExpectedType = Inst->getType();
7659 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7660 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7661 return false;
7662 return true;
7663 };
7665 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7666 assert(!Instruction::isUnaryOp(Opcode) ||
7667 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7668 }
7669#endif
7670
7671 switch (Opcode) {
7672 default:
7673 return true;
7674 case Instruction::UDiv:
7675 case Instruction::URem: {
7676 // x / y is undefined if y == 0.
7677 const APInt *V;
7678 if (match(Inst->getOperand(1), m_APInt(V)))
7679 return *V != 0;
7680 return false;
7681 }
7682 case Instruction::SDiv:
7683 case Instruction::SRem: {
7684 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7685 const APInt *Numerator, *Denominator;
7686 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7687 return false;
7688 // We cannot hoist this division if the denominator is 0.
7689 if (*Denominator == 0)
7690 return false;
7691 // It's safe to hoist if the denominator is not 0 or -1.
7692 if (!Denominator->isAllOnes())
7693 return true;
7694 // At this point we know that the denominator is -1. It is safe to hoist as
7695 // long we know that the numerator is not INT_MIN.
7696 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7697 return !Numerator->isMinSignedValue();
7698 // The numerator *might* be MinSignedValue.
7699 return false;
7700 }
7701 case Instruction::Load: {
7702 if (!UseVariableInfo)
7703 return false;
7704
7705 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7706 if (!LI)
7707 return false;
7708 if (mustSuppressSpeculation(*LI))
7709 return false;
7710 const DataLayout &DL = LI->getDataLayout();
7712 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7713 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7714 }
7715 case Instruction::Call: {
7716 auto *CI = dyn_cast<const CallInst>(Inst);
7717 if (!CI)
7718 return false;
7719 const Function *Callee = CI->getCalledFunction();
7720
7721 // The called function could have undefined behavior or side-effects, even
7722 // if marked readnone nounwind.
7723 if (!Callee || !Callee->isSpeculatable())
7724 return false;
7725 // Since the operands may be changed after hoisting, undefined behavior may
7726 // be triggered by some UB-implying attributes.
7727 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7728 }
7729 case Instruction::VAArg:
7730 case Instruction::Alloca:
7731 case Instruction::Invoke:
7732 case Instruction::CallBr:
7733 case Instruction::PHI:
7734 case Instruction::Store:
7735 case Instruction::Ret:
7736 case Instruction::UncondBr:
7737 case Instruction::CondBr:
7738 case Instruction::IndirectBr:
7739 case Instruction::Switch:
7740 case Instruction::Unreachable:
7741 case Instruction::Fence:
7742 case Instruction::AtomicRMW:
7743 case Instruction::AtomicCmpXchg:
7744 case Instruction::LandingPad:
7745 case Instruction::Resume:
7746 case Instruction::CatchSwitch:
7747 case Instruction::CatchPad:
7748 case Instruction::CatchRet:
7749 case Instruction::CleanupPad:
7750 case Instruction::CleanupRet:
7751 return false; // Misc instructions which have effects
7752 }
7753}
7754
7756 if (I.mayReadOrWriteMemory())
7757 // Memory dependency possible
7758 return true;
7760 // Can't move above a maythrow call or infinite loop. Or if an
7761 // inalloca alloca, above a stacksave call.
7762 return true;
7764 // 1) Can't reorder two inf-loop calls, even if readonly
7765 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7766 // safe to speculative execute. (Inverse of above)
7767 return true;
7768 return false;
7769}
7770
7771/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7785
7786/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7789 bool ForSigned,
7790 const SimplifyQuery &SQ) {
7791 ConstantRange CR1 =
7792 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7793 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7796 return CR1.intersectWith(CR2, RangeType);
7797}
7798
7800 const Value *RHS,
7801 const SimplifyQuery &SQ,
7802 bool IsNSW) {
7803 ConstantRange LHSRange =
7804 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7805 ConstantRange RHSRange =
7806 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7807
7808 // mul nsw of two non-negative numbers is also nuw.
7809 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7811
7812 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7813}
7814
7816 const Value *RHS,
7817 const SimplifyQuery &SQ) {
7818 // Multiplying n * m significant bits yields a result of n + m significant
7819 // bits. If the total number of significant bits does not exceed the
7820 // result bit width (minus 1), there is no overflow.
7821 // This means if we have enough leading sign bits in the operands
7822 // we can guarantee that the result does not overflow.
7823 // Ref: "Hacker's Delight" by Henry Warren
7824 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7825
7826 // Note that underestimating the number of sign bits gives a more
7827 // conservative answer.
7828 unsigned SignBits =
7829 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7830
7831 // First handle the easy case: if we have enough sign bits there's
7832 // definitely no overflow.
7833 if (SignBits > BitWidth + 1)
7835
7836 // There are two ambiguous cases where there can be no overflow:
7837 // SignBits == BitWidth + 1 and
7838 // SignBits == BitWidth
7839 // The second case is difficult to check, therefore we only handle the
7840 // first case.
7841 if (SignBits == BitWidth + 1) {
7842 // It overflows only when both arguments are negative and the true
7843 // product is exactly the minimum negative number.
7844 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7845 // For simplicity we just check if at least one side is not negative.
7846 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7847 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7848 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7850 }
7852}
7853
7856 const WithCache<const Value *> &RHS,
7857 const SimplifyQuery &SQ) {
7858 ConstantRange LHSRange =
7859 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7860 ConstantRange RHSRange =
7861 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7862 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7863}
7864
7865static OverflowResult
7868 const AddOperator *Add, const SimplifyQuery &SQ) {
7869 if (Add && Add->hasNoSignedWrap()) {
7871 }
7872
7873 // If LHS and RHS each have at least two sign bits, the addition will look
7874 // like
7875 //
7876 // XX..... +
7877 // YY.....
7878 //
7879 // If the carry into the most significant position is 0, X and Y can't both
7880 // be 1 and therefore the carry out of the addition is also 0.
7881 //
7882 // If the carry into the most significant position is 1, X and Y can't both
7883 // be 0 and therefore the carry out of the addition is also 1.
7884 //
7885 // Since the carry into the most significant position is always equal to
7886 // the carry out of the addition, there is no signed overflow.
7887 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7889
7890 ConstantRange LHSRange =
7891 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7892 ConstantRange RHSRange =
7893 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7894 OverflowResult OR =
7895 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7897 return OR;
7898
7899 // The remaining code needs Add to be available. Early returns if not so.
7900 if (!Add)
7902
7903 // If the sign of Add is the same as at least one of the operands, this add
7904 // CANNOT overflow. If this can be determined from the known bits of the
7905 // operands the above signedAddMayOverflow() check will have already done so.
7906 // The only other way to improve on the known bits is from an assumption, so
7907 // call computeKnownBitsFromContext() directly.
7908 bool LHSOrRHSKnownNonNegative =
7909 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7910 bool LHSOrRHSKnownNegative =
7911 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7912 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7913 KnownBits AddKnown(LHSRange.getBitWidth());
7914 computeKnownBitsFromContext(Add, AddKnown, SQ);
7915 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7916 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7918 }
7919
7921}
7922
7924 const Value *RHS,
7925 const SimplifyQuery &SQ) {
7926 // X - (X % ?)
7927 // The remainder of a value can't have greater magnitude than itself,
7928 // so the subtraction can't overflow.
7929
7930 // X - (X -nuw ?)
7931 // In the minimal case, this would simplify to "?", so there's no subtract
7932 // at all. But if this analysis is used to peek through casts, for example,
7933 // then determining no-overflow may allow other transforms.
7934
7935 // TODO: There are other patterns like this.
7936 // See simplifyICmpWithBinOpOnLHS() for candidates.
7937 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7938 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7939 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7941
7942 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
7943 SQ.DL)) {
7944 if (*C)
7947 }
7948
7949 ConstantRange LHSRange =
7950 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7951 ConstantRange RHSRange =
7952 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7953 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7954}
7955
7957 const Value *RHS,
7958 const SimplifyQuery &SQ) {
7959 // X - (X % ?)
7960 // The remainder of a value can't have greater magnitude than itself,
7961 // so the subtraction can't overflow.
7962
7963 // X - (X -nsw ?)
7964 // In the minimal case, this would simplify to "?", so there's no subtract
7965 // at all. But if this analysis is used to peek through casts, for example,
7966 // then determining no-overflow may allow other transforms.
7967 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7968 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7969 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
7971
7972 // If LHS and RHS each have at least two sign bits, the subtraction
7973 // cannot overflow.
7974 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7976
7977 ConstantRange LHSRange =
7978 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7979 ConstantRange RHSRange =
7980 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7981 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7982}
7983
7985 const DominatorTree &DT) {
7986 SmallVector<const CondBrInst *, 2> GuardingBranches;
7988
7989 for (const User *U : WO->users()) {
7990 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7991 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7992
7993 if (EVI->getIndices()[0] == 0)
7994 Results.push_back(EVI);
7995 else {
7996 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7997
7998 for (const auto *U : EVI->users())
7999 if (const auto *B = dyn_cast<CondBrInst>(U))
8000 GuardingBranches.push_back(B);
8001 }
8002 } else {
8003 // We are using the aggregate directly in a way we don't want to analyze
8004 // here (storing it to a global, say).
8005 return false;
8006 }
8007 }
8008
8009 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8010 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8011
8012 // Check if all users of the add are provably no-wrap.
8013 for (const auto *Result : Results) {
8014 // If the extractvalue itself is not executed on overflow, the we don't
8015 // need to check each use separately, since domination is transitive.
8016 if (DT.dominates(NoWrapEdge, Result->getParent()))
8017 continue;
8018
8019 for (const auto &RU : Result->uses())
8020 if (!DT.dominates(NoWrapEdge, RU))
8021 return false;
8022 }
8023
8024 return true;
8025 };
8026
8027 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8028}
8029
8030/// Shifts return poison if shiftwidth is larger than the bitwidth.
8031static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8032 auto *C = dyn_cast<Constant>(ShiftAmount);
8033 if (!C)
8034 return false;
8035
8036 // Shifts return poison if shiftwidth is larger than the bitwidth.
8038 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8039 unsigned NumElts = FVTy->getNumElements();
8040 for (unsigned i = 0; i < NumElts; ++i)
8041 ShiftAmounts.push_back(C->getAggregateElement(i));
8042 } else if (isa<ScalableVectorType>(C->getType()))
8043 return false; // Can't tell, just return false to be safe
8044 else
8045 ShiftAmounts.push_back(C);
8046
8047 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8048 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8049 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8050 });
8051
8052 return Safe;
8053}
8054
8056 bool ConsiderFlagsAndMetadata) {
8057
8058 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8059 Op->hasPoisonGeneratingAnnotations())
8060 return true;
8061
8062 unsigned Opcode = Op->getOpcode();
8063
8064 // Check whether opcode is a poison/undef-generating operation
8065 switch (Opcode) {
8066 case Instruction::Shl:
8067 case Instruction::AShr:
8068 case Instruction::LShr:
8069 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8070 case Instruction::FPToSI:
8071 case Instruction::FPToUI:
8072 // fptosi/ui yields poison if the resulting value does not fit in the
8073 // destination type.
8074 return true;
8075 case Instruction::Call:
8076 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8077 switch (II->getIntrinsicID()) {
8078 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8079 case Intrinsic::ctlz:
8080 case Intrinsic::cttz:
8081 case Intrinsic::abs:
8082 // We're not considering flags so it is safe to just return false.
8083 return false;
8084 case Intrinsic::sshl_sat:
8085 case Intrinsic::ushl_sat:
8086 if (!includesPoison(Kind) ||
8087 shiftAmountKnownInRange(II->getArgOperand(1)))
8088 return false;
8089 break;
8090 }
8091 }
8092 [[fallthrough]];
8093 case Instruction::CallBr:
8094 case Instruction::Invoke: {
8095 const auto *CB = cast<CallBase>(Op);
8096 return !CB->hasRetAttr(Attribute::NoUndef) &&
8097 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8098 }
8099 case Instruction::InsertElement:
8100 case Instruction::ExtractElement: {
8101 // If index exceeds the length of the vector, it returns poison
8102 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8103 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8104 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8105 if (includesPoison(Kind))
8106 return !Idx ||
8107 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8108 return false;
8109 }
8110 case Instruction::ShuffleVector: {
8112 ? cast<ConstantExpr>(Op)->getShuffleMask()
8113 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8114 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8115 }
8116 case Instruction::FNeg:
8117 case Instruction::PHI:
8118 case Instruction::Select:
8119 case Instruction::ExtractValue:
8120 case Instruction::InsertValue:
8121 case Instruction::Freeze:
8122 case Instruction::ICmp:
8123 case Instruction::FCmp:
8124 case Instruction::GetElementPtr:
8125 return false;
8126 case Instruction::AddrSpaceCast:
8127 return true;
8128 default: {
8129 const auto *CE = dyn_cast<ConstantExpr>(Op);
8130 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8131 return false;
8132 else if (Instruction::isBinaryOp(Opcode))
8133 return false;
8134 // Be conservative and return true.
8135 return true;
8136 }
8137 }
8138}
8139
8141 bool ConsiderFlagsAndMetadata) {
8142 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8143 ConsiderFlagsAndMetadata);
8144}
8145
8146bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8147 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8148 ConsiderFlagsAndMetadata);
8149}
8150
8151static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8152 unsigned Depth) {
8153 if (ValAssumedPoison == V)
8154 return true;
8155
8156 const unsigned MaxDepth = 2;
8157 if (Depth >= MaxDepth)
8158 return false;
8159
8160 if (const auto *I = dyn_cast<Instruction>(V)) {
8161 if (any_of(I->operands(), [=](const Use &Op) {
8162 return propagatesPoison(Op) &&
8163 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8164 }))
8165 return true;
8166
8167 // V = extractvalue V0, idx
8168 // V2 = extractvalue V0, idx2
8169 // V0's elements are all poison or not. (e.g., add_with_overflow)
8170 const WithOverflowInst *II;
8172 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8173 llvm::is_contained(II->args(), ValAssumedPoison)))
8174 return true;
8175 }
8176 return false;
8177}
8178
8179static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8180 unsigned Depth) {
8181 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8182 return true;
8183
8184 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8185 return true;
8186
8187 const unsigned MaxDepth = 2;
8188 if (Depth >= MaxDepth)
8189 return false;
8190
8191 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8192 if (I && !canCreatePoison(cast<Operator>(I))) {
8193 return all_of(I->operands(), [=](const Value *Op) {
8194 return impliesPoison(Op, V, Depth + 1);
8195 });
8196 }
8197 return false;
8198}
8199
8200bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8201 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8202}
8203
8204static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8205
8207 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8208 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8210 return false;
8211
8212 if (isa<MetadataAsValue>(V))
8213 return false;
8214
8215 if (const auto *A = dyn_cast<Argument>(V)) {
8216 if (A->hasAttribute(Attribute::NoUndef) ||
8217 A->hasAttribute(Attribute::Dereferenceable) ||
8218 A->hasAttribute(Attribute::DereferenceableOrNull))
8219 return true;
8220 }
8221
8222 if (auto *C = dyn_cast<Constant>(V)) {
8223 if (isa<PoisonValue>(C))
8224 return !includesPoison(Kind);
8225
8226 if (isa<UndefValue>(C))
8227 return !includesUndef(Kind);
8228
8231 return true;
8232
8233 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8234 if (isa<ConstantExpr>(C)) {
8235 // Scalable vectors can use a ConstantExpr to build a splat.
8236 if (Constant *SplatC = C->getSplatValue())
8237 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8238 return true;
8239 } else {
8240 if (includesUndef(Kind) && C->containsUndefElement())
8241 return false;
8242 if (includesPoison(Kind) && C->containsPoisonElement())
8243 return false;
8244 return !C->containsConstantExpression();
8245 }
8246 }
8247 }
8248
8249 // Strip cast operations from a pointer value.
8250 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8251 // inbounds with zero offset. To guarantee that the result isn't poison, the
8252 // stripped pointer is checked as it has to be pointing into an allocated
8253 // object or be null `null` to ensure `inbounds` getelement pointers with a
8254 // zero offset could not produce poison.
8255 // It can strip off addrspacecast that do not change bit representation as
8256 // well. We believe that such addrspacecast is equivalent to no-op.
8257 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8258 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8259 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8260 return true;
8261
8262 auto OpCheck = [&](const Value *V) {
8263 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8264 };
8265
8266 if (auto *Opr = dyn_cast<Operator>(V)) {
8267 // If the value is a freeze instruction, then it can never
8268 // be undef or poison.
8269 if (isa<FreezeInst>(V))
8270 return true;
8271
8272 if (const auto *CB = dyn_cast<CallBase>(V)) {
8273 if (CB->hasRetAttr(Attribute::NoUndef) ||
8274 CB->hasRetAttr(Attribute::Dereferenceable) ||
8275 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8276 return true;
8277 }
8278
8279 if (!::canCreateUndefOrPoison(Opr, Kind,
8280 /*ConsiderFlagsAndMetadata=*/true)) {
8281 if (const auto *PN = dyn_cast<PHINode>(V)) {
8282 unsigned Num = PN->getNumIncomingValues();
8283 bool IsWellDefined = true;
8284 for (unsigned i = 0; i < Num; ++i) {
8285 if (PN == PN->getIncomingValue(i))
8286 continue;
8287 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8288 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8289 DT, Depth + 1, Kind)) {
8290 IsWellDefined = false;
8291 break;
8292 }
8293 }
8294 if (IsWellDefined)
8295 return true;
8296 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8297 : nullptr) {
8298 // For splats we only need to check the value being splatted.
8299 if (OpCheck(Splat))
8300 return true;
8301 } else if (all_of(Opr->operands(), OpCheck))
8302 return true;
8303 }
8304 }
8305
8306 if (auto *I = dyn_cast<LoadInst>(V))
8307 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8308 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8309 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8310 return true;
8311
8313 return true;
8314
8315 // CtxI may be null or a cloned instruction.
8316 if (!CtxI || !CtxI->getParent() || !DT)
8317 return false;
8318
8319 auto *DNode = DT->getNode(CtxI->getParent());
8320 if (!DNode)
8321 // Unreachable block
8322 return false;
8323
8324 // If V is used as a branch condition before reaching CtxI, V cannot be
8325 // undef or poison.
8326 // br V, BB1, BB2
8327 // BB1:
8328 // CtxI ; V cannot be undef or poison here
8329 auto *Dominator = DNode->getIDom();
8330 // This check is purely for compile time reasons: we can skip the IDom walk
8331 // if what we are checking for includes undef and the value is not an integer.
8332 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8333 while (Dominator) {
8334 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8335
8336 Value *Cond = nullptr;
8337 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8338 Cond = BI->getCondition();
8339 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8340 Cond = SI->getCondition();
8341 }
8342
8343 if (Cond) {
8344 if (Cond == V)
8345 return true;
8346 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8347 // For poison, we can analyze further
8348 auto *Opr = cast<Operator>(Cond);
8349 if (any_of(Opr->operands(), [V](const Use &U) {
8350 return V == U && propagatesPoison(U);
8351 }))
8352 return true;
8353 }
8354 }
8355
8356 Dominator = Dominator->getIDom();
8357 }
8358
8359 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8360 return true;
8361
8362 return false;
8363}
8364
8366 const Instruction *CtxI,
8367 const DominatorTree *DT,
8368 unsigned Depth) {
8369 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8371}
8372
8374 const Instruction *CtxI,
8375 const DominatorTree *DT, unsigned Depth) {
8376 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8378}
8379
8381 const Instruction *CtxI,
8382 const DominatorTree *DT, unsigned Depth) {
8383 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8385}
8386
8387/// Return true if undefined behavior would provably be executed on the path to
8388/// OnPathTo if Root produced a posion result. Note that this doesn't say
8389/// anything about whether OnPathTo is actually executed or whether Root is
8390/// actually poison. This can be used to assess whether a new use of Root can
8391/// be added at a location which is control equivalent with OnPathTo (such as
8392/// immediately before it) without introducing UB which didn't previously
8393/// exist. Note that a false result conveys no information.
8395 Instruction *OnPathTo,
8396 DominatorTree *DT) {
8397 // Basic approach is to assume Root is poison, propagate poison forward
8398 // through all users we can easily track, and then check whether any of those
8399 // users are provable UB and must execute before out exiting block might
8400 // exit.
8401
8402 // The set of all recursive users we've visited (which are assumed to all be
8403 // poison because of said visit)
8406 Worklist.push_back(Root);
8407 while (!Worklist.empty()) {
8408 const Instruction *I = Worklist.pop_back_val();
8409
8410 // If we know this must trigger UB on a path leading our target.
8411 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8412 return true;
8413
8414 // If we can't analyze propagation through this instruction, just skip it
8415 // and transitive users. Safe as false is a conservative result.
8416 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8417 return KnownPoison.contains(U) && propagatesPoison(U);
8418 }))
8419 continue;
8420
8421 if (KnownPoison.insert(I).second)
8422 for (const User *User : I->users())
8423 Worklist.push_back(cast<Instruction>(User));
8424 }
8425
8426 // Might be non-UB, or might have a path we couldn't prove must execute on
8427 // way to exiting bb.
8428 return false;
8429}
8430
8432 const SimplifyQuery &SQ) {
8433 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8434 Add, SQ);
8435}
8436
8439 const WithCache<const Value *> &RHS,
8440 const SimplifyQuery &SQ) {
8441 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8442}
8443
8445 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8446 // of time because it's possible for another thread to interfere with it for an
8447 // arbitrary length of time, but programs aren't allowed to rely on that.
8448
8449 // If there is no successor, then execution can't transfer to it.
8450 if (isa<ReturnInst>(I))
8451 return false;
8453 return false;
8454
8455 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8456 // Instruction::willReturn.
8457 //
8458 // FIXME: Move this check into Instruction::willReturn.
8459 if (isa<CatchPadInst>(I)) {
8460 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8461 default:
8462 // A catchpad may invoke exception object constructors and such, which
8463 // in some languages can be arbitrary code, so be conservative by default.
8464 return false;
8466 // For CoreCLR, it just involves a type test.
8467 return true;
8468 }
8469 }
8470
8471 // An instruction that returns without throwing must transfer control flow
8472 // to a successor.
8473 return !I->mayThrow() && I->willReturn();
8474}
8475
8477 // TODO: This is slightly conservative for invoke instruction since exiting
8478 // via an exception *is* normal control for them.
8479 for (const Instruction &I : *BB)
8481 return false;
8482 return true;
8483}
8484
8491
8494 assert(ScanLimit && "scan limit must be non-zero");
8495 for (const Instruction &I : Range) {
8496 if (--ScanLimit == 0)
8497 return false;
8499 return false;
8500 }
8501 return true;
8502}
8503
8505 const Loop *L) {
8506 // The loop header is guaranteed to be executed for every iteration.
8507 //
8508 // FIXME: Relax this constraint to cover all basic blocks that are
8509 // guaranteed to be executed at every iteration.
8510 if (I->getParent() != L->getHeader()) return false;
8511
8512 for (const Instruction &LI : *L->getHeader()) {
8513 if (&LI == I) return true;
8514 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8515 }
8516 llvm_unreachable("Instruction not contained in its own parent basic block.");
8517}
8518
8520 switch (IID) {
8521 // TODO: Add more intrinsics.
8522 case Intrinsic::sadd_with_overflow:
8523 case Intrinsic::ssub_with_overflow:
8524 case Intrinsic::smul_with_overflow:
8525 case Intrinsic::uadd_with_overflow:
8526 case Intrinsic::usub_with_overflow:
8527 case Intrinsic::umul_with_overflow:
8528 // If an input is a vector containing a poison element, the
8529 // two output vectors (calculated results, overflow bits)'
8530 // corresponding lanes are poison.
8531 return true;
8532 case Intrinsic::ctpop:
8533 case Intrinsic::ctlz:
8534 case Intrinsic::cttz:
8535 case Intrinsic::abs:
8536 case Intrinsic::smax:
8537 case Intrinsic::smin:
8538 case Intrinsic::umax:
8539 case Intrinsic::umin:
8540 case Intrinsic::scmp:
8541 case Intrinsic::smulh:
8542 case Intrinsic::umulh:
8543 case Intrinsic::is_fpclass:
8544 case Intrinsic::ptrmask:
8545 case Intrinsic::ucmp:
8546 case Intrinsic::bitreverse:
8547 case Intrinsic::bswap:
8548 case Intrinsic::sadd_sat:
8549 case Intrinsic::ssub_sat:
8550 case Intrinsic::sshl_sat:
8551 case Intrinsic::uadd_sat:
8552 case Intrinsic::usub_sat:
8553 case Intrinsic::ushl_sat:
8554 case Intrinsic::smul_fix:
8555 case Intrinsic::smul_fix_sat:
8556 case Intrinsic::umul_fix:
8557 case Intrinsic::umul_fix_sat:
8558 case Intrinsic::pow:
8559 case Intrinsic::powi:
8560 case Intrinsic::sin:
8561 case Intrinsic::sinh:
8562 case Intrinsic::cos:
8563 case Intrinsic::cosh:
8564 case Intrinsic::sincos:
8565 case Intrinsic::sincospi:
8566 case Intrinsic::tan:
8567 case Intrinsic::tanh:
8568 case Intrinsic::asin:
8569 case Intrinsic::acos:
8570 case Intrinsic::atan:
8571 case Intrinsic::atan2:
8572 case Intrinsic::canonicalize:
8573 case Intrinsic::sqrt:
8574 case Intrinsic::fma:
8575 case Intrinsic::fmuladd:
8576 case Intrinsic::exp:
8577 case Intrinsic::exp2:
8578 case Intrinsic::exp10:
8579 case Intrinsic::log:
8580 case Intrinsic::log2:
8581 case Intrinsic::log10:
8582 case Intrinsic::modf:
8583 case Intrinsic::floor:
8584 case Intrinsic::ceil:
8585 case Intrinsic::trunc:
8586 case Intrinsic::rint:
8587 case Intrinsic::nearbyint:
8588 case Intrinsic::round:
8589 case Intrinsic::roundeven:
8590 case Intrinsic::lrint:
8591 case Intrinsic::llrint:
8592 case Intrinsic::fshl:
8593 case Intrinsic::fshr:
8594 case Intrinsic::frexp:
8595 case Intrinsic::get_active_lane_mask:
8596 return true;
8597 default:
8598 return false;
8599 }
8600}
8601
8602bool llvm::propagatesPoison(const Use &PoisonOp) {
8603 const Operator *I = cast<Operator>(PoisonOp.getUser());
8604 switch (I->getOpcode()) {
8605 case Instruction::Freeze:
8606 case Instruction::PHI:
8607 case Instruction::Invoke:
8608 return false;
8609 case Instruction::Select:
8610 return PoisonOp.getOperandNo() == 0;
8611 case Instruction::Call:
8612 if (auto *II = dyn_cast<IntrinsicInst>(I))
8613 return intrinsicPropagatesPoison(II->getIntrinsicID());
8614 return false;
8615 case Instruction::ICmp:
8616 case Instruction::FCmp:
8617 case Instruction::GetElementPtr:
8618 return true;
8619 default:
8621 return true;
8622
8623 // Be conservative and return false.
8624 return false;
8625 }
8626}
8627
8628/// Enumerates all operands of \p I that are guaranteed to not be undef or
8629/// poison. If the callback \p Handle returns true, stop processing and return
8630/// true. Otherwise, return false.
8631template <typename CallableT>
8633 const CallableT &Handle) {
8634 switch (I->getOpcode()) {
8635 case Instruction::Store:
8636 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8637 return true;
8638 break;
8639
8640 case Instruction::Load:
8641 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8642 return true;
8643 break;
8644
8645 // Since dereferenceable attribute imply noundef, atomic operations
8646 // also implicitly have noundef pointers too
8647 case Instruction::AtomicCmpXchg:
8649 return true;
8650 break;
8651
8652 case Instruction::AtomicRMW:
8653 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8654 return true;
8655 break;
8656
8657 case Instruction::Call:
8658 case Instruction::Invoke: {
8659 const CallBase *CB = cast<CallBase>(I);
8660 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8661 return true;
8662 for (unsigned i = 0; i < CB->arg_size(); ++i)
8663 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8664 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8665 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8666 Handle(CB->getArgOperand(i)))
8667 return true;
8668 break;
8669 }
8670 case Instruction::Ret:
8671 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8672 Handle(I->getOperand(0)))
8673 return true;
8674 break;
8675 case Instruction::Switch:
8676 if (Handle(cast<SwitchInst>(I)->getCondition()))
8677 return true;
8678 break;
8679 case Instruction::CondBr:
8680 if (Handle(cast<CondBrInst>(I)->getCondition()))
8681 return true;
8682 break;
8683 default:
8684 break;
8685 }
8686
8687 return false;
8688}
8689
8690/// Enumerates all operands of \p I that are guaranteed to not be poison.
8691template <typename CallableT>
8693 const CallableT &Handle) {
8694 if (handleGuaranteedWellDefinedOps(I, Handle))
8695 return true;
8696 switch (I->getOpcode()) {
8697 // Divisors of these operations are allowed to be partially undef.
8698 case Instruction::UDiv:
8699 case Instruction::SDiv:
8700 case Instruction::URem:
8701 case Instruction::SRem:
8702 return Handle(I->getOperand(1));
8703 default:
8704 return false;
8705 }
8706}
8707
8709 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8711 I, [&](const Value *V) { return KnownPoison.count(V); });
8712}
8713
8715 bool PoisonOnly) {
8716 // We currently only look for uses of values within the same basic
8717 // block, as that makes it easier to guarantee that the uses will be
8718 // executed given that Inst is executed.
8719 //
8720 // FIXME: Expand this to consider uses beyond the same basic block. To do
8721 // this, look out for the distinction between post-dominance and strong
8722 // post-dominance.
8723 const BasicBlock *BB = nullptr;
8725 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8726 BB = Inst->getParent();
8727 Begin = Inst->getIterator();
8728 Begin++;
8729 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8730 if (Arg->getParent()->isDeclaration())
8731 return false;
8732 BB = &Arg->getParent()->getEntryBlock();
8733 Begin = BB->begin();
8734 } else {
8735 return false;
8736 }
8737
8738 // Limit number of instructions we look at, to avoid scanning through large
8739 // blocks. The current limit is chosen arbitrarily.
8740 unsigned ScanLimit = 32;
8742
8743 if (!PoisonOnly) {
8744 // Since undef does not propagate eagerly, be conservative & just check
8745 // whether a value is directly passed to an instruction that must take
8746 // well-defined operands.
8747
8748 for (const auto &I : make_range(Begin, End)) {
8749 if (--ScanLimit == 0)
8750 break;
8751
8752 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8753 return WellDefinedOp == V;
8754 }))
8755 return true;
8756
8758 break;
8759 }
8760 return false;
8761 }
8762
8763 // Set of instructions that we have proved will yield poison if Inst
8764 // does.
8765 SmallPtrSet<const Value *, 16> YieldsPoison;
8767
8768 YieldsPoison.insert(V);
8769 Visited.insert(BB);
8770
8771 while (true) {
8772 for (const auto &I : make_range(Begin, End)) {
8773 if (--ScanLimit == 0)
8774 return false;
8775 if (mustTriggerUB(&I, YieldsPoison))
8776 return true;
8778 return false;
8779
8780 // If an operand is poison and propagates it, mark I as yielding poison.
8781 for (const Use &Op : I.operands()) {
8782 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8783 YieldsPoison.insert(&I);
8784 break;
8785 }
8786 }
8787
8788 // Special handling for select, which returns poison if its operand 0 is
8789 // poison (handled in the loop above) *or* if both its true/false operands
8790 // are poison (handled here).
8791 if (I.getOpcode() == Instruction::Select &&
8792 YieldsPoison.count(I.getOperand(1)) &&
8793 YieldsPoison.count(I.getOperand(2))) {
8794 YieldsPoison.insert(&I);
8795 }
8796 }
8797
8798 BB = BB->getSingleSuccessor();
8799 if (!BB || !Visited.insert(BB).second)
8800 break;
8801
8802 Begin = BB->getFirstNonPHIIt();
8803 End = BB->end();
8804 }
8805 return false;
8806}
8807
8809 return ::programUndefinedIfUndefOrPoison(Inst, false);
8810}
8811
8813 return ::programUndefinedIfUndefOrPoison(Inst, true);
8814}
8815
8816static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8817 if (FMF.noNaNs())
8818 return true;
8819
8820 if (auto *C = dyn_cast<ConstantFP>(V))
8821 return !C->isNaN();
8822
8823 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8824 if (!C->getElementType()->isFloatingPointTy())
8825 return false;
8826 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8827 if (C->getElementAsAPFloat(I).isNaN())
8828 return false;
8829 }
8830 return true;
8831 }
8832
8834 return true;
8835
8836 return false;
8837}
8838
8839static bool isKnownNonZero(const Value *V) {
8840 if (auto *C = dyn_cast<ConstantFP>(V))
8841 return !C->isZero();
8842
8843 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8844 if (!C->getElementType()->isFloatingPointTy())
8845 return false;
8846 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8847 if (C->getElementAsAPFloat(I).isZero())
8848 return false;
8849 }
8850 return true;
8851 }
8852
8853 return false;
8854}
8855
8856/// Match clamp pattern for float types without care about NaNs or signed zeros.
8857/// Given non-min/max outer cmp/select from the clamp pattern this
8858/// function recognizes if it can be substitued by a "canonical" min/max
8859/// pattern.
8861 Value *CmpLHS, Value *CmpRHS,
8862 Value *TrueVal, Value *FalseVal,
8863 Value *&LHS, Value *&RHS) {
8864 // Try to match
8865 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8866 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8867 // and return description of the outer Max/Min.
8868
8869 // First, check if select has inverse order:
8870 if (CmpRHS == FalseVal) {
8871 std::swap(TrueVal, FalseVal);
8872 Pred = CmpInst::getInversePredicate(Pred);
8873 }
8874
8875 // Assume success now. If there's no match, callers should not use these anyway.
8876 LHS = TrueVal;
8877 RHS = FalseVal;
8878
8879 const APFloat *FC1;
8880 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8881 return {SPF_UNKNOWN, SPNB_NA, false};
8882
8883 const APFloat *FC2;
8884 switch (Pred) {
8885 case CmpInst::FCMP_OLT:
8886 case CmpInst::FCMP_OLE:
8887 case CmpInst::FCMP_ULT:
8888 case CmpInst::FCMP_ULE:
8889 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8890 *FC1 < *FC2)
8891 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8892 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8893 *FC1 < *FC2)
8894 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8895 break;
8896 case CmpInst::FCMP_OGT:
8897 case CmpInst::FCMP_OGE:
8898 case CmpInst::FCMP_UGT:
8899 case CmpInst::FCMP_UGE:
8900 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8901 *FC1 > *FC2)
8902 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8903 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8904 *FC1 > *FC2)
8905 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8906 break;
8907 default:
8908 break;
8909 }
8910
8911 return {SPF_UNKNOWN, SPNB_NA, false};
8912}
8913
8914/// Recognize variations of:
8915/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8917 Value *CmpLHS, Value *CmpRHS,
8918 Value *TrueVal, Value *FalseVal) {
8919 // Swap the select operands and predicate to match the patterns below.
8920 if (CmpRHS != TrueVal) {
8921 Pred = ICmpInst::getSwappedPredicate(Pred);
8922 std::swap(TrueVal, FalseVal);
8923 }
8924 const APInt *C1;
8925 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8926 const APInt *C2;
8927 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8928 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8929 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8930 return {SPF_SMAX, SPNB_NA, false};
8931
8932 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8933 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8934 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8935 return {SPF_SMIN, SPNB_NA, false};
8936
8937 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8938 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8939 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8940 return {SPF_UMAX, SPNB_NA, false};
8941
8942 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8943 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8944 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8945 return {SPF_UMIN, SPNB_NA, false};
8946 }
8947 return {SPF_UNKNOWN, SPNB_NA, false};
8948}
8949
8950/// Recognize variations of:
8951/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8953 Value *CmpLHS, Value *CmpRHS,
8954 Value *TVal, Value *FVal,
8955 unsigned Depth) {
8956 // TODO: Allow FP min/max with nnan/nsz.
8957 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8958
8959 Value *A = nullptr, *B = nullptr;
8960 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8961 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8962 return {SPF_UNKNOWN, SPNB_NA, false};
8963
8964 Value *C = nullptr, *D = nullptr;
8965 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8966 if (L.Flavor != R.Flavor)
8967 return {SPF_UNKNOWN, SPNB_NA, false};
8968
8969 // We have something like: x Pred y ? min(a, b) : min(c, d).
8970 // Try to match the compare to the min/max operations of the select operands.
8971 // First, make sure we have the right compare predicate.
8972 switch (L.Flavor) {
8973 case SPF_SMIN:
8974 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8975 Pred = ICmpInst::getSwappedPredicate(Pred);
8976 std::swap(CmpLHS, CmpRHS);
8977 }
8978 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8979 break;
8980 return {SPF_UNKNOWN, SPNB_NA, false};
8981 case SPF_SMAX:
8982 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8983 Pred = ICmpInst::getSwappedPredicate(Pred);
8984 std::swap(CmpLHS, CmpRHS);
8985 }
8986 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8987 break;
8988 return {SPF_UNKNOWN, SPNB_NA, false};
8989 case SPF_UMIN:
8990 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8991 Pred = ICmpInst::getSwappedPredicate(Pred);
8992 std::swap(CmpLHS, CmpRHS);
8993 }
8994 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8995 break;
8996 return {SPF_UNKNOWN, SPNB_NA, false};
8997 case SPF_UMAX:
8998 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8999 Pred = ICmpInst::getSwappedPredicate(Pred);
9000 std::swap(CmpLHS, CmpRHS);
9001 }
9002 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
9003 break;
9004 return {SPF_UNKNOWN, SPNB_NA, false};
9005 default:
9006 return {SPF_UNKNOWN, SPNB_NA, false};
9007 }
9008
9009 // If there is a common operand in the already matched min/max and the other
9010 // min/max operands match the compare operands (either directly or inverted),
9011 // then this is min/max of the same flavor.
9012
9013 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
9014 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
9015 if (D == B) {
9016 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
9017 match(A, m_Not(m_Specific(CmpRHS)))))
9018 return {L.Flavor, SPNB_NA, false};
9019 }
9020 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
9021 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
9022 if (C == B) {
9023 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
9024 match(A, m_Not(m_Specific(CmpRHS)))))
9025 return {L.Flavor, SPNB_NA, false};
9026 }
9027 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
9028 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
9029 if (D == A) {
9030 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
9031 match(B, m_Not(m_Specific(CmpRHS)))))
9032 return {L.Flavor, SPNB_NA, false};
9033 }
9034 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
9035 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
9036 if (C == A) {
9037 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
9038 match(B, m_Not(m_Specific(CmpRHS)))))
9039 return {L.Flavor, SPNB_NA, false};
9040 }
9041
9042 return {SPF_UNKNOWN, SPNB_NA, false};
9043}
9044
9045/// If the input value is the result of a 'not' op, constant integer, or vector
9046/// splat of a constant integer, return the bitwise-not source value.
9047/// TODO: This could be extended to handle non-splat vector integer constants.
9049 Value *NotV;
9050 if (match(V, m_Not(m_Value(NotV))))
9051 return NotV;
9052
9053 const APInt *C;
9054 if (match(V, m_APInt(C)))
9055 return ConstantInt::get(V->getType(), ~(*C));
9056
9057 return nullptr;
9058}
9059
9060/// Match non-obvious integer minimum and maximum sequences.
9062 Value *CmpLHS, Value *CmpRHS,
9063 Value *TrueVal, Value *FalseVal,
9064 Value *&LHS, Value *&RHS,
9065 unsigned Depth) {
9066 // Assume success. If there's no match, callers should not use these anyway.
9067 LHS = TrueVal;
9068 RHS = FalseVal;
9069
9070 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9072 return SPR;
9073
9074 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
9076 return SPR;
9077
9078 // Look through 'not' ops to find disguised min/max.
9079 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9080 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9081 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9082 switch (Pred) {
9083 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9084 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9085 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9086 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9087 default: break;
9088 }
9089 }
9090
9091 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9092 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9093 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9094 switch (Pred) {
9095 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9096 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9097 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9098 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9099 default: break;
9100 }
9101 }
9102
9103 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9104 return {SPF_UNKNOWN, SPNB_NA, false};
9105
9106 const APInt *C1;
9107 if (!match(CmpRHS, m_APInt(C1)))
9108 return {SPF_UNKNOWN, SPNB_NA, false};
9109
9110 // An unsigned min/max can be written with a signed compare.
9111 const APInt *C2;
9112 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9113 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9114 // Is the sign bit set?
9115 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9116 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9117 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9118 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9119
9120 // Is the sign bit clear?
9121 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9122 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9123 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9124 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9125 }
9126
9127 return {SPF_UNKNOWN, SPNB_NA, false};
9128}
9129
9130bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9131 bool AllowPoison) {
9132 assert(X && Y && "Invalid operand");
9133
9134 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9135 if (!match(X, m_Neg(m_Specific(Y))))
9136 return false;
9137
9138 auto *BO = cast<BinaryOperator>(X);
9139 if (NeedNSW && !BO->hasNoSignedWrap())
9140 return false;
9141
9142 auto *Zero = cast<Constant>(BO->getOperand(0));
9143 if (!AllowPoison && !Zero->isNullValue())
9144 return false;
9145
9146 return true;
9147 };
9148
9149 // X = -Y or Y = -X
9150 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9151 return true;
9152
9153 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9154 Value *A, *B;
9155 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9156 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9157 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9159}
9160
9161bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9162 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9163 Value *A, *B, *C;
9164 CmpPredicate Pred1, Pred2;
9165 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9166 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9167 return false;
9168
9169 // They must both have samesign flag or not.
9170 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9171 return false;
9172
9173 if (B == C)
9174 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9175
9176 // Try to infer the relationship from constant ranges.
9177 const APInt *RHSC1, *RHSC2;
9178 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9179 return false;
9180
9181 // Sign bits of two RHSCs should match.
9182 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9183 return false;
9184
9185 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9186 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9187
9188 return CR1.inverse() == CR2;
9189}
9190
9192 SelectPatternNaNBehavior NaNBehavior,
9193 bool Ordered) {
9194 switch (Pred) {
9195 default:
9196 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9197 case ICmpInst::ICMP_UGT:
9198 case ICmpInst::ICMP_UGE:
9199 return {SPF_UMAX, SPNB_NA, false};
9200 case ICmpInst::ICMP_SGT:
9201 case ICmpInst::ICMP_SGE:
9202 return {SPF_SMAX, SPNB_NA, false};
9203 case ICmpInst::ICMP_ULT:
9204 case ICmpInst::ICMP_ULE:
9205 return {SPF_UMIN, SPNB_NA, false};
9206 case ICmpInst::ICMP_SLT:
9207 case ICmpInst::ICMP_SLE:
9208 return {SPF_SMIN, SPNB_NA, false};
9209 case FCmpInst::FCMP_UGT:
9210 case FCmpInst::FCMP_UGE:
9211 case FCmpInst::FCMP_OGT:
9212 case FCmpInst::FCMP_OGE:
9213 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9214 case FCmpInst::FCMP_ULT:
9215 case FCmpInst::FCMP_ULE:
9216 case FCmpInst::FCMP_OLT:
9217 case FCmpInst::FCMP_OLE:
9218 return {SPF_FMINNUM, NaNBehavior, Ordered};
9219 }
9220}
9221
9222std::optional<std::pair<CmpPredicate, Constant *>>
9225 "Only for relational integer predicates.");
9226 if (isa<UndefValue>(C))
9227 return std::nullopt;
9228
9229 Type *Type = C->getType();
9230 bool IsSigned = ICmpInst::isSigned(Pred);
9231
9233 bool WillIncrement =
9234 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9235
9236 // Check if the constant operand can be safely incremented/decremented
9237 // without overflowing/underflowing.
9238 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9239 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9240 return false;
9241
9242 if (!Pred.hasSameSign())
9243 return true;
9244
9245 // Crossing the corresponding boundary in the other ordering changes the
9246 // sign bit, and therefore changes the poison domain.
9247 return WillIncrement ? !C->isMaxValue(!IsSigned)
9248 : !C->isMinValue(!IsSigned);
9249 };
9250
9251 Constant *SafeReplacementConstant = nullptr;
9252 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9253 // Bail out if the constant can't be safely incremented/decremented.
9254 if (!ConstantIsOk(CI))
9255 return std::nullopt;
9256 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9257 unsigned NumElts = FVTy->getNumElements();
9258 for (unsigned i = 0; i != NumElts; ++i) {
9259 Constant *Elt = C->getAggregateElement(i);
9260 if (!Elt)
9261 return std::nullopt;
9262
9263 if (isa<UndefValue>(Elt))
9264 continue;
9265
9266 // Bail out if we can't determine if this constant is min/max or if we
9267 // know that this constant is min/max.
9268 auto *CI = dyn_cast<ConstantInt>(Elt);
9269 if (!CI || !ConstantIsOk(CI))
9270 return std::nullopt;
9271
9272 if (!SafeReplacementConstant)
9273 SafeReplacementConstant = CI;
9274 }
9275 } else if (isa<VectorType>(C->getType())) {
9276 // Handle scalable splat
9277 Value *SplatC = C->getSplatValue();
9278 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9279 // Bail out if the constant can't be safely incremented/decremented.
9280 if (!CI || !ConstantIsOk(CI))
9281 return std::nullopt;
9282 } else {
9283 // ConstantExpr?
9284 return std::nullopt;
9285 }
9286
9287 // It may not be safe to change a compare predicate in the presence of
9288 // undefined elements, so replace those elements with the first safe constant
9289 // that we found.
9290 // TODO: in case of poison, it is safe; let's replace undefs only.
9291 if (C->containsUndefOrPoisonElement()) {
9292 assert(SafeReplacementConstant && "Replacement constant not set");
9293 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9294 }
9295
9297 Pred.hasSameSign());
9298
9299 // Increment or decrement the constant.
9300 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9301 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9302
9303 return std::make_pair(NewPred, NewC);
9304}
9305
9307 FastMathFlags FMF,
9308 Value *CmpLHS, Value *CmpRHS,
9309 Value *TrueVal, Value *FalseVal,
9310 Value *&LHS, Value *&RHS,
9311 unsigned Depth) {
9312 if (CmpInst::isFPPredicate(Pred)) {
9313 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9314 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9315 // purpose of identifying min/max. Disregard vector constants with undefined
9316 // elements because those can not be back-propagated for analysis.
9317 Value *OutputZeroVal = nullptr;
9318 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9319 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9320 OutputZeroVal = TrueVal;
9321 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9322 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9323 OutputZeroVal = FalseVal;
9324
9325 if (OutputZeroVal) {
9326 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9327 CmpLHS = OutputZeroVal;
9328 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9329 CmpRHS = OutputZeroVal;
9330 }
9331 }
9332
9333 LHS = CmpLHS;
9334 RHS = CmpRHS;
9335
9336 // Signed zero may return inconsistent results between implementations.
9337 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9338 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9339 // Therefore, we behave conservatively and only proceed if at least one of the
9340 // operands is known to not be zero or if we don't care about signed zero.
9341 if (CmpInst::isFPPredicate(Pred)) {
9342 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9343 !isKnownNonZero(CmpRHS))
9344 return {SPF_UNKNOWN, SPNB_NA, false};
9345 }
9346
9347 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9348 bool Ordered = false;
9349
9350 // When given one NaN and one non-NaN input:
9351 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9352 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9353 // ordered comparison fails), which could be NaN or non-NaN.
9354 // so here we discover exactly what NaN behavior is required/accepted.
9355 if (CmpInst::isFPPredicate(Pred)) {
9356 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9357 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9358
9359 if (LHSSafe && RHSSafe) {
9360 // Both operands are known non-NaN.
9361 NaNBehavior = SPNB_RETURNS_ANY;
9362 Ordered = CmpInst::isOrdered(Pred);
9363 } else if (CmpInst::isOrdered(Pred)) {
9364 // An ordered comparison will return false when given a NaN, so it
9365 // returns the RHS.
9366 Ordered = true;
9367 if (LHSSafe)
9368 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9369 NaNBehavior = SPNB_RETURNS_NAN;
9370 else if (RHSSafe)
9371 NaNBehavior = SPNB_RETURNS_OTHER;
9372 else
9373 // Completely unsafe.
9374 return {SPF_UNKNOWN, SPNB_NA, false};
9375 } else {
9376 Ordered = false;
9377 // An unordered comparison will return true when given a NaN, so it
9378 // returns the LHS.
9379 if (LHSSafe)
9380 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9381 NaNBehavior = SPNB_RETURNS_OTHER;
9382 else if (RHSSafe)
9383 NaNBehavior = SPNB_RETURNS_NAN;
9384 else
9385 // Completely unsafe.
9386 return {SPF_UNKNOWN, SPNB_NA, false};
9387 }
9388 }
9389
9390 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9391 std::swap(CmpLHS, CmpRHS);
9392 Pred = CmpInst::getSwappedPredicate(Pred);
9393 if (NaNBehavior == SPNB_RETURNS_NAN)
9394 NaNBehavior = SPNB_RETURNS_OTHER;
9395 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9396 NaNBehavior = SPNB_RETURNS_NAN;
9397 Ordered = !Ordered;
9398 }
9399
9400 // ([if]cmp X, Y) ? X : Y
9401 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9402 return getSelectPattern(Pred, NaNBehavior, Ordered);
9403
9404 if (isKnownNegation(TrueVal, FalseVal)) {
9405 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9406 // match against either LHS or sign-preserving operations on LHS, like
9407 // sext(LHS), or binary ops that do not wrap in signed sense.
9408 auto CmpLHSOrSExt =
9409 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9410 auto MaybeSExtOrMulCmpLHS =
9411 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9412 m_NSWShl(CmpLHSOrSExt, m_Value()));
9413 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9414 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9415 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9416 // Set the return values. If the compare uses the negated value (-X >s 0),
9417 // swap the return values because the negated value is always 'RHS'.
9418 LHS = TrueVal;
9419 RHS = FalseVal;
9420 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9421 std::swap(LHS, RHS);
9422
9423 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9424 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9425 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9426 return {SPF_ABS, SPNB_NA, false};
9427
9428 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9429 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9430 return {SPF_ABS, SPNB_NA, false};
9431
9432 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9433 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9434 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9435 return {SPF_NABS, SPNB_NA, false};
9436 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9437 // Set the return values. If the compare uses the negated value (-X >s 0),
9438 // swap the return values because the negated value is always 'RHS'.
9439 LHS = FalseVal;
9440 RHS = TrueVal;
9441 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9442 std::swap(LHS, RHS);
9443
9444 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9445 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9446 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9447 return {SPF_NABS, SPNB_NA, false};
9448
9449 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9450 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9451 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9452 return {SPF_ABS, SPNB_NA, false};
9453 }
9454 }
9455
9456 if (CmpInst::isIntPredicate(Pred))
9457 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS, Depth);
9458
9459 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9460 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9461 // semantics than minNum. Be conservative in such case.
9462 if (NaNBehavior != SPNB_RETURNS_ANY ||
9463 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9464 !isKnownNonZero(CmpRHS)))
9465 return {SPF_UNKNOWN, SPNB_NA, false};
9466
9467 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9468}
9469
9471 Instruction::CastOps *CastOp) {
9472 const DataLayout &DL = CmpI->getDataLayout();
9473
9474 Constant *CastedTo = nullptr;
9475 switch (*CastOp) {
9476 case Instruction::ZExt:
9477 if (CmpI->isUnsigned())
9478 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9479 break;
9480 case Instruction::SExt:
9481 if (CmpI->isSigned())
9482 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9483 break;
9484 case Instruction::Trunc:
9485 Constant *CmpConst;
9486 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9487 CmpConst->getType() == SrcTy) {
9488 // Here we have the following case:
9489 //
9490 // %cond = cmp iN %x, CmpConst
9491 // %tr = trunc iN %x to iK
9492 // %narrowsel = select i1 %cond, iK %t, iK C
9493 //
9494 // We can always move trunc after select operation:
9495 //
9496 // %cond = cmp iN %x, CmpConst
9497 // %widesel = select i1 %cond, iN %x, iN CmpConst
9498 // %tr = trunc iN %widesel to iK
9499 //
9500 // Note that C could be extended in any way because we don't care about
9501 // upper bits after truncation. It can't be abs pattern, because it would
9502 // look like:
9503 //
9504 // select i1 %cond, x, -x.
9505 //
9506 // So only min/max pattern could be matched. Such match requires widened C
9507 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9508 // CmpConst == C is checked below.
9509 CastedTo = CmpConst;
9510 } else {
9511 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9512 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9513 }
9514 break;
9515 case Instruction::FPTrunc:
9516 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9517 break;
9518 case Instruction::FPExt:
9519 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9520 break;
9521 case Instruction::FPToUI:
9522 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9523 break;
9524 case Instruction::FPToSI:
9525 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9526 break;
9527 case Instruction::UIToFP:
9528 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9529 break;
9530 case Instruction::SIToFP:
9531 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9532 break;
9533 default:
9534 break;
9535 }
9536
9537 if (!CastedTo)
9538 return nullptr;
9539
9540 // Make sure the cast doesn't lose any information.
9541 Constant *CastedBack =
9542 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9543 if (CastedBack && CastedBack != C)
9544 return nullptr;
9545
9546 return CastedTo;
9547}
9548
9549/// Helps to match a select pattern in case of a type mismatch.
9550///
9551/// The function processes the case when type of true and false values of a
9552/// select instruction differs from type of the cmp instruction operands because
9553/// of a cast instruction. The function checks if it is legal to move the cast
9554/// operation after "select". If yes, it returns the new second value of
9555/// "select" (with the assumption that cast is moved):
9556/// 1. As operand of cast instruction when both values of "select" are same cast
9557/// instructions.
9558/// 2. As restored constant (by applying reverse cast operation) when the first
9559/// value of the "select" is a cast operation and the second value is a
9560/// constant. It is implemented in lookThroughCastConst().
9561/// 3. As one operand is cast instruction and the other is not. The operands in
9562/// sel(cmp) are in different type integer.
9563/// NOTE: We return only the new second value because the first value could be
9564/// accessed as operand of cast instruction.
9566 Instruction::CastOps *CastOp) {
9567 auto *Cast1 = dyn_cast<CastInst>(V1);
9568 if (!Cast1)
9569 return nullptr;
9570
9571 *CastOp = Cast1->getOpcode();
9572 Type *SrcTy = Cast1->getSrcTy();
9573 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9574 // If V1 and V2 are both the same cast from the same type, look through V1.
9575 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9576 return Cast2->getOperand(0);
9577 return nullptr;
9578 }
9579
9580 auto *C = dyn_cast<Constant>(V2);
9581 if (C)
9582 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9583
9584 Value *CastedTo = nullptr;
9585 if (*CastOp == Instruction::Trunc) {
9586 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9587 // Here we have the following case:
9588 // %y_ext = sext iK %y to iN
9589 // %cond = cmp iN %x, %y_ext
9590 // %tr = trunc iN %x to iK
9591 // %narrowsel = select i1 %cond, iK %tr, iK %y
9592 //
9593 // We can always move trunc after select operation:
9594 // %y_ext = sext iK %y to iN
9595 // %cond = cmp iN %x, %y_ext
9596 // %widesel = select i1 %cond, iN %x, iN %y_ext
9597 // %tr = trunc iN %widesel to iK
9598 assert(V2->getType() == Cast1->getType() &&
9599 "V2 and Cast1 should be the same type.");
9600 CastedTo = CmpI->getOperand(1);
9601 }
9602 }
9603
9604 return CastedTo;
9605}
9607 Instruction::CastOps *CastOp,
9608 unsigned Depth) {
9610 return {SPF_UNKNOWN, SPNB_NA, false};
9611
9613 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9614
9615 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9616 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9617
9618 Value *TrueVal = SI->getTrueValue();
9619 Value *FalseVal = SI->getFalseValue();
9620
9621 return llvm::matchDecomposedSelectPattern(CmpI, TrueVal, FalseVal, LHS, RHS,
9622 SI->getFastMathFlagsOrNone(),
9623 CastOp, Depth);
9624}
9625
9627 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9628 FastMathFlags FMF, Instruction::CastOps *CastOp, unsigned Depth) {
9629 CmpInst::Predicate Pred = CmpI->getPredicate();
9630 Value *CmpLHS = CmpI->getOperand(0);
9631 Value *CmpRHS = CmpI->getOperand(1);
9632 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9633 FMF.setNoNaNs();
9634
9635 // Bail out early.
9636 if (CmpI->isEquality())
9637 return {SPF_UNKNOWN, SPNB_NA, false};
9638
9639 // Deal with type mismatches.
9640 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9641 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9642 // If this is a potential fmin/fmax with a cast to integer, then ignore
9643 // -0.0 because there is no corresponding integer value.
9644 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9645 FMF.setNoSignedZeros();
9646 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9647 cast<CastInst>(TrueVal)->getOperand(0), C,
9648 LHS, RHS, Depth);
9649 }
9650 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9651 // If this is a potential fmin/fmax with a cast to integer, then ignore
9652 // -0.0 because there is no corresponding integer value.
9653 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9654 FMF.setNoSignedZeros();
9655 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9656 C, cast<CastInst>(FalseVal)->getOperand(0),
9657 LHS, RHS, Depth);
9658 }
9659 }
9660 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal,
9661 LHS, RHS, Depth);
9662}
9663
9665 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9666 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9667 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9668 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9669 if (SPF == SPF_FMINNUM)
9670 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9671 if (SPF == SPF_FMAXNUM)
9672 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9673 llvm_unreachable("unhandled!");
9674}
9675
9677 switch (SPF) {
9679 return Intrinsic::umin;
9681 return Intrinsic::umax;
9683 return Intrinsic::smin;
9685 return Intrinsic::smax;
9686 default:
9687 llvm_unreachable("Unexpected SPF");
9688 }
9689}
9690
9692 if (SPF == SPF_SMIN) return SPF_SMAX;
9693 if (SPF == SPF_UMIN) return SPF_UMAX;
9694 if (SPF == SPF_SMAX) return SPF_SMIN;
9695 if (SPF == SPF_UMAX) return SPF_UMIN;
9696 llvm_unreachable("unhandled!");
9697}
9698
9700 switch (MinMaxID) {
9701 case Intrinsic::smax: return Intrinsic::smin;
9702 case Intrinsic::smin: return Intrinsic::smax;
9703 case Intrinsic::umax: return Intrinsic::umin;
9704 case Intrinsic::umin: return Intrinsic::umax;
9705 // Please note that next four intrinsics may produce the same result for
9706 // original and inverted case even if X != Y due to NaN is handled specially.
9707 case Intrinsic::maximum: return Intrinsic::minimum;
9708 case Intrinsic::minimum: return Intrinsic::maximum;
9709 case Intrinsic::maxnum: return Intrinsic::minnum;
9710 case Intrinsic::minnum: return Intrinsic::maxnum;
9711 case Intrinsic::maximumnum:
9712 return Intrinsic::minimumnum;
9713 case Intrinsic::minimumnum:
9714 return Intrinsic::maximumnum;
9715 default: llvm_unreachable("Unexpected intrinsic");
9716 }
9717}
9718
9720 switch (SPF) {
9723 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9724 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9725 default: llvm_unreachable("Unexpected flavor");
9726 }
9727}
9728
9729std::pair<Intrinsic::ID, bool>
9731 // Check if VL contains select instructions that can be folded into a min/max
9732 // vector intrinsic and return the intrinsic if it is possible.
9733 // TODO: Support floating point min/max.
9734 bool AllCmpSingleUse = true;
9735 SelectPatternResult SelectPattern;
9736 SelectPattern.Flavor = SPF_UNKNOWN;
9737 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9738 Value *LHS, *RHS;
9739 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9740 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9741 return false;
9742 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9743 SelectPattern.Flavor != CurrentPattern.Flavor)
9744 return false;
9745 SelectPattern = CurrentPattern;
9746 AllCmpSingleUse &=
9748 return true;
9749 })) {
9750 switch (SelectPattern.Flavor) {
9751 case SPF_SMIN:
9752 return {Intrinsic::smin, AllCmpSingleUse};
9753 case SPF_UMIN:
9754 return {Intrinsic::umin, AllCmpSingleUse};
9755 case SPF_SMAX:
9756 return {Intrinsic::smax, AllCmpSingleUse};
9757 case SPF_UMAX:
9758 return {Intrinsic::umax, AllCmpSingleUse};
9759 case SPF_FMAXNUM:
9760 return {Intrinsic::maxnum, AllCmpSingleUse};
9761 case SPF_FMINNUM:
9762 return {Intrinsic::minnum, AllCmpSingleUse};
9763 default:
9764 llvm_unreachable("unexpected select pattern flavor");
9765 }
9766 }
9767 return {Intrinsic::not_intrinsic, false};
9768}
9769
9770template <typename InstTy>
9771static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9772 Value *&Init, Value *&OtherOp) {
9773 // Handle the case of a simple two-predecessor recurrence PHI.
9774 // There's a lot more that could theoretically be done here, but
9775 // this is sufficient to catch some interesting cases.
9776 // TODO: Expand list -- gep, uadd.sat etc.
9777 if (PN->getNumIncomingValues() != 2)
9778 return false;
9779
9780 for (unsigned I = 0; I != 2; ++I) {
9781 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9782 Operation && Operation->getNumOperands() >= 2) {
9783 Value *LHS = Operation->getOperand(0);
9784 Value *RHS = Operation->getOperand(1);
9785 if (LHS != PN && RHS != PN)
9786 continue;
9787
9788 Inst = Operation;
9789 Init = PN->getIncomingValue(!I);
9790 OtherOp = (LHS == PN) ? RHS : LHS;
9791 return true;
9792 }
9793 }
9794 return false;
9795}
9796
9797template <typename InstTy>
9798static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9799 Value *&Init, Value *&OtherOp0,
9800 Value *&OtherOp1) {
9801 if (PN->getNumIncomingValues() != 2)
9802 return false;
9803
9804 for (unsigned I = 0; I != 2; ++I) {
9805 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9806 Operation && Operation->getNumOperands() >= 3) {
9807 Value *Op0 = Operation->getOperand(0);
9808 Value *Op1 = Operation->getOperand(1);
9809 Value *Op2 = Operation->getOperand(2);
9810
9811 if (Op0 != PN && Op1 != PN && Op2 != PN)
9812 continue;
9813
9814 Inst = Operation;
9815 Init = PN->getIncomingValue(!I);
9816 if (Op0 == PN) {
9817 OtherOp0 = Op1;
9818 OtherOp1 = Op2;
9819 } else if (Op1 == PN) {
9820 OtherOp0 = Op0;
9821 OtherOp1 = Op2;
9822 } else {
9823 OtherOp0 = Op0;
9824 OtherOp1 = Op1;
9825 }
9826 return true;
9827 }
9828 }
9829 return false;
9830}
9832 Value *&Start, Value *&Step) {
9833 // We try to match a recurrence of the form:
9834 // %iv = [Start, %entry], [%iv.next, %backedge]
9835 // %iv.next = binop %iv, Step
9836 // Or:
9837 // %iv = [Start, %entry], [%iv.next, %backedge]
9838 // %iv.next = binop Step, %iv
9839 return matchTwoInputRecurrence(P, BO, Start, Step);
9840}
9841
9843 Value *&Start, Value *&Step) {
9844 BinaryOperator *BO = nullptr;
9845 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9846 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9847}
9848
9850 PHINode *&P, Value *&Init,
9851 Value *&OtherOp) {
9852 // Binary intrinsics only supported for now.
9853 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9854 I->getType() != I->getArgOperand(1)->getType())
9855 return false;
9856
9857 IntrinsicInst *II = nullptr;
9858 P = dyn_cast<PHINode>(I->getArgOperand(0));
9859 if (!P)
9860 P = dyn_cast<PHINode>(I->getArgOperand(1));
9861
9862 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9863}
9864
9866 PHINode *&P, Value *&Init,
9867 Value *&OtherOp0,
9868 Value *&OtherOp1) {
9869 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9870 I->getType() != I->getArgOperand(1)->getType() ||
9871 I->getType() != I->getArgOperand(2)->getType())
9872 return false;
9873 IntrinsicInst *II = nullptr;
9874 P = dyn_cast<PHINode>(I->getArgOperand(0));
9875 if (!P) {
9876 P = dyn_cast<PHINode>(I->getArgOperand(1));
9877 if (!P)
9878 P = dyn_cast<PHINode>(I->getArgOperand(2));
9879 }
9880 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9881 II == I;
9882}
9883
9884/// Return true if "icmp Pred LHS RHS" is always true.
9886 const Value *RHS) {
9887 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9888 return true;
9889
9890 switch (Pred) {
9891 default:
9892 return false;
9893
9894 case CmpInst::ICMP_SLE: {
9895 const APInt *C;
9896
9897 // LHS s<= LHS +_{nsw} C if C >= 0
9898 // LHS s<= LHS | C if C >= 0
9899 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9901 return !C->isNegative();
9902
9903 // LHS s<= smax(LHS, V) for any V
9905 return true;
9906
9907 // smin(RHS, V) s<= RHS for any V
9909 return true;
9910
9911 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9912 const Value *X;
9913 const APInt *CLHS, *CRHS;
9914 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9916 return CLHS->sle(*CRHS);
9917
9918 return false;
9919 }
9920
9921 case CmpInst::ICMP_ULE: {
9922 // LHS u<= LHS +_{nuw} V for any V
9923 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9925 return true;
9926
9927 // LHS u<= LHS | V for any V
9928 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9929 return true;
9930
9931 // LHS u<= umax(LHS, V) for any V
9933 return true;
9934
9935 // RHS >> V u<= RHS for any V
9936 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9937 return true;
9938
9939 // RHS u/ C_ugt_1 u<= RHS
9940 const APInt *C;
9941 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9942 return true;
9943
9944 // RHS & V u<= RHS for any V
9946 return true;
9947
9948 // umin(RHS, V) u<= RHS for any V
9950 return true;
9951
9952 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9953 const Value *X;
9954 const APInt *CLHS, *CRHS;
9955 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9957 return CLHS->ule(*CRHS);
9958
9959 return false;
9960 }
9961 }
9962}
9963
9964/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9965/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9966static std::optional<bool>
9968 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9969 switch (Pred) {
9970 default:
9971 return std::nullopt;
9972
9973 case CmpInst::ICMP_SLT:
9974 case CmpInst::ICMP_SLE:
9975 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9977 return true;
9978 return std::nullopt;
9979
9980 case CmpInst::ICMP_SGT:
9981 case CmpInst::ICMP_SGE:
9982 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9984 return true;
9985 return std::nullopt;
9986
9987 case CmpInst::ICMP_ULT:
9988 case CmpInst::ICMP_ULE:
9989 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9991 return true;
9992 return std::nullopt;
9993
9994 case CmpInst::ICMP_UGT:
9995 case CmpInst::ICMP_UGE:
9996 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9998 return true;
9999 return std::nullopt;
10000 }
10001}
10002
10003/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
10004/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
10005/// Otherwise, return std::nullopt if we can't infer anything.
10006static std::optional<bool>
10008 CmpPredicate RPred, const ConstantRange &RCR) {
10009 auto CRImpliesPred = [&](ConstantRange CR,
10010 CmpInst::Predicate Pred) -> std::optional<bool> {
10011 // If all true values for lhs and true for rhs, lhs implies rhs
10012 if (CR.icmp(Pred, RCR))
10013 return true;
10014
10015 // If there is no overlap, lhs implies not rhs
10016 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
10017 return false;
10018
10019 return std::nullopt;
10020 };
10021 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10022 RPred))
10023 return Res;
10024 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
10026 : LPred.dropSameSign();
10028 : RPred.dropSameSign();
10029 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
10030 RPred);
10031 }
10032 return std::nullopt;
10033}
10034
10035/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10036/// is true. Return false if LHS implies RHS is false. Otherwise, return
10037/// std::nullopt if we can't infer anything.
10038static std::optional<bool>
10039isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
10040 CmpPredicate RPred, const Value *R0, const Value *R1,
10041 const DataLayout &DL, bool LHSIsTrue) {
10042 // The rest of the logic assumes the LHS condition is true. If that's not the
10043 // case, invert the predicate to make it so.
10044 if (!LHSIsTrue)
10045 LPred = ICmpInst::getInverseCmpPredicate(LPred);
10046
10047 // We can have non-canonical operands, so try to normalize any common operand
10048 // to L0/R0.
10049 if (L0 == R1) {
10050 std::swap(R0, R1);
10051 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10052 }
10053 if (R0 == L1) {
10054 std::swap(L0, L1);
10055 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10056 }
10057 if (L1 == R1) {
10058 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10059 if (L0 != R0 || match(L0, m_ImmConstant())) {
10060 std::swap(L0, L1);
10061 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10062 std::swap(R0, R1);
10063 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10064 }
10065 }
10066
10067 // See if we can infer anything if operand-0 matches and we have at least one
10068 // constant.
10069 const APInt *Unused;
10070 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10071 // Potential TODO: We could also further use the constant range of L0/R0 to
10072 // further constraint the constant ranges. At the moment this leads to
10073 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10074 // C1` (see discussion: D58633).
10075 SimplifyQuery SQ(DL);
10080
10081 // Even if L1/R1 are not both constant, we can still sometimes deduce
10082 // relationship from a single constant. For example X u> Y implies X != 0.
10083 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10084 return R;
10085 // If both L1/R1 were exact constant ranges and we didn't get anything
10086 // here, we won't be able to deduce this.
10087 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10088 return std::nullopt;
10089 }
10090
10091 // Can we infer anything when the two compares have matching operands?
10092 if (L0 == R0 && L1 == R1)
10093 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10094
10095 // It only really makes sense in the context of signed comparison for "X - Y
10096 // must be positive if X >= Y and no overflow".
10097 // Take SGT as an example: L0:x > L1:y and C >= 0
10098 // ==> R0:(x -nsw y) < R1:(-C) is false
10099 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10100 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10101 SignedLPred == ICmpInst::ICMP_SGE) &&
10102 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10103 if (match(R1, m_NonPositive()) &&
10104 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10105 return false;
10106 }
10107
10108 // Take SLT as an example: L0:x < L1:y and C <= 0
10109 // ==> R0:(x -nsw y) < R1:(-C) is true
10110 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10111 SignedLPred == ICmpInst::ICMP_SLE) &&
10112 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10113 if (match(R1, m_NonNegative()) &&
10114 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10115 return true;
10116 }
10117
10118 // a - b == NonZero -> a != b
10119 // ptrtoint(a) - ptrtoint(b) == NonZero -> a != b
10120 const APInt *L1C;
10121 Value *A, *B;
10122 if (LPred == ICmpInst::ICMP_EQ && ICmpInst::isEquality(RPred) &&
10123 match(L1, m_APInt(L1C)) && !L1C->isZero() &&
10124 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10125 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10130 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10131 }
10132
10133 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10134 if (L0 == R0 &&
10135 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10136 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10137 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10138 return CmpPredicate::getMatching(LPred, RPred).has_value();
10139
10140 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10141 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10142
10143 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10144 // Example: L0 u< 13 => (L0 & 16) == 0
10145 const APInt *LC, *RC, *MaskC;
10146 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10147 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10149 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10150 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10151 return true;
10152 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10153 ConstantRange(*RC)))
10154 return false;
10155 }
10156
10157 return std::nullopt;
10158}
10159
10160/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10161/// is true. Return false if LHS implies RHS is false. Otherwise, return
10162/// std::nullopt if we can't infer anything.
10163static std::optional<bool>
10165 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10166 const DataLayout &DL, bool LHSIsTrue) {
10167 // The rest of the logic assumes the LHS condition is true. If that's not the
10168 // case, invert the predicate to make it so.
10169 if (!LHSIsTrue)
10170 LPred = FCmpInst::getInversePredicate(LPred);
10171
10172 // We can have non-canonical operands, so try to normalize any common operand
10173 // to L0/R0.
10174 if (L0 == R1) {
10175 std::swap(R0, R1);
10176 RPred = FCmpInst::getSwappedPredicate(RPred);
10177 }
10178 if (R0 == L1) {
10179 std::swap(L0, L1);
10180 LPred = FCmpInst::getSwappedPredicate(LPred);
10181 }
10182 if (L1 == R1) {
10183 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10184 if (L0 != R0 || match(L0, m_ImmConstant())) {
10185 std::swap(L0, L1);
10186 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10187 std::swap(R0, R1);
10188 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10189 }
10190 }
10191
10192 // Can we infer anything when the two compares have matching operands?
10193 if (L0 == R0 && L1 == R1) {
10194 if ((LPred & RPred) == LPred)
10195 return true;
10196 if ((LPred & ~RPred) == LPred)
10197 return false;
10198 }
10199
10200 // See if we can infer anything if operand-0 matches and we have at least one
10201 // constant.
10202 const APFloat *L1C, *R1C;
10203 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10204 if (std::optional<ConstantFPRange> DomCR =
10206 if (std::optional<ConstantFPRange> ImpliedCR =
10208 if (ImpliedCR->contains(*DomCR))
10209 return true;
10210 }
10211 if (std::optional<ConstantFPRange> ImpliedCR =
10213 FCmpInst::getInversePredicate(RPred), *R1C)) {
10214 if (ImpliedCR->contains(*DomCR))
10215 return false;
10216 }
10217 }
10218 }
10219
10220 return std::nullopt;
10221}
10222
10223/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10224/// false. Otherwise, return std::nullopt if we can't infer anything. We
10225/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10226/// instruction.
10227static std::optional<bool>
10229 const Value *RHSOp0, const Value *RHSOp1,
10230 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10231 // The LHS must be an 'or', 'and', or a 'select' instruction.
10232 assert((LHS->getOpcode() == Instruction::And ||
10233 LHS->getOpcode() == Instruction::Or ||
10234 LHS->getOpcode() == Instruction::Select) &&
10235 "Expected LHS to be 'and', 'or', or 'select'.");
10236
10237 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10238
10239 // If the result of an 'or' is false, then we know both legs of the 'or' are
10240 // false. Similarly, if the result of an 'and' is true, then we know both
10241 // legs of the 'and' are true.
10242 const Value *ALHS, *ARHS;
10243 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10244 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10245 // FIXME: Make this non-recursion.
10246 if (std::optional<bool> Implication = isImpliedCondition(
10247 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10248 return Implication;
10249 if (std::optional<bool> Implication = isImpliedCondition(
10250 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10251 return Implication;
10252 return std::nullopt;
10253 }
10254 return std::nullopt;
10255}
10256
10257std::optional<bool>
10259 const Value *RHSOp0, const Value *RHSOp1,
10260 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10261 // Bail out when we hit the limit.
10263 return std::nullopt;
10264
10265 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10266 // example.
10267 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10268 return std::nullopt;
10269
10270 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10271 "Expected integer type only!");
10272
10273 // Match not
10274 if (match(LHS, m_Not(m_Value(LHS))))
10275 LHSIsTrue = !LHSIsTrue;
10276
10277 // Both LHS and RHS are icmps.
10278 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10279 CmpPredicate LHSPred;
10280 Value *LHSOp0, *LHSOp1;
10281 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10282 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10283 RHSOp1, DL, LHSIsTrue);
10284 } else {
10285 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10286 "Expected floating point type only!");
10287 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10288 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10289 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10290 DL, LHSIsTrue);
10291 }
10292
10293 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10294 /// the RHS to be an icmp.
10295 /// FIXME: Add support for and/or/select on the RHS.
10296 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10297 if ((LHSI->getOpcode() == Instruction::And ||
10298 LHSI->getOpcode() == Instruction::Or ||
10299 LHSI->getOpcode() == Instruction::Select))
10300 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10301 Depth);
10302 }
10303 return std::nullopt;
10304}
10305
10306std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10307 const DataLayout &DL,
10308 bool LHSIsTrue, unsigned Depth) {
10309 // LHS ==> RHS by definition
10310 if (LHS == RHS)
10311 return LHSIsTrue;
10312
10313 // Match not
10314 bool InvertRHS = false;
10315 if (match(RHS, m_Not(m_Value(RHS)))) {
10316 if (LHS == RHS)
10317 return !LHSIsTrue;
10318 InvertRHS = true;
10319 }
10320
10321 CmpPredicate RHSPred;
10322 Value *RHSOp0, *RHSOp1;
10323 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10324 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10325 LHSIsTrue, Depth))
10326 return InvertRHS ? !*Implied : *Implied;
10327 return std::nullopt;
10328 }
10329 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10330 if (auto Implied = isImpliedCondition(
10331 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10332 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10333 return InvertRHS ? !*Implied : *Implied;
10334 return std::nullopt;
10335 }
10336
10338 return std::nullopt;
10339
10340 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10341 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10342 const Value *RHS1, *RHS2;
10343 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10344 if (std::optional<bool> Imp =
10345 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10346 if (*Imp == true)
10347 return !InvertRHS;
10348 if (std::optional<bool> Imp =
10349 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10350 if (*Imp == true)
10351 return !InvertRHS;
10352 }
10353 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10354 if (std::optional<bool> Imp =
10355 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10356 if (*Imp == false)
10357 return InvertRHS;
10358 if (std::optional<bool> Imp =
10359 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10360 if (*Imp == false)
10361 return InvertRHS;
10362 }
10363
10364 return std::nullopt;
10365}
10366
10367// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10368// condition dominating ContextI or nullptr, if no condition is found.
10369static std::pair<Value *, bool>
10371 if (!ContextI || !ContextI->getParent())
10372 return {nullptr, false};
10373
10374 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10375 // dominator tree (eg, from a SimplifyQuery) instead?
10376 const BasicBlock *ContextBB = ContextI->getParent();
10377 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10378 if (!PredBB)
10379 return {nullptr, false};
10380
10381 // We need a conditional branch in the predecessor.
10382 Value *PredCond;
10383 BasicBlock *TrueBB, *FalseBB;
10384 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10385 return {nullptr, false};
10386
10387 // The branch should get simplified. Don't bother simplifying this condition.
10388 if (TrueBB == FalseBB)
10389 return {nullptr, false};
10390
10391 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10392 "Predecessor block does not point to successor?");
10393
10394 // Is this condition implied by the predecessor condition?
10395 return {PredCond, TrueBB == ContextBB};
10396}
10397
10398std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10399 const Instruction *ContextI,
10400 const DataLayout &DL) {
10401 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10402 auto PredCond = getDomPredecessorCondition(ContextI);
10403 if (PredCond.first)
10404 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10405 return std::nullopt;
10406}
10407
10409 const Value *LHS,
10410 const Value *RHS,
10411 const Instruction *ContextI,
10412 const DataLayout &DL) {
10413 auto PredCond = getDomPredecessorCondition(ContextI);
10414 if (PredCond.first)
10415 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10416 PredCond.second);
10417 return std::nullopt;
10418}
10419
10421 APInt &Upper, const InstrInfoQuery &IIQ,
10422 bool PreferSignedRange) {
10423 unsigned Width = Lower.getBitWidth();
10424 const APInt *C;
10425 switch (BO.getOpcode()) {
10426 case Instruction::Sub:
10427 if (match(BO.getOperand(0), m_APInt(C))) {
10428 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10429 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10430
10431 // If the caller expects a signed compare, then try to use a signed range.
10432 // Otherwise if both no-wraps are set, use the unsigned range because it
10433 // is never larger than the signed range. Example:
10434 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10435 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10436 if (PreferSignedRange && HasNSW && HasNUW)
10437 HasNUW = false;
10438
10439 if (HasNUW) {
10440 // 'sub nuw c, x' produces [0, C].
10441 Upper = *C + 1;
10442 } else if (HasNSW) {
10443 if (C->isNegative()) {
10444 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10446 Upper = *C - APInt::getSignedMaxValue(Width);
10447 } else {
10448 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10449 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10450 Lower = *C - APInt::getSignedMaxValue(Width);
10452 }
10453 }
10454 }
10455 break;
10456 case Instruction::Add:
10457 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10458 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10459 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10460
10461 // If the caller expects a signed compare, then try to use a signed
10462 // range. Otherwise if both no-wraps are set, use the unsigned range
10463 // because it is never larger than the signed range. Example: "add nuw
10464 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10465 if (PreferSignedRange && HasNSW && HasNUW)
10466 HasNUW = false;
10467
10468 if (HasNUW) {
10469 // 'add nuw x, C' produces [C, UINT_MAX].
10470 Lower = *C;
10471 } else if (HasNSW) {
10472 if (C->isNegative()) {
10473 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10475 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10476 } else {
10477 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10478 Lower = APInt::getSignedMinValue(Width) + *C;
10479 Upper = APInt::getSignedMaxValue(Width) + 1;
10480 }
10481 }
10482 }
10483 break;
10484
10485 case Instruction::And:
10486 if (match(BO.getOperand(1), m_APInt(C)))
10487 // 'and x, C' produces [0, C].
10488 Upper = *C + 1;
10489 // X & -X is a power of two or zero. So we can cap the value at max power of
10490 // two.
10491 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10492 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10493 Upper = APInt::getSignedMinValue(Width) + 1;
10494 break;
10495
10496 case Instruction::Or:
10497 if (match(BO.getOperand(1), m_APInt(C)))
10498 // 'or x, C' produces [C, UINT_MAX].
10499 Lower = *C;
10500 break;
10501
10502 case Instruction::AShr:
10503 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10504 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10506 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10507 } else if (match(BO.getOperand(0), m_APInt(C))) {
10508 unsigned ShiftAmount = Width - 1;
10509 if (!C->isZero() && IIQ.isExact(&BO))
10510 ShiftAmount = C->countr_zero();
10511 if (C->isNegative()) {
10512 // 'ashr C, x' produces [C, C >> (Width-1)]
10513 Lower = *C;
10514 Upper = C->ashr(ShiftAmount) + 1;
10515 } else {
10516 // 'ashr C, x' produces [C >> (Width-1), C]
10517 Lower = C->ashr(ShiftAmount);
10518 Upper = *C + 1;
10519 }
10520 }
10521 break;
10522
10523 case Instruction::LShr:
10524 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10525 // 'lshr x, C' produces [0, UINT_MAX >> C].
10526 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10527 } else if (match(BO.getOperand(0), m_APInt(C))) {
10528 // 'lshr C, x' produces [C >> (Width-1), C].
10529 unsigned ShiftAmount = Width - 1;
10530 if (!C->isZero() && IIQ.isExact(&BO))
10531 ShiftAmount = C->countr_zero();
10532 Lower = C->lshr(ShiftAmount);
10533 Upper = *C + 1;
10534 }
10535 break;
10536
10537 case Instruction::Shl:
10538 if (match(BO.getOperand(0), m_APInt(C))) {
10539 if (IIQ.hasNoUnsignedWrap(&BO)) {
10540 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10541 Lower = *C;
10542 Upper = Lower.shl(Lower.countl_zero()) + 1;
10543 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10544 if (C->isNegative()) {
10545 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10546 unsigned ShiftAmount = C->countl_one() - 1;
10547 Lower = C->shl(ShiftAmount);
10548 Upper = *C + 1;
10549 } else {
10550 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10551 unsigned ShiftAmount = C->countl_zero() - 1;
10552 Lower = *C;
10553 Upper = C->shl(ShiftAmount) + 1;
10554 }
10555 } else {
10556 // If lowbit is set, value can never be zero.
10557 if ((*C)[0])
10558 Lower = APInt::getOneBitSet(Width, 0);
10559 // If we are shifting a constant the largest it can be is if the longest
10560 // sequence of consecutive ones is shifted to the highbits (breaking
10561 // ties for which sequence is higher). At the moment we take a liberal
10562 // upper bound on this by just popcounting the constant.
10563 // TODO: There may be a bitwise trick for it longest/highest
10564 // consecutative sequence of ones (naive method is O(Width) loop).
10565 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10566 }
10567 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10568 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10569 }
10570 break;
10571
10572 case Instruction::SDiv:
10573 if (match(BO.getOperand(1), m_APInt(C))) {
10574 APInt IntMin = APInt::getSignedMinValue(Width);
10575 APInt IntMax = APInt::getSignedMaxValue(Width);
10576 if (C->isAllOnes()) {
10577 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10578 // where C != -1 and C != 0 and C != 1
10579 Lower = IntMin + 1;
10580 Upper = IntMax + 1;
10581 } else if (C->countl_zero() < Width - 1) {
10582 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10583 // where C != -1 and C != 0 and C != 1
10584 Lower = IntMin.sdiv(*C);
10585 Upper = IntMax.sdiv(*C);
10586 if (Lower.sgt(Upper))
10588 Upper = Upper + 1;
10589 assert(Upper != Lower && "Upper part of range has wrapped!");
10590 }
10591 } else if (match(BO.getOperand(0), m_APInt(C))) {
10592 if (C->isMinSignedValue()) {
10593 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10594 Lower = *C;
10595 Upper = Lower.lshr(1) + 1;
10596 } else {
10597 // 'sdiv C, x' produces [-|C|, |C|].
10598 Upper = C->abs() + 1;
10599 Lower = (-Upper) + 1;
10600 }
10601 }
10602 break;
10603
10604 case Instruction::UDiv:
10605 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10606 // 'udiv x, C' produces [0, UINT_MAX / C].
10607 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10608 } else if (match(BO.getOperand(0), m_APInt(C))) {
10609 // 'udiv C, x' produces [0, C].
10610 Upper = *C + 1;
10611 }
10612 break;
10613
10614 case Instruction::SRem:
10615 if (match(BO.getOperand(1), m_APInt(C))) {
10616 // 'srem x, C' produces (-|C|, |C|).
10617 Upper = C->abs();
10618 Lower = (-Upper) + 1;
10619 } else if (match(BO.getOperand(0), m_APInt(C))) {
10620 if (C->isNegative()) {
10621 // 'srem -|C|, x' produces [-|C|, 0].
10622 Upper = 1;
10623 Lower = *C;
10624 } else {
10625 // 'srem |C|, x' produces [0, |C|].
10626 Upper = *C + 1;
10627 }
10628 }
10629 break;
10630
10631 case Instruction::URem:
10632 if (match(BO.getOperand(1), m_APInt(C)))
10633 // 'urem x, C' produces [0, C).
10634 Upper = *C;
10635 else if (match(BO.getOperand(0), m_APInt(C)))
10636 // 'urem C, x' produces [0, C].
10637 Upper = *C + 1;
10638 break;
10639
10640 default:
10641 break;
10642 }
10643}
10644
10646 bool UseInstrInfo) {
10647 unsigned Width = II.getType()->getScalarSizeInBits();
10648 const APInt *C;
10649 switch (II.getIntrinsicID()) {
10650 case Intrinsic::ctlz:
10651 case Intrinsic::cttz: {
10652 APInt Upper(Width, Width);
10653 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10654 Upper += 1;
10655 // Maximum of set/clear bits is the bit width.
10657 }
10658 case Intrinsic::ctpop:
10659 // Maximum of set/clear bits is the bit width.
10661 APInt(Width, Width) + 1);
10662 case Intrinsic::uadd_sat:
10663 // uadd.sat(x, C) produces [C, UINT_MAX].
10664 if (match(II.getOperand(0), m_APInt(C)) ||
10665 match(II.getOperand(1), m_APInt(C)))
10667 break;
10668 case Intrinsic::sadd_sat:
10669 if (match(II.getOperand(0), m_APInt(C)) ||
10670 match(II.getOperand(1), m_APInt(C))) {
10671 if (C->isNegative())
10672 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10674 APInt::getSignedMaxValue(Width) + *C +
10675 1);
10676
10677 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10679 APInt::getSignedMaxValue(Width) + 1);
10680 }
10681 break;
10682 case Intrinsic::usub_sat:
10683 // usub.sat(C, x) produces [0, C].
10684 if (match(II.getOperand(0), m_APInt(C)))
10685 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10686
10687 // usub.sat(x, C) produces [0, UINT_MAX - C].
10688 if (match(II.getOperand(1), m_APInt(C)))
10690 APInt::getMaxValue(Width) - *C + 1);
10691 break;
10692 case Intrinsic::ssub_sat:
10693 if (match(II.getOperand(0), m_APInt(C))) {
10694 if (C->isNegative())
10695 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10697 *C - APInt::getSignedMinValue(Width) +
10698 1);
10699
10700 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10702 APInt::getSignedMaxValue(Width) + 1);
10703 } else if (match(II.getOperand(1), m_APInt(C))) {
10704 if (C->isNegative())
10705 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10707 APInt::getSignedMaxValue(Width) + 1);
10708
10709 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10711 APInt::getSignedMaxValue(Width) - *C +
10712 1);
10713 }
10714 break;
10715 case Intrinsic::umin:
10716 case Intrinsic::umax:
10717 case Intrinsic::smin:
10718 case Intrinsic::smax:
10719 if (!match(II.getOperand(0), m_APInt(C)) &&
10720 !match(II.getOperand(1), m_APInt(C)))
10721 break;
10722
10723 switch (II.getIntrinsicID()) {
10724 case Intrinsic::umin:
10725 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10726 case Intrinsic::umax:
10728 case Intrinsic::smin:
10730 *C + 1);
10731 case Intrinsic::smax:
10733 APInt::getSignedMaxValue(Width) + 1);
10734 default:
10735 llvm_unreachable("Must be min/max intrinsic");
10736 }
10737 break;
10738 case Intrinsic::abs:
10739 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10740 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10741 if (match(II.getOperand(1), m_One()))
10743 APInt::getSignedMaxValue(Width) + 1);
10744
10746 APInt::getSignedMinValue(Width) + 1);
10747 case Intrinsic::vscale:
10748 if (!II.getParent() || !II.getFunction())
10749 break;
10750 return getVScaleRange(II.getFunction(), Width);
10751 case Intrinsic::read_register:
10752 case Intrinsic::read_volatile_register: {
10753 const Module *M = II.getModule();
10754 if (!M || !M->getTargetTriple().isRISCV())
10755 break;
10756 if (II.getFunction() && isReadVLENB(II))
10757 return getRISCVVLENBRange(II, Width);
10758 break;
10759 }
10760 default:
10761 break;
10762 }
10763
10764 return ConstantRange::getFull(Width);
10765}
10766
10768 const InstrInfoQuery &IIQ) {
10769 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10770 const Value *LHS = nullptr, *RHS = nullptr;
10772 if (R.Flavor == SPF_UNKNOWN)
10773 return ConstantRange::getFull(BitWidth);
10774
10775 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10776 // If the negation part of the abs (in RHS) has the NSW flag,
10777 // then the result of abs(X) is [0..SIGNED_MAX],
10778 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10779 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10783
10786 }
10787
10788 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10789 // The result of -abs(X) is <= 0.
10791 APInt(BitWidth, 1));
10792 }
10793
10794 const APInt *C;
10795 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10796 return ConstantRange::getFull(BitWidth);
10797
10798 switch (R.Flavor) {
10799 case SPF_UMIN:
10801 case SPF_UMAX:
10803 case SPF_SMIN:
10805 *C + 1);
10806 case SPF_SMAX:
10809 default:
10810 return ConstantRange::getFull(BitWidth);
10811 }
10812}
10813
10815 // The maximum representable value of a half is 65504. For floats the maximum
10816 // value is 3.4e38 which requires roughly 129 bits.
10817 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10818 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10819 return;
10820 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10821 Lower = APInt(BitWidth, -65504, true);
10822 Upper = APInt(BitWidth, 65505);
10823 }
10824
10825 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10826 // For a fptoui the lower limit is left as 0.
10827 Upper = APInt(BitWidth, 65505);
10828 }
10829}
10830
10832 const SimplifyQuery &SQ,
10833 unsigned Depth) {
10834 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10835
10837 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10838
10839 if (auto *C = dyn_cast<Constant>(V))
10840 return C->toConstantRange();
10841
10842 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10843 ConstantRange CR = ConstantRange::getFull(BitWidth);
10844 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10845 APInt Lower = APInt(BitWidth, 0);
10846 APInt Upper = APInt(BitWidth, 0);
10847 // TODO: Return ConstantRange.
10848 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10850 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10852 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10853 ConstantRange CRTrue =
10854 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10855 ConstantRange CRFalse =
10856 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10857 CR = CRTrue.unionWith(CRFalse);
10859 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10860 ConstantRange SrcCR =
10861 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10862 CR = SrcCR.truncate(BitWidth);
10863 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10864 ConstantRange SrcCR =
10865 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10866 CR = SrcCR.zeroExtend(BitWidth);
10867 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10868 ConstantRange SrcCR =
10869 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10870 CR = SrcCR.signExtend(BitWidth);
10871 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10872 APInt Lower = APInt(BitWidth, 0);
10873 APInt Upper = APInt(BitWidth, 0);
10874 // TODO: Return ConstantRange.
10877 } else if (const auto *A = dyn_cast<Argument>(V))
10878 if (std::optional<ConstantRange> Range = A->getRange())
10879 CR = *Range;
10880
10881 if (auto *I = dyn_cast<Instruction>(V)) {
10882 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10884
10885 Value *FrexpSrc;
10886 if (const auto *CB = dyn_cast<CallBase>(V)) {
10887 if (std::optional<ConstantRange> Range = CB->getRange())
10888 CR = CR.intersectWith(*Range);
10890 m_Value(FrexpSrc))))) {
10891 const fltSemantics &FltSem =
10892 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10893 // It should be possible to implement this for any type, but this logic
10894 // only computes the range assuming standard subnormal handling.
10895 if (APFloat::isIEEELikeFP(FltSem)) {
10897 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10898
10899 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10900 // constrain its range when the source can be neither.
10901 if (KnownSrc.isKnownNeverInfOrNaN()) {
10902 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10903
10904 // Offset to find the true minimum exponent value for a denormal.
10905 if (!KnownSrc.isKnownNeverSubnormal())
10906 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10907
10908 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10909
10910 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10912
10913 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10914 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10915
10916 MinExp = std::max(AdjustedMin, MinExp);
10917 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10918 MaxExp);
10919
10921 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10922 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10923 /*isSigned=*/true));
10924 }
10925 }
10926 }
10927 }
10928
10929 if (SQ.CtxI && SQ.AC) {
10930 // Try to restrict the range based on information from assumptions.
10931 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10932 if (!AssumeVH)
10933 continue;
10934 CallInst *I = cast<CallInst>(AssumeVH);
10935 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10936 "Got assumption for the wrong function!");
10937 assert(I->getIntrinsicID() == Intrinsic::assume &&
10938 "must be an assume intrinsic");
10939
10940 if (!isValidAssumeForContext(I, SQ))
10941 continue;
10942 Value *Arg = I->getArgOperand(0);
10943 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10944 // Currently we just use information from comparisons.
10945 if (!Cmp || Cmp->getOperand(0) != V)
10946 continue;
10947 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10948 ConstantRange RHS =
10949 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10950 SQ.getWithInstruction(I), Depth + 1);
10951 CR = CR.intersectWith(
10952 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10953 }
10954 }
10955
10956 return CR;
10957}
10958
10959static void
10961 function_ref<void(Value *)> InsertAffected) {
10962 assert(V != nullptr);
10963 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10964 InsertAffected(V);
10965 } else if (auto *I = dyn_cast<Instruction>(V)) {
10966 InsertAffected(V);
10967
10968 // Peek through unary operators to find the source of the condition.
10969 Value *Op;
10971 m_Trunc(m_Value(Op))))) {
10973 InsertAffected(Op);
10974 }
10975 }
10976}
10977
10979 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10980 auto AddAffected = [&InsertAffected](Value *V) {
10981 addValueAffectedByCondition(V, InsertAffected);
10982 };
10983
10984 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10985 if (IsAssume) {
10986 AddAffected(LHS);
10987 AddAffected(RHS);
10988 } else if (match(RHS, m_Constant()))
10989 AddAffected(LHS);
10990 };
10991
10992 SmallVector<Value *, 8> Worklist;
10994 Worklist.push_back(Cond);
10995 while (!Worklist.empty()) {
10996 Value *V = Worklist.pop_back_val();
10997 if (!Visited.insert(V).second)
10998 continue;
10999
11000 CmpPredicate Pred;
11001 Value *A, *B, *X;
11002
11003 if (IsAssume) {
11004 AddAffected(V);
11005 if (match(V, m_Not(m_Value(X))))
11006 AddAffected(X);
11007 }
11008
11009 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
11010 // assume(A && B) is split to -> assume(A); assume(B);
11011 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
11012 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
11013 // enough information to be worth handling (intersection of information as
11014 // opposed to union).
11015 if (!IsAssume) {
11016 Worklist.push_back(A);
11017 Worklist.push_back(B);
11018 }
11019 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
11020 bool HasRHSC = match(B, m_ConstantInt());
11021 if (ICmpInst::isEquality(Pred)) {
11022 AddAffected(A);
11023 if (IsAssume)
11024 AddAffected(B);
11025 if (HasRHSC) {
11026 Value *Y;
11027 // (X << C) or (X >>_s C) or (X >>_u C).
11028 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
11029 AddAffected(X);
11030 // (X & C) or (X | C).
11031 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11032 match(A, m_Or(m_Value(X), m_Value(Y)))) {
11033 AddAffected(X);
11034 AddAffected(Y);
11035 }
11036 // X - Y
11037 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11038 AddAffected(X);
11039 AddAffected(Y);
11040 }
11041 }
11042 } else {
11043 AddCmpOperands(A, B);
11044 if (HasRHSC) {
11045 // Handle (A + C1) u< C2, which is the canonical form of
11046 // A > C3 && A < C4.
11048 AddAffected(X);
11049
11050 if (ICmpInst::isUnsigned(Pred)) {
11051 Value *Y;
11052 // X & Y u> C -> X >u C && Y >u C
11053 // X | Y u< C -> X u< C && Y u< C
11054 // X nuw+ Y u< C -> X u< C && Y u< C
11055 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11056 match(A, m_Or(m_Value(X), m_Value(Y))) ||
11057 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
11058 AddAffected(X);
11059 AddAffected(Y);
11060 }
11061 // X nuw- Y u> C -> X u> C
11062 if (match(A, m_NUWSub(m_Value(X), m_Value())))
11063 AddAffected(X);
11064 }
11065 }
11066
11067 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11068 // by computeKnownFPClass().
11070 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11071 InsertAffected(X);
11072 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11073 InsertAffected(X);
11074 }
11075 }
11076
11077 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11078 Value *SquareOp = nullptr;
11079 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11080 AddAffected(SquareOp);
11081 };
11082 AddNuwSquareOperand(A);
11083 AddNuwSquareOperand(B);
11084
11085 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11086 AddAffected(X);
11087 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11088 AddCmpOperands(A, B);
11089
11090 // fcmp fneg(x), y
11091 // fcmp fabs(x), y
11092 // fcmp fneg(fabs(x)), y
11093 if (match(A, m_FNeg(m_Value(A))))
11094 AddAffected(A);
11095 if (match(A, m_FAbs(m_Value(A))))
11096 AddAffected(A);
11097
11099 m_Value()))) {
11100 // Handle patterns that computeKnownFPClass() support.
11101 AddAffected(A);
11102 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11103 // Assume is checked here as X is already added above for assumes in
11104 // addValueAffectedByCondition
11105 AddAffected(X);
11106 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11107 // Assume is checked here to avoid issues with ephemeral values
11108 Worklist.push_back(X);
11109 }
11110 }
11111}
11112
11114 // (X >> C) or/add (X & mask(C) != 0)
11115 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11116 if (BO->getOpcode() == Instruction::Add ||
11117 BO->getOpcode() == Instruction::Or) {
11118 const Value *X;
11119 const APInt *C1, *C2;
11120 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11124 m_Zero())))) &&
11125 C2->popcount() == C1->getZExtValue())
11126 return X;
11127 }
11128 }
11129 return nullptr;
11130}
11131
11133 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11134}
11135
11138 unsigned MaxCount, bool AllowUndefOrPoison) {
11141 auto Push = [&](const Value *V) -> bool {
11142 Constant *C;
11143 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11144 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11145 return false;
11146 // Check existence first to avoid unnecessary allocations.
11147 if (Constants.contains(C))
11148 return true;
11149 if (Constants.size() == MaxCount)
11150 return false;
11151 Constants.insert(C);
11152 return true;
11153 }
11154
11155 if (auto *Inst = dyn_cast<Instruction>(V)) {
11156 if (Visited.insert(Inst).second)
11157 Worklist.push_back(Inst);
11158 return true;
11159 }
11160 return false;
11161 };
11162 if (!Push(V))
11163 return false;
11164 while (!Worklist.empty()) {
11165 const Instruction *CurInst = Worklist.pop_back_val();
11166 switch (CurInst->getOpcode()) {
11167 case Instruction::Select:
11168 if (!Push(CurInst->getOperand(1)))
11169 return false;
11170 if (!Push(CurInst->getOperand(2)))
11171 return false;
11172 break;
11173 case Instruction::PHI:
11174 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11175 // Fast path for recurrence PHI.
11176 if (IncomingValue == CurInst)
11177 continue;
11178 if (!Push(IncomingValue))
11179 return false;
11180 }
11181 break;
11182 default:
11183 return false;
11184 }
11185 }
11186 return true;
11187}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
const SmallVectorImpl< MachineOperand > & Cond
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static 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 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 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 SelectPatternResult matchMinMaxOfMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TVal, Value *FVal, unsigned Depth)
Recognize variations of: a < c ?
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, unsigned Depth)
Match non-obvious integer minimum and maximum sequences.
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:362
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:337
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:358
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:333
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:329
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:366
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:354
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:379
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:370
static LLVM_ABI const fltSemantics * getArbitraryFPSemantics(StringRef Format)
Returns the fltSemantics for a given arbitrary FP format string, or nullptr if invalid.
Definition APFloat.cpp:6155
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:266
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:459
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:446
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI 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:43
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:64
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:68
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:200
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h: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)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
@ 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:452
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h: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 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
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.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI 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:244
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI 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 bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
SmallPtrSet< Value *, 4 > AffectedValues
Represents offset+length into a ConstantDataArray.
const ConstantDataArray * Array
ConstantDataArray pointer.
Represent subnormal handling kind for floating point instruction inputs and outputs.
static constexpr DenormalMode getDynamic()
InstrInfoQuery provides an interface to query additional information for instructions like metadata o...
bool isExact(const BinaryOperator *Op) const
MDNode * getMetadata(const Instruction *I, unsigned KindID) const
bool hasNoSignedZeros(const InstT *Op) const
bool hasNoSignedWrap(const InstT *Op) const
bool hasNoUnsignedWrap(const InstT *Op) const
static KnownBits makeConstant(const APInt &C)
Create known bits from a known constant.
Definition KnownBits.h:315
static LLVM_ABI KnownBits sadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.sadd.sat(LHS, RHS)
KnownBits anyextOrTrunc(unsigned BitWidth) const
Return known bits for an "any" extension or truncation of the value we're tracking.
Definition KnownBits.h:190
static LLVM_ABI KnownBits mulhu(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from zero-extended multiply-hi.
unsigned countMinSignBits() const
Returns the number of times the sign bit is replicated into the other bits.
Definition KnownBits.h:269
static LLVM_ABI KnownBits smax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smax(LHS, RHS).
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition KnownBits.h:106
bool isZero() const
Returns true if value is all zero.
Definition KnownBits.h:78
LLVM_ABI KnownBits blsi() const
Compute known bits for X & -X, which has only the lowest bit set of X set.
void makeNonNegative()
Make this value non-negative.
Definition KnownBits.h:125
static LLVM_ABI KnownBits usub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.usub.sat(LHS, RHS)
unsigned countMinLeadingOnes() const
Returns the minimum number of leading one bits.
Definition KnownBits.h:265
unsigned countMinTrailingZeros() const
Returns the minimum number of trailing zero bits.
Definition KnownBits.h:256
static LLVM_ABI KnownBits ashr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for ashr(LHS, RHS).
static LLVM_ABI KnownBits ssub_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.ssub.sat(LHS, RHS)
static LLVM_ABI KnownBits urem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for urem(LHS, RHS).
bool isUnknown() const
Returns true if we don't know any bits.
Definition KnownBits.h:64
unsigned countMaxTrailingZeros() const
Returns the maximum number of trailing zero bits possible.
Definition KnownBits.h:288
LLVM_ABI KnownBits blsmsk() const
Compute known bits for X ^ (X - 1), which has all bits up to and including the lowest set bit of X se...
KnownBits byteSwap() const
Definition KnownBits.h:559
bool hasConflict() const
Returns true if there is conflicting information.
Definition KnownBits.h:51
static LLVM_ABI KnownBits fshl(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshl(LHS, RHS, Amt).
unsigned countMaxPopulation() const
Returns the maximum number of bits that could be one.
Definition KnownBits.h:303
void setAllZero()
Make all bits known to be zero and discard any previous information.
Definition KnownBits.h:84
KnownBits reverseBits() const
Definition KnownBits.h:563
unsigned getBitWidth() const
Get the bit width of this value.
Definition KnownBits.h:44
static LLVM_ABI KnownBits umax(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umax(LHS, RHS).
KnownBits zext(unsigned BitWidth) const
Return known bits for a zero extension of the value we're tracking.
Definition KnownBits.h:176
bool isConstant() const
Returns true if we know the value of all bits.
Definition KnownBits.h:54
static KnownBits add(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false, bool SelfAdd=false)
Compute knownbits resulting from addition of LHS and RHS.
Definition KnownBits.h:361
KnownBits unionWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for either this or RHS or both.
Definition KnownBits.h:335
static LLVM_ABI KnownBits lshr(const KnownBits &LHS, const KnownBits &RHS, bool ShAmtNonZero=false, bool Exact=false)
Compute known bits for lshr(LHS, RHS).
bool isNonZero() const
Returns true if this value is known to be non-zero.
Definition KnownBits.h:109
bool isEven() const
Return if the value is known even (the low bit is 0).
Definition KnownBits.h:162
KnownBits extractBits(unsigned NumBits, unsigned BitPosition) const
Return a subset of the known bits from [bitPosition,bitPosition+numBits).
Definition KnownBits.h:239
static LLVM_ABI KnownBits pdep(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pdep(Val, Mask).
KnownBits intersectWith(const KnownBits &RHS) const
Returns KnownBits information that is known to be true for both this and RHS.
Definition KnownBits.h:325
unsigned countMinTrailingOnes() const
Returns the minimum number of trailing one bits.
Definition KnownBits.h:259
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
static LLVM_ABI KnownBits fshr(const KnownBits &LHS, const KnownBits &RHS, const APInt &Amt)
Compute known bits for fshr(LHS, RHS, Amt).
static LLVM_ABI KnownBits smin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for smin(LHS, RHS).
static LLVM_ABI KnownBits mulhs(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits from sign-extended multiply-hi.
static LLVM_ABI KnownBits srem(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for srem(LHS, RHS).
static LLVM_ABI KnownBits udiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for udiv(LHS, RHS).
APInt getMinValue() const
Return the minimal unsigned value possible given these KnownBits.
Definition KnownBits.h:130
static LLVM_ABI KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits &LHS, const KnownBits &RHS)
Compute known bits resulting from adding LHS and RHS.
Definition KnownBits.cpp:61
static LLVM_ABI KnownBits sdiv(const KnownBits &LHS, const KnownBits &RHS, bool Exact=false)
Compute known bits for sdiv(LHS, RHS).
static bool haveNoCommonBitsSet(const KnownBits &LHS, const KnownBits &RHS)
Return true if LHS and RHS have no common bits set.
Definition KnownBits.h:340
bool isNegative() const
Returns true if this value is known to be negative.
Definition KnownBits.h:103
static KnownBits sub(const KnownBits &LHS, const KnownBits &RHS, bool NSW=false, bool NUW=false)
Compute knownbits resulting from subtraction of LHS and RHS.
Definition KnownBits.h:376
unsigned countMaxLeadingZeros() const
Returns the maximum number of leading zero bits possible.
Definition KnownBits.h:294
void setAllOnes()
Make all bits known to be one and discard any previous information.
Definition KnownBits.h:90
static LLVM_ABI KnownBits uadd_sat(const KnownBits &LHS, const KnownBits &RHS)
Compute knownbits resulting from llvm.uadd.sat(LHS, RHS)
static LLVM_ABI KnownBits mul(const KnownBits &LHS, const KnownBits &RHS, bool NoUndefSelfMultiply=false)
Compute known bits resulting from multiplying LHS and RHS.
KnownBits anyext(unsigned BitWidth) const
Return known bits for an "any" extension of the value we're tracking, where we don't know anything ab...
Definition KnownBits.h:171
static LLVM_ABI KnownBits clmul(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for clmul(LHS, RHS).
LLVM_ABI KnownBits abs(bool IntMinIsPoison=false) const
Compute known bits for the absolute value.
static LLVM_ABI std::optional< bool > sgt(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_SGT result.
static LLVM_ABI std::optional< bool > uge(const KnownBits &LHS, const KnownBits &RHS)
Determine if these known bits always give the same ICMP_UGE result.
static LLVM_ABI KnownBits shl(const KnownBits &LHS, const KnownBits &RHS, bool NUW=false, bool NSW=false, bool ShAmtNonZero=false)
Compute known bits for shl(LHS, RHS).
static LLVM_ABI KnownBits umin(const KnownBits &LHS, const KnownBits &RHS)
Compute known bits for umin(LHS, RHS).
static LLVM_ABI KnownBits pext(const KnownBits &Val, const KnownBits &Mask)
Compute known bits for pext(Val, Mask).
KnownBits sextOrTrunc(unsigned BitWidth) const
Return known bits for a sign extension or truncation of the value we're tracking.
Definition KnownBits.h:210
bool isKnownNeverInfOrNaN() const
Return true if it's known this can never be an infinity or nan.
static LLVM_ABI KnownFPClass sin(const KnownFPClass &Src)
Report known values for sin.
static LLVM_ABI KnownFPClass frem(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem.
static LLVM_ABI KnownFPClass fdiv_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv x, x.
static constexpr FPClassTest OrderedLessThanZeroMask
void knownNot(FPClassTest RuleOut)
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass 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())
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
bool isKnownNever(FPClassTest Mask) const
Return true if it's known this can never be one of the mask entries.
std::optional< bool > getSignBit() const
std::nullopt if the sign bit is unknown, true if the sign bit is definitely set or false if the sign ...
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy)
Propagate known class for fpext.
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc)
Propagate known class for fptrunc.
bool cannotBeOrderedLessThanZero() const
Return true if we can prove that the analyzed floating-point value is either NaN or never less than -...
void signBitMustBeOne()
Assume the sign bit is one.
void signBitMustBeZero()
Assume the sign bit is zero.
static LLVM_ABI KnownFPClass sqrt(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for sqrt.
LLVM_ABI bool isKnownNeverLogicalPosZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a positive zero.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass 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 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 roundToIntegral(const KnownFPClass &Src, bool IsTrunc, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for rounding intrinsics (trunc, floor, ceil, rint, nearbyint,...
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 InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041