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 const SimplifyQuery &SQ, unsigned Depth) {
312 if (auto *CI = dyn_cast<ConstantInt>(V.getValue()))
313 return CI->getValue().isStrictlyPositive();
314
315 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
316 // this updated.
317 KnownBits Known = Depth == 0 ? V.getKnownBits(SQ)
318 : computeKnownBits(V.getValue(), SQ, Depth);
319 return Known.isNonNegative() &&
320 (Known.isNonZero() || isKnownNonZero(V.getValue(), SQ, Depth));
321}
322
324 const SimplifyQuery &SQ, unsigned Depth) {
325 if (Depth == 0)
326 return V.getKnownBits(SQ).isNegative();
327 return computeKnownBits(V.getValue(), SQ, Depth).isNegative();
328}
329
330static bool isKnownNonEqual(const Value *V1, const Value *V2,
331 const APInt &DemandedElts, const SimplifyQuery &Q,
332 unsigned Depth);
333
334static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
335 const Value *RHS);
336
337bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
338 const SimplifyQuery &Q, unsigned Depth) {
339 // We don't support looking through casts.
340 if (V1 == V2 || V1->getType() != V2->getType())
341 return false;
342 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
343 APInt DemandedElts =
344 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
345 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
346}
347
348bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
349 const SimplifyQuery &SQ, unsigned Depth) {
350 KnownBits Known(Mask.getBitWidth());
352 return Mask.isSubsetOf(Known.Zero);
353}
354
355static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
356 const SimplifyQuery &Q, unsigned Depth);
357
358static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
359 unsigned Depth = 0) {
360 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
361 APInt DemandedElts =
362 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
363 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
364}
365
366unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
367 AssumptionCache *AC, const Instruction *CtxI,
368 const DominatorTree *DT, bool UseInstrInfo,
369 unsigned Depth) {
370 return ::ComputeNumSignBits(
371 V, SimplifyQuery(DL, DT, AC, safeCtxI(V, CtxI), UseInstrInfo), Depth);
372}
373
375 AssumptionCache *AC,
376 const Instruction *CtxI,
377 const DominatorTree *DT,
378 unsigned Depth) {
379 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CtxI, DT, Depth);
380 return V->getType()->getScalarSizeInBits() - SignBits + 1;
381}
382
383/// Try to detect the lerp pattern: a * (b - c) + c * d
384/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
385///
386/// In that particular case, we can use the following chain of reasoning:
387///
388/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
389///
390/// Since that is true for arbitrary a, b, c and d within our constraints, we
391/// can conclude that:
392///
393/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
394///
395/// Considering that any result of the lerp would be less or equal to U, it
396/// would have at least the number of leading 0s as in U.
397///
398/// While being quite a specific situation, it is fairly common in computer
399/// graphics in the shape of alpha blending.
400///
401/// Modifies given KnownOut in-place with the inferred information.
402static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
403 const APInt &DemandedElts,
404 KnownBits &KnownOut,
405 const SimplifyQuery &Q,
406 unsigned Depth) {
407
408 Type *Ty = Op0->getType();
409 const unsigned BitWidth = Ty->getScalarSizeInBits();
410
411 // Only handle scalar types for now
412 if (Ty->isVectorTy())
413 return;
414
415 // Try to match: a * (b - c) + c * d.
416 // When a == 1 => A == nullptr, the same applies to d/D as well.
417 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
418 const Instruction *SubBC = nullptr;
419
420 const auto MatchSubBC = [&]() {
421 // (b - c) can have two forms that interest us:
422 //
423 // 1. sub nuw %b, %c
424 // 2. xor %c, %b
425 //
426 // For the first case, nuw flag guarantees our requirement b >= c.
427 //
428 // The second case might happen when the analysis can infer that b is a mask
429 // for c and we can transform sub operation into xor (that is usually true
430 // for constant b's). Even though xor is symmetrical, canonicalization
431 // ensures that the constant will be the RHS. We have additional checks
432 // later on to ensure that this xor operation is equivalent to subtraction.
434 m_Xor(m_Value(C), m_Value(B))));
435 };
436
437 const auto MatchASubBC = [&]() {
438 // Cases:
439 // - a * (b - c)
440 // - (b - c) * a
441 // - (b - c) <- a implicitly equals 1
442 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
443 };
444
445 const auto MatchCD = [&]() {
446 // Cases:
447 // - d * c
448 // - c * d
449 // - c <- d implicitly equals 1
451 };
452
453 const auto Match = [&](const Value *LHS, const Value *RHS) {
454 // We do use m_Specific(C) in MatchCD, so we have to make sure that
455 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
456 // has to evaluate first and return true.
457 //
458 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
459 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
460 };
461
462 if (!Match(Op0, Op1) && !Match(Op1, Op0))
463 return;
464
465 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
466 // For some of the values we use the convention of leaving
467 // it nullptr to signify an implicit constant 1.
468 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
470 };
471
472 // Check that all operands are non-negative
473 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
474 if (!KnownA.isNonNegative())
475 return;
476
477 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
478 if (!KnownD.isNonNegative())
479 return;
480
481 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
482 if (!KnownB.isNonNegative())
483 return;
484
485 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
486 if (!KnownC.isNonNegative())
487 return;
488
489 // If we matched subtraction as xor, we need to actually check that xor
490 // is semantically equivalent to subtraction.
491 //
492 // For that to be true, b has to be a mask for c or that b's known
493 // ones cover all known and possible ones of c.
494 if (SubBC->getOpcode() == Instruction::Xor &&
495 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
496 return;
497
498 const APInt MaxA = KnownA.getMaxValue();
499 const APInt MaxD = KnownD.getMaxValue();
500 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
501 const APInt MaxB = KnownB.getMaxValue();
502
503 // We can't infer leading zeros info if the upper-bound estimate wraps.
504 bool Overflow;
505 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
506
507 if (Overflow)
508 return;
509
510 // If we know that x <= y and both are positive than x has at least the same
511 // number of leading zeros as y.
512 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
513 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
514}
515
516static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
517 bool NSW, bool NUW,
518 const APInt &DemandedElts,
519 KnownBits &KnownOut, KnownBits &Known2,
520 const SimplifyQuery &Q, unsigned Depth) {
521 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
522
523 // If one operand is unknown and we have no nowrap information,
524 // the result will be unknown independently of the second operand.
525 if (KnownOut.isUnknown() && !NSW && !NUW)
526 return;
527
528 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
529 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
530
531 if (!Add && NSW && !KnownOut.isNonNegative() &&
533 .value_or(false) ||
534 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
535 KnownOut.makeNonNegative();
536
537 if (Add)
538 // Try to match lerp pattern and combine results
539 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
540}
541
542static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
543 bool NUW, const APInt &DemandedElts,
544 KnownBits &Known, KnownBits &Known2,
545 const SimplifyQuery &Q, unsigned Depth) {
546 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
547 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
548
549 bool isKnownNegative = false;
550 bool isKnownNonNegative = false;
551 // If the multiplication is known not to overflow, compute the sign bit.
552 if (NSW) {
553 if (Op0 == Op1) {
554 // The product of a number with itself is non-negative.
555 isKnownNonNegative = true;
556 } else {
557 bool isKnownNonNegativeOp1 = Known.isNonNegative();
558 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
559 bool isKnownNegativeOp1 = Known.isNegative();
560 bool isKnownNegativeOp0 = Known2.isNegative();
561 // The product of two numbers with the same sign is non-negative.
562 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
563 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
564 if (!isKnownNonNegative && NUW) {
565 // mul nuw nsw with a factor > 1 is non-negative.
566 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
567 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
568 KnownBits::sgt(Known2, One).value_or(false);
569 }
570
571 // The product of a negative number and a non-negative number is either
572 // negative or zero.
575 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
576 Known2.isNonZero()) ||
577 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
578 }
579 }
580
581 bool SelfMultiply = Op0 == Op1;
582 if (SelfMultiply)
583 SelfMultiply &=
584 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CtxI, Q.DT, Depth + 1);
585 Known = KnownBits::mul(Known, Known2, SelfMultiply);
586
587 if (SelfMultiply) {
588 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
589 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
590 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
591
592 if (OutValidBits < TyBits) {
593 APInt KnownZeroMask =
594 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
595 Known.Zero |= KnownZeroMask;
596 }
597 }
598
599 // Only make use of no-wrap flags if we failed to compute the sign bit
600 // directly. This matters if the multiplication always overflows, in
601 // which case we prefer to follow the result of the direct computation,
602 // though as the program is invoking undefined behaviour we can choose
603 // whatever we like here.
604 if (isKnownNonNegative && !Known.isNegative())
605 Known.makeNonNegative();
606 else if (isKnownNegative && !Known.isNonNegative())
607 Known.makeNegative();
608}
609
611 KnownBits &Known) {
612 unsigned BitWidth = Known.getBitWidth();
613 unsigned NumRanges = Ranges.getNumOperands() / 2;
614 assert(NumRanges >= 1);
615
616 Known.setAllConflict();
617
618 for (unsigned i = 0; i < NumRanges; ++i) {
620 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
622 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
623 ConstantRange Range(Lower->getValue(), Upper->getValue());
624 // BitWidth must equal the Ranges BitWidth for the correct number of high
625 // bits to be set.
626 assert(BitWidth == Range.getBitWidth() &&
627 "Known bit width must match range bit width!");
628
629 // The first CommonPrefixBits of all values in Range are equal.
630 unsigned CommonPrefixBits =
631 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
632 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
633 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
634 Known.One &= UnsignedMax & Mask;
635 Known.Zero &= ~UnsignedMax & Mask;
636 }
637}
638
639static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
640 // The instruction defining an assumption's condition itself is always
641 // considered ephemeral to that assumption (even if it has other
642 // non-ephemeral users). See r246696's test case for an example.
643 if (is_contained(I->operands(), E))
644 return true;
645
646 const auto *EI = dyn_cast<Instruction>(E);
647 if (!EI)
648 return false;
649
650 if (EI == I)
651 return true;
652
655 Visited.insert(EI);
656 WorkList.push_back(EI);
657 bool ReachesI = false;
658 while (!WorkList.empty()) {
659 const Instruction *V = WorkList.pop_back_val();
660 for (const User *U : V->users()) {
661 const auto *UI = cast<Instruction>(U);
662 if (UI == I) {
663 ReachesI = true;
664 continue;
665 }
666 if (UI->mayHaveSideEffects() || UI->isTerminator())
667 return false;
668 if (Visited.insert(UI).second)
669 WorkList.push_back(UI);
670 }
671 }
672 return ReachesI;
673}
674
675// Is this an intrinsic that cannot be speculated but also cannot trap?
677 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
678 return CI->isAssumeLikeIntrinsic();
679
680 return false;
681}
682
684 const Instruction *CtxI,
685 const DominatorTree *DT,
686 bool AllowEphemerals) {
687 // There are two restrictions on the use of an assume:
688 // 1. The assume must dominate the context (or the control flow must
689 // reach the assume whenever it reaches the context).
690 // 2. The context must not be in the assume's set of ephemeral values
691 // (otherwise we will use the assume to prove that the condition
692 // feeding the assume is trivially true, thus causing the removal of
693 // the assume).
694
695 if (Inv->getParent() == CtxI->getParent()) {
696 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
697 // in the BB.
698 if (Inv->comesBefore(CtxI))
699 return true;
700
701 // Don't let an assume affect itself - this would cause the problems
702 // `isEphemeralValueOf` is trying to prevent, and it would also make
703 // the loop below go out of bounds.
704 if (!AllowEphemerals && Inv == CtxI)
705 return false;
706
707 // The context comes first, but they're both in the same block.
708 // Make sure there is nothing in between that might interrupt
709 // the control flow, not even CtxI itself.
710 // We limit the scan distance between the assume and its context instruction
711 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
712 // it can be adjusted if needed (could be turned into a cl::opt).
713 auto Range = make_range(CtxI->getIterator(), Inv->getIterator());
715 return false;
716
717 return AllowEphemerals || !isEphemeralValueOf(Inv, CtxI);
718 }
719
720 // Inv and CtxI are in different blocks.
721 if (DT) {
722 if (DT->dominates(Inv, CtxI))
723 return true;
724 } else if (Inv->getParent() == CtxI->getParent()->getSinglePredecessor() ||
725 Inv->getParent()->isEntryBlock()) {
726 // We don't have a DT, but this trivially dominates.
727 return true;
728 }
729
730 return false;
731}
732
735 unsigned &NumChecked) {
736 for (const Instruction &I : make_range(Begin, End)) {
737 if (NumChecked++ > MaxInstrsToCheckForFree)
738 return false;
739 if (auto *CB = dyn_cast<CallBase>(&I)) {
740 if (!CB->hasFnAttr(Attribute::NoFree))
741 return false;
742 } else if (I.maySynchronize()) {
743 return false;
744 }
745 }
746 return true;
747}
748
750 const Instruction *CtxI,
751 const DominatorTree *DT) {
752 const BasicBlock *CtxBB = CtxI->getParent();
753 const BasicBlock *AssumeBB = Assume->getParent();
754 unsigned NumChecked = 0;
755 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
756 if (CtxBB == AssumeBB) {
757 if (Assume != CtxI && !Assume->comesBefore(CtxI))
758 return false;
759 return hasNoFreeInRange(Assume->getIterator(), CtxIter, NumChecked);
760 }
761 if (DT && !DT->dominates(Assume, CtxI))
762 return false;
763 if (!hasNoFreeInRange(CtxBB->begin(), CtxIter, NumChecked))
764 return false;
765 if (pred_empty(CtxBB))
766 return false;
767
768 // Note: CtxBB is NOT pre-inserted into Visited to ensure that loop
769 // backedges returning to CtxBB are enqueued and checked correctly.
772 while (!Worklist.empty()) {
773 const BasicBlock *CurBB = Worklist.pop_back_val();
774 if (!Visited.insert(CurBB).second)
775 continue;
776
777 if (CurBB == AssumeBB) {
778 if (!hasNoFreeInRange(Assume->getIterator(), AssumeBB->end(), NumChecked))
779 return false;
780 continue;
781 }
782 assert((!DT || DT->dominates(AssumeBB, CurBB)) &&
783 "Blocks between Assume and CtxI must be dominated by AssumeBB");
784
785 if (pred_empty(CurBB))
786 return false;
787
788 // If CurBB == CtxBB (due to a loop backedge targeting CtxBB), check
789 // instructions from CtxIter to the end of CtxBB (instructions before
790 // CtxIter were checked above). Otherwise, check the entire block.
791 auto StartIt = (CurBB == CtxBB) ? CtxIter : CurBB->begin();
792 if (!hasNoFreeInRange(StartIt, CurBB->end(), NumChecked))
793 return false;
794 append_range(Worklist, predecessors(CurBB));
795 }
796 return true;
797}
798
799// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
800// we still have enough information about `RHS` to conclude non-zero. For
801// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
802// so the extra compile time may not be worth it, but possibly a second API
803// should be created for use outside of loops.
804static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
805 // v u> y implies v != 0.
806 if (Pred == ICmpInst::ICMP_UGT)
807 return true;
808
809 // Special-case v != 0 to also handle v != null.
810 if (Pred == ICmpInst::ICMP_NE)
811 return match(RHS, m_Zero());
812
813 // All other predicates - rely on generic ConstantRange handling.
814 const APInt *C;
815 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
816 if (match(RHS, m_APInt(C))) {
818 return !TrueValues.contains(Zero);
819 }
820
822 if (VC == nullptr)
823 return false;
824
825 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
826 ++ElemIdx) {
828 Pred, VC->getElementAsAPInt(ElemIdx));
829 if (TrueValues.contains(Zero))
830 return false;
831 }
832 return true;
833}
834
835static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
836 Value *&ValOut, Instruction *&CtxIOut,
837 const PHINode **PhiOut = nullptr) {
838 ValOut = U->get();
839 if (ValOut == PHI)
840 return;
841 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
842 if (PhiOut)
843 *PhiOut = PHI;
844 Value *V;
845 // If the Use is a select of this phi, compute analysis on other arm to break
846 // recursion.
847 // TODO: Min/Max
848 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
849 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
850 ValOut = V;
851
852 // Same for select, if this phi is 2-operand phi, compute analysis on other
853 // incoming value to break recursion.
854 // TODO: We could handle any number of incoming edges as long as we only have
855 // two unique values.
856 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
857 IncPhi && IncPhi->getNumIncomingValues() == 2) {
858 for (int Idx = 0; Idx < 2; ++Idx) {
859 if (IncPhi->getIncomingValue(Idx) == PHI) {
860 ValOut = IncPhi->getIncomingValue(1 - Idx);
861 if (PhiOut)
862 *PhiOut = IncPhi;
863 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
864 break;
865 }
866 }
867 }
868}
869
870static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
871 // Use of assumptions is context-sensitive. If we don't have a context, we
872 // cannot use them!
873 if (!Q.AC || !Q.CtxI)
874 return false;
875
876 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
877 if (!Elem.Assume)
878 continue;
879
880 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
881 assert(I->getFunction() == Q.CtxI->getFunction() &&
882 "Got assumption for the wrong function!");
883
884 if (Elem.Index != AssumptionCache::ExprResultIdx) {
886 I->getOperandBundleAt(Elem.Index)) &&
888 return true;
889 continue;
890 }
891
892 // Warning: This loop can end up being somewhat performance sensitive.
893 // We're running this loop for once for each value queried resulting in a
894 // runtime of ~O(#assumes * #values).
895
896 if (match(I->getArgOperand(0), m_Trunc(m_Specific(V))) &&
898 return true;
899
900 Value *RHS;
901 CmpPredicate Pred;
902 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
903 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
904 continue;
905
907 return true;
908 }
909
910 return false;
911}
912
915 const SimplifyQuery &Q) {
916 if (RHS->getType()->isPointerTy()) {
917 // Handle comparison of pointer to null explicitly, as it will not be
918 // covered by the m_APInt() logic below.
919 if (LHS == V && match(RHS, m_Zero())) {
920 switch (Pred) {
922 Known.setAllZero();
923 break;
926 Known.makeNonNegative();
927 break;
929 Known.makeNegative();
930 break;
931 default:
932 break;
933 }
934 }
935 return;
936 }
937
938 unsigned BitWidth = Known.getBitWidth();
939 auto m_V =
941
942 Value *Y;
943 const APInt *Mask, *C;
944 if (!match(RHS, m_APInt(C)))
945 return;
946
947 uint64_t ShAmt;
948 switch (Pred) {
950 // assume(V = C)
951 if (match(LHS, m_V)) {
952 Known = Known.unionWith(KnownBits::makeConstant(*C));
953 // assume(V & Mask = C)
954 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
955 // For one bits in Mask, we can propagate bits from C to V.
956 Known.One |= *C;
957 if (match(Y, m_APInt(Mask)))
958 Known.Zero |= ~*C & *Mask;
959 // assume(V | Mask = C)
960 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
961 // For zero bits in Mask, we can propagate bits from C to V.
962 Known.Zero |= ~*C;
963 if (match(Y, m_APInt(Mask)))
964 Known.One |= *C & ~*Mask;
965 // assume(V << ShAmt = C)
966 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
967 ShAmt < BitWidth) {
968 // For those bits in C that are known, we can propagate them to known
969 // bits in V shifted to the right by ShAmt.
971 RHSKnown >>= ShAmt;
972 Known = Known.unionWith(RHSKnown);
973 // assume(V >> ShAmt = C)
974 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
975 ShAmt < BitWidth) {
976 // For those bits in RHS that are known, we can propagate them to known
977 // bits in V shifted to the right by C.
979 RHSKnown <<= ShAmt;
980 Known = Known.unionWith(RHSKnown);
981 }
982 break;
983 case ICmpInst::ICMP_NE: {
984 // assume (V & B != 0) where B is a power of 2
985 const APInt *BPow2;
986 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
987 Known.One |= *BPow2;
988 break;
989 }
990 default: {
991 const APInt *Offset = nullptr;
992 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
994 if (Offset)
995 LHSRange = LHSRange.sub(*Offset);
996 Known = Known.unionWith(LHSRange.toKnownBits());
997 }
998 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
999 // X & Y u> C -> X u> C && Y u> C
1000 // X nuw- Y u> C -> X u> C
1001 if (match(LHS, m_c_And(m_V, m_Value())) ||
1002 match(LHS, m_NUWSub(m_V, m_Value())))
1003 Known.One.setHighBits(
1004 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
1005 }
1006 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
1007 // X | Y u< C -> X u< C && Y u< C
1008 // X nuw+ Y u< C -> X u< C && Y u< C
1009 if (match(LHS, m_c_Or(m_V, m_Value())) ||
1010 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
1011 Known.Zero.setHighBits(
1012 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
1013 }
1014 }
1015 } break;
1016 }
1017}
1018
1021 const SimplifyQuery &SQ, bool Invert) {
1022 ICmpInst::Predicate Pred =
1023 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1024 Value *LHS = Cmp->getOperand(0);
1025 Value *RHS = Cmp->getOperand(1);
1026
1027 // Handle icmp pred (trunc V), C
1028 if (match(LHS, m_Trunc(m_Specific(V)))) {
1029 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1030 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1032 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1033 else
1034 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1035 return;
1036 }
1037
1038 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1039}
1040
1042 KnownBits &Known, const SimplifyQuery &SQ,
1043 bool Invert, unsigned Depth) {
1044 Value *A, *B;
1047 KnownBits Known2(Known.getBitWidth());
1048 KnownBits Known3(Known.getBitWidth());
1049 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1050 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1051 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1053 Known2 = Known2.unionWith(Known3);
1054 else
1055 Known2 = Known2.intersectWith(Known3);
1056 Known = Known.unionWith(Known2);
1057 return;
1058 }
1059
1060 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1061 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1062 return;
1063 }
1064
1065 if (match(Cond, m_Trunc(m_Specific(V)))) {
1066 KnownBits DstKnown(1);
1067 if (Invert) {
1068 DstKnown.setAllZero();
1069 } else {
1070 DstKnown.setAllOnes();
1071 }
1073 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1074 return;
1075 }
1076 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1077 return;
1078 }
1079
1081 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1082}
1083
1085 const SimplifyQuery &Q, unsigned Depth) {
1086 // Handle injected condition.
1087 if (Q.CC && Q.CC->AffectedValues.contains(V))
1089
1090 if (!Q.CtxI)
1091 return;
1092
1093 if (Q.DC && Q.DT) {
1094 // Handle dominating conditions.
1095 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1096 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1097 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
1098 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1099 /*Invert*/ false, Depth);
1100
1101 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1102 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
1103 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1104 /*Invert*/ true, Depth);
1105 }
1106
1107 if (Known.hasConflict())
1108 Known.resetAll();
1109 }
1110
1111 if (!Q.AC)
1112 return;
1113
1114 unsigned BitWidth = Known.getBitWidth();
1115
1116 // Note that the patterns below need to be kept in sync with the code
1117 // in AssumptionCache::updateAffectedValues.
1118
1119 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1120 if (!Elem.Assume)
1121 continue;
1122
1123 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1124 assert(I->getParent()->getParent() == Q.CtxI->getParent()->getParent() &&
1125 "Got assumption for the wrong function!");
1126
1127 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1128 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1129 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1130 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1131 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1133 Known.Zero |= (*Alignment - 1) & ~*Offset;
1134 Known.One |= (*Alignment - 1) & *Offset;
1135 }
1136 }
1137 continue;
1138 }
1139
1140 // Warning: This loop can end up being somewhat performance sensitive.
1141 // We're running this loop for once for each value queried resulting in a
1142 // runtime of ~O(#assumes * #values).
1143
1144 Value *Arg = I->getArgOperand(0);
1145
1146 if (Arg == V && isValidAssumeForContext(I, Q)) {
1147 assert(BitWidth == 1 && "assume operand is not i1?");
1148 (void)BitWidth;
1149 Known.setAllOnes();
1150 return;
1151 }
1152 if (match(Arg, m_Not(m_Specific(V))) &&
1154 assert(BitWidth == 1 && "assume operand is not i1?");
1155 (void)BitWidth;
1156 Known.setAllZero();
1157 return;
1158 }
1159 auto *Trunc = dyn_cast<TruncInst>(Arg);
1160 if (Trunc && Trunc->getOperand(0) == V &&
1162 if (Trunc->hasNoUnsignedWrap()) {
1164 return;
1165 }
1166 Known.One.setBit(0);
1167 return;
1168 }
1169
1170 // The remaining tests are all recursive, so bail out if we hit the limit.
1172 continue;
1173
1174 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1175 if (!Cmp)
1176 continue;
1177
1178 if (!isValidAssumeForContext(I, Q))
1179 continue;
1180
1181 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1182 }
1183
1184 // Conflicting assumption: Undefined behavior will occur on this execution
1185 // path.
1186 if (Known.hasConflict())
1187 Known.resetAll();
1188}
1189
1190/// Compute known bits from a shift operator, including those with a
1191/// non-constant shift amount. Known is the output of this function. Known2 is a
1192/// pre-allocated temporary with the same bit width as Known and on return
1193/// contains the known bit of the shift value source. KF is an
1194/// operator-specific function that, given the known-bits and a shift amount,
1195/// compute the implied known-bits of the shift operator's result respectively
1196/// for that shift amount. The results from calling KF are conservatively
1197/// combined for all permitted shift amounts.
1199 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1200 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1201 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1202 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1203 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1204 // To limit compile-time impact, only query isKnownNonZero() if we know at
1205 // least something about the shift amount.
1206 bool ShAmtNonZero =
1207 Known.isNonZero() ||
1208 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1209 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1210 Known = KF(Known2, Known, ShAmtNonZero);
1211}
1212
1213static KnownBits
1214getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1215 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1216 const SimplifyQuery &Q, unsigned Depth) {
1217 unsigned BitWidth = KnownLHS.getBitWidth();
1218 KnownBits KnownOut(BitWidth);
1219 bool IsAnd = false;
1220 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1221 Value *X = nullptr, *Y = nullptr;
1222
1223 switch (I->getOpcode()) {
1224 case Instruction::And:
1225 KnownOut = KnownLHS & KnownRHS;
1226 IsAnd = true;
1227 // and(x, -x) is common idioms that will clear all but lowest set
1228 // bit. If we have a single known bit in x, we can clear all bits
1229 // above it.
1230 // TODO: instcombine often reassociates independent `and` which can hide
1231 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1232 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1233 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1234 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1235 KnownOut = KnownLHS.blsi();
1236 else
1237 KnownOut = KnownRHS.blsi();
1238 }
1239 break;
1240 case Instruction::Or:
1241 KnownOut = KnownLHS | KnownRHS;
1242 break;
1243 case Instruction::Xor:
1244 KnownOut = KnownLHS ^ KnownRHS;
1245 // xor(x, x-1) is common idioms that will clear all but lowest set
1246 // bit. If we have a single known bit in x, we can clear all bits
1247 // above it.
1248 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1249 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1250 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1251 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1252 if (HasKnownOne &&
1254 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1255 KnownOut = XBits.blsmsk();
1256 }
1257 break;
1258 default:
1259 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1260 }
1261
1262 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1263 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1264 // here we handle the more general case of adding any odd number by
1265 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1266 // TODO: This could be generalized to clearing any bit set in y where the
1267 // following bit is known to be unset in y.
1268 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1272 KnownBits KnownY(BitWidth);
1273 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1274 if (KnownY.countMinTrailingOnes() > 0) {
1275 if (IsAnd)
1276 KnownOut.Zero.setBit(0);
1277 else
1278 KnownOut.One.setBit(0);
1279 }
1280 }
1281 return KnownOut;
1282}
1283
1285 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1286 unsigned Depth,
1287 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1288 KnownBitsFunc) {
1289 APInt DemandedEltsLHS, DemandedEltsRHS;
1291 DemandedElts, DemandedEltsLHS,
1292 DemandedEltsRHS);
1293
1294 const auto ComputeForSingleOpFunc =
1295 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1296 return KnownBitsFunc(
1297 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1298 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1299 };
1300
1301 if (DemandedEltsRHS.isZero())
1302 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1303 if (DemandedEltsLHS.isZero())
1304 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1305
1306 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1307 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1308}
1309
1310// Public so this can be used in `SimplifyDemandedUseBits`.
1312 const KnownBits &KnownLHS,
1313 const KnownBits &KnownRHS,
1314 const SimplifyQuery &SQ,
1315 unsigned Depth) {
1316 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1317 APInt DemandedElts =
1318 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1319
1320 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1321 Depth);
1322}
1323
1325 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1326 // Without vscale_range, we only know that vscale is non-zero.
1327 if (!Attr.isValid())
1329
1330 unsigned AttrMin = Attr.getVScaleRangeMin();
1331 // Minimum is larger than vscale width, result is always poison.
1332 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1333 return ConstantRange::getEmpty(BitWidth);
1334
1335 APInt Min(BitWidth, AttrMin);
1336 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1337 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1339
1340 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1341}
1342
1343/// Return true if \p II reads a register named "vlenb". On RISC-V this is the
1344/// VLENB CSR, which holds VLEN/8: a non-zero power of two bounded by the
1345/// target's VLEN range. Callers must ensure the target is RISC-V.
1346static bool isReadVLENB(const IntrinsicInst &II) {
1347 auto *MAV = dyn_cast<MetadataAsValue>(II.getArgOperand(0));
1348 if (!MAV)
1349 return false;
1350 auto *MD = dyn_cast<MDNode>(MAV->getMetadata());
1351 if (!MD || MD->getNumOperands() != 1)
1352 return false;
1353 auto *RegName = dyn_cast<MDString>(MD->getOperand(0));
1354 return RegName && RegName->getString() == "vlenb";
1355}
1356
1357/// Return the value range of a RISC-V vlenb CSR read. RVV requires VLEN to be a
1358/// power of two in [32, 65536] (Zvl32b is the smallest vector extension), so
1359/// VLENB = VLEN/8 is in [4, 8192]. This architectural bound is independent of
1360/// any function attribute and stays sound for Zvl32b, whose VLEN (32) is not
1361/// representable as an integer vscale (VLEN / RVVBitsPerBlock). A vscale_range
1362/// attribute, when present, pins the subtarget's VLEN in units of
1363/// RVVBitsPerBlock (64 bits) and so gives a tighter VLENB = vscale *
1364/// RVVBytesPerBlock.
1366 unsigned Width) {
1367 // Architectural bounds: VLEN in [32, 65536] => VLENB in [4, 8192].
1368 ConstantRange Range(APInt(Width, 32 / 8), APInt(Width, 65536 / 8) + 1);
1369
1370 const Function *F = II.getFunction();
1371 if (F->getFnAttribute(Attribute::VScaleRange).isValid()) {
1372 ConstantRange VScale = getVScaleRange(F, Width);
1373 Range = Range.intersectWith(
1375 }
1376 return Range;
1377}
1378
1380 Value *Arm, bool Invert,
1381 const SimplifyQuery &Q, unsigned Depth) {
1382 // If we have a constant arm, we are done.
1383 if (Known.isConstant())
1384 return;
1385
1386 // See what condition implies about the bits of the select arm.
1387 KnownBits CondRes(Known.getBitWidth());
1388 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1389 // If we don't get any information from the condition, no reason to
1390 // proceed.
1391 if (CondRes.isUnknown())
1392 return;
1393
1394 // We can have conflict if the condition is dead. I.e if we have
1395 // (x | 64) < 32 ? (x | 64) : y
1396 // we will have conflict at bit 6 from the condition/the `or`.
1397 // In that case just return. Its not particularly important
1398 // what we do, as this select is going to be simplified soon.
1399 CondRes = CondRes.unionWith(Known);
1400 if (CondRes.hasConflict())
1401 return;
1402
1403 // Finally make sure the information we found is valid. This is relatively
1404 // expensive so it's left for the very end.
1405 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CtxI, Q.DT, Depth + 1))
1406 return;
1407
1408 // Finally, we know we get information from the condition and its valid,
1409 // so return it.
1410 Known = std::move(CondRes);
1411}
1412
1413// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1414// Returns the input and lower/upper bounds.
1415static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1416 const APInt *&CLow, const APInt *&CHigh) {
1418 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1419 "Input should be a Select!");
1420
1421 const Value *LHS = nullptr, *RHS = nullptr;
1423 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1424 return false;
1425
1426 if (!match(RHS, m_APInt(CLow)))
1427 return false;
1428
1429 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1431 if (getInverseMinMaxFlavor(SPF) != SPF2)
1432 return false;
1433
1434 if (!match(RHS2, m_APInt(CHigh)))
1435 return false;
1436
1437 if (SPF == SPF_SMIN)
1438 std::swap(CLow, CHigh);
1439
1440 In = LHS2;
1441 return CLow->sle(*CHigh);
1442}
1443
1445 const APInt *&CLow,
1446 const APInt *&CHigh) {
1447 assert((II->getIntrinsicID() == Intrinsic::smin ||
1448 II->getIntrinsicID() == Intrinsic::smax) &&
1449 "Must be smin/smax");
1450
1451 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1452 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1453 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1454 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1455 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1456 return false;
1457
1458 if (II->getIntrinsicID() == Intrinsic::smin)
1459 std::swap(CLow, CHigh);
1460 return CLow->sle(*CHigh);
1461}
1462
1464 KnownBits &Known) {
1465 const APInt *CLow, *CHigh;
1466 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1467 Known = Known.unionWith(
1468 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1469}
1470
1472 const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts,
1473 KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q,
1474 unsigned Depth) {
1475 // Change the context instruction to the "edge" that flows into the phi. This
1476 // is important because that is where the value is actually "evaluated" even
1477 // though it is used later somewhere else. (see also D69571).
1479 unsigned OpNum = P->getOperand(0) == Start ? 0 : 1;
1480
1481 RecQ.CtxI = P->getIncomingBlock(OpNum)->getTerminator();
1482 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1483
1484 RecQ.CtxI = P->getIncomingBlock(1 - OpNum)->getTerminator();
1485 computeKnownBits(Step, DemandedElts, KnownStep, RecQ, Depth + 1);
1486}
1487
1489 const APInt &DemandedElts,
1491 const SimplifyQuery &Q,
1492 unsigned Depth) {
1493 unsigned BitWidth = Known.getBitWidth();
1494
1495 KnownBits Known2(BitWidth);
1496 switch (I->getOpcode()) {
1497 default: break;
1498 case Instruction::Load:
1499 if (MDNode *MD =
1500 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1502 break;
1503 case Instruction::And:
1504 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1505 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1506
1507 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1508 break;
1509 case Instruction::Or:
1510 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1511 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1512
1513 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1514 break;
1515 case Instruction::Xor:
1516 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1517 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1518
1519 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1520 break;
1521 case Instruction::Mul: {
1524 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1525 DemandedElts, Known, Known2, Q, Depth);
1526 break;
1527 }
1528 case Instruction::UDiv: {
1529 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1530 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1531 Known =
1533 break;
1534 }
1535 case Instruction::SDiv: {
1536 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1537 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1538 Known =
1540 break;
1541 }
1542 case Instruction::Select: {
1543 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1544 KnownBits Res(Known.getBitWidth());
1545 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1546 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1547 return Res;
1548 };
1549 // Only known if known in both the LHS and RHS.
1550 Known =
1551 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1552 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1553 break;
1554 }
1555 case Instruction::FPToSI: {
1556 // fptosi is poison if the rounded value doesn't fit in the result type,
1557 // so we can assume the conversion is well-defined and rounds towards
1558 // zero. +-Inf can never fit in an integer type, so it is always poison,
1559 // like NaN. Negative subnormals and negative zero round to 0. That
1560 // leaves negative normals as the only class that can produce a defined
1561 // negative result.
1562 KnownFPClass SrcFPClass = computeKnownFPClass(
1563 I->getOperand(0), DemandedElts, fcNegNormal, Q, Depth + 1);
1564 if (SrcFPClass.isKnownNever(fcNegNormal))
1565 Known.makeNonNegative();
1566 break;
1567 }
1568 case Instruction::FPTrunc:
1569 case Instruction::FPExt:
1570 case Instruction::FPToUI:
1571 case Instruction::SIToFP:
1572 case Instruction::UIToFP:
1573 break; // Can't work with floating point.
1574 case Instruction::PtrToInt:
1575 case Instruction::PtrToAddr:
1576 case Instruction::IntToPtr:
1577 // Fall through and handle them the same as zext/trunc.
1578 [[fallthrough]];
1579 case Instruction::ZExt:
1580 case Instruction::Trunc: {
1581 Type *SrcTy = I->getOperand(0)->getType();
1582
1583 unsigned SrcBitWidth;
1584 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1585 // which fall through here.
1586 Type *ScalarTy = SrcTy->getScalarType();
1587 SrcBitWidth = ScalarTy->isPointerTy() ?
1588 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1589 Q.DL.getTypeSizeInBits(ScalarTy);
1590
1591 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1592 Known = Known.anyextOrTrunc(SrcBitWidth);
1593 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1594 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1595 Inst && Inst->hasNonNeg() && !Known.isNegative())
1596 Known.makeNonNegative();
1597 Known = Known.zextOrTrunc(BitWidth);
1598 break;
1599 }
1600 case Instruction::BitCast: {
1601 Type *SrcTy = I->getOperand(0)->getType();
1602 if (SrcTy->isIntOrPtrTy() &&
1603 // TODO: For now, not handling conversions like:
1604 // (bitcast i64 %x to <2 x i32>)
1605 !I->getType()->isVectorTy()) {
1606 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1607 break;
1608 }
1609
1610 const Value *V;
1611 // Handle bitcast from floating point to integer.
1612 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1613 V->getType()->isFPOrFPVectorTy()) {
1614 Type *FPType = V->getType()->getScalarType();
1615 KnownFPClass Result =
1616 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1617
1618 Known = Result.toKnownBits(FPType->getFltSemantics());
1619
1620 break;
1621 }
1622
1623 // Handle cast from vector integer type to scalar or vector integer.
1624 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1625 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1626 !I->getType()->isIntOrIntVectorTy() ||
1627 isa<ScalableVectorType>(I->getType()))
1628 break;
1629
1630 unsigned NumElts = DemandedElts.getBitWidth();
1631 bool IsLE = Q.DL.isLittleEndian();
1632 // Look through a cast from narrow vector elements to wider type.
1633 // Examples: v4i32 -> v2i64, v3i8 -> v24
1634 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1635 if (BitWidth % SubBitWidth == 0) {
1636 // Known bits are automatically intersected across demanded elements of a
1637 // vector. So for example, if a bit is computed as known zero, it must be
1638 // zero across all demanded elements of the vector.
1639 //
1640 // For this bitcast, each demanded element of the output is sub-divided
1641 // across a set of smaller vector elements in the source vector. To get
1642 // the known bits for an entire element of the output, compute the known
1643 // bits for each sub-element sequentially. This is done by shifting the
1644 // one-set-bit demanded elements parameter across the sub-elements for
1645 // consecutive calls to computeKnownBits. We are using the demanded
1646 // elements parameter as a mask operator.
1647 //
1648 // The known bits of each sub-element are then inserted into place
1649 // (dependent on endian) to form the full result of known bits.
1650 unsigned SubScale = BitWidth / SubBitWidth;
1651 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1652 for (unsigned i = 0; i != NumElts; ++i) {
1653 if (DemandedElts[i])
1654 SubDemandedElts.setBit(i * SubScale);
1655 }
1656
1657 KnownBits KnownSrc(SubBitWidth);
1658 for (unsigned i = 0; i != SubScale; ++i) {
1659 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1660 Depth + 1);
1661 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1662 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1663 }
1664 }
1665 // Look through a cast from wider vector elements to narrow type.
1666 // Examples: v2i64 -> v4i32
1667 if (SubBitWidth % BitWidth == 0) {
1668 unsigned SubScale = SubBitWidth / BitWidth;
1669 KnownBits KnownSrc(SubBitWidth);
1670 APInt SubDemandedElts =
1671 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1672 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1673 Depth + 1);
1674
1675 Known.setAllConflict();
1676 for (unsigned i = 0; i != NumElts; ++i) {
1677 if (DemandedElts[i]) {
1678 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1679 unsigned Offset = (Shifts % SubScale) * BitWidth;
1680 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1681 if (Known.isUnknown())
1682 break;
1683 }
1684 }
1685 }
1686 break;
1687 }
1688 case Instruction::SExt: {
1689 // Compute the bits in the result that are not present in the input.
1690 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1691
1692 Known = Known.trunc(SrcBitWidth);
1693 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1694 // If the sign bit of the input is known set or clear, then we know the
1695 // top bits of the result.
1696 Known = Known.sext(BitWidth);
1697 break;
1698 }
1699 case Instruction::Shl: {
1702 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1703 bool ShAmtNonZero) {
1704 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1705 };
1706 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1707 KF);
1708 // Trailing zeros of a right-shifted constant never decrease.
1709 const APInt *C;
1710 if (match(I->getOperand(0), m_APInt(C)))
1711 Known.Zero.setLowBits(C->countr_zero());
1712
1713 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1714 // lands at bit Y, when BitWidth is a power of 2.
1715 const APInt *YC;
1716 Value *X = I->getOperand(0);
1717 if (isPowerOf2_32(BitWidth) &&
1718 match(I->getOperand(1),
1720 m_SpecificInt(BitWidth - 1)))) &&
1721 YC->ult(BitWidth - 1)) {
1722 unsigned Y = YC->getZExtValue();
1723 Known.One.setBit(Y);
1724 Known.Zero.setBitsFrom(Y + 1);
1725 }
1726 break;
1727 }
1728 case Instruction::LShr: {
1729 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1730 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1731 bool ShAmtNonZero) {
1732 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1733 };
1734 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1735 KF);
1736 // Leading zeros of a left-shifted constant never decrease.
1737 const APInt *C;
1738 if (match(I->getOperand(0), m_APInt(C)))
1739 Known.Zero.setHighBits(C->countl_zero());
1740 break;
1741 }
1742 case Instruction::AShr: {
1743 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1744 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1745 bool ShAmtNonZero) {
1746 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1747 };
1748 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1749 KF);
1750 break;
1751 }
1752 case Instruction::Sub: {
1755 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1756 DemandedElts, Known, Known2, Q, Depth);
1757 break;
1758 }
1759 case Instruction::Add: {
1762 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1763 DemandedElts, Known, Known2, Q, Depth);
1764 break;
1765 }
1766 case Instruction::SRem:
1767 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1768 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1769 Known = KnownBits::srem(Known, Known2);
1770 break;
1771
1772 case Instruction::URem:
1773 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1774 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1775 Known = KnownBits::urem(Known, Known2);
1776 break;
1777 case Instruction::Alloca:
1778 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1779 break;
1780 case Instruction::GetElementPtr: {
1781 // Analyze all of the subscripts of this getelementptr instruction
1782 // to determine if we can prove known low zero bits.
1783 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1784 // Accumulate the constant indices in a separate variable
1785 // to minimize the number of calls to computeForAddSub.
1786 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1787 APInt AccConstIndices(IndexWidth, 0);
1788
1789 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1790 if (IndexWidth == BitWidth) {
1791 // Note that inbounds does *not* guarantee nsw for the addition, as only
1792 // the offset is signed, while the base address is unsigned.
1793 Known = KnownBits::add(Known, IndexBits);
1794 } else {
1795 // If the index width is smaller than the pointer width, only add the
1796 // value to the low bits.
1797 assert(IndexWidth < BitWidth &&
1798 "Index width can't be larger than pointer width");
1799 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1800 }
1801 };
1802
1804 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1805 // TrailZ can only become smaller, short-circuit if we hit zero.
1806 if (Known.isUnknown())
1807 break;
1808
1809 Value *Index = I->getOperand(i);
1810
1811 // Handle case when index is zero.
1812 Constant *CIndex = dyn_cast<Constant>(Index);
1813 if (CIndex && CIndex->isNullValue())
1814 continue;
1815
1816 if (StructType *STy = GTI.getStructTypeOrNull()) {
1817 // Handle struct member offset arithmetic.
1818
1819 assert(CIndex &&
1820 "Access to structure field must be known at compile time");
1821
1822 if (CIndex->getType()->isVectorTy())
1823 Index = CIndex->getSplatValue();
1824
1825 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1826 const StructLayout *SL = Q.DL.getStructLayout(STy);
1827 uint64_t Offset = SL->getElementOffset(Idx);
1828 AccConstIndices += Offset;
1829 continue;
1830 }
1831
1832 // Handle array index arithmetic.
1833 Type *IndexedTy = GTI.getIndexedType();
1834 if (!IndexedTy->isSized()) {
1835 Known.resetAll();
1836 break;
1837 }
1838
1839 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1840 uint64_t StrideInBytes = Stride.getKnownMinValue();
1841 if (!Stride.isScalable()) {
1842 // Fast path for constant offset.
1843 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1844 AccConstIndices +=
1845 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1846 continue;
1847 }
1848 }
1849
1850 KnownBits IndexBits =
1851 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1852 KnownBits ScalingFactor(IndexWidth);
1853 // Multiply by current sizeof type.
1854 // &A[i] == A + i * sizeof(*A[i]).
1855 if (Stride.isScalable()) {
1856 // For scalable types the only thing we know about sizeof is
1857 // that this is a multiple of the minimum size.
1858 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1859 } else {
1860 ScalingFactor =
1861 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1862 }
1863 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1864 }
1865 if (!Known.isUnknown() && !AccConstIndices.isZero())
1866 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1867 break;
1868 }
1869 case Instruction::PHI: {
1870 const PHINode *P = cast<PHINode>(I);
1871 BinaryOperator *BO = nullptr;
1872 Value *Start = nullptr, *Step = nullptr;
1873 KnownBits &KnownStart = Known2;
1874 if (matchSimpleRecurrence(P, BO, Start, Step)) {
1875 // Handle the case of a simple two-predecessor recurrence PHI.
1876 // There's a lot more that could theoretically be done here, but
1877 // this is sufficient to catch some interesting cases.
1878 unsigned Opcode = BO->getOpcode();
1879
1880 switch (Opcode) {
1881 // If this is a shift recurrence, we know the bits being shifted in. We
1882 // can combine that with information about the start value of the
1883 // recurrence to conclude facts about the result. If this is a udiv
1884 // recurrence, we know that the result can never exceed either the
1885 // numerator or the start value, whichever is greater.
1886 case Instruction::LShr:
1887 case Instruction::AShr:
1888 case Instruction::Shl:
1889 case Instruction::UDiv:
1890 if (BO->getOperand(0) != I)
1891 break;
1892 [[fallthrough]];
1893
1894 // For a urem recurrence, the result can never exceed the start value. The
1895 // phi could either be the numerator or the denominator.
1896 case Instruction::URem: {
1897 // We have matched a recurrence of the form:
1898 // %iv = [R, %entry], [%iv.next, %backedge]
1899 // %iv.next = shift_op %iv, L
1900
1901 // Recurse with the phi context to avoid concern about whether facts
1902 // inferred hold at original context instruction. TODO: It may be
1903 // correct to use the original context. IF warranted, explore and
1904 // add sufficient tests to cover.
1906 RecQ.CtxI = P;
1907 computeKnownBits(Start, DemandedElts, KnownStart, RecQ, Depth + 1);
1908 switch (Opcode) {
1909 case Instruction::Shl:
1910 // A shl recurrence will only increase the tailing zeros
1911 Known.Zero.setLowBits(KnownStart.countMinTrailingZeros());
1912 break;
1913 case Instruction::LShr:
1914 case Instruction::UDiv:
1915 case Instruction::URem:
1916 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1917 // the start value.
1918 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1919 break;
1920 case Instruction::AShr:
1921 // An ashr recurrence will extend the initial sign bit
1922 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
1923 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
1924 break;
1925 }
1926 break;
1927 }
1928
1929 case Instruction::And: {
1930 // Bits that are zero in the start value stay zero, and bits that are
1931 // one in both the start value and the step stay one.
1932 KnownBits KnownStep(BitWidth);
1933 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1934 KnownStart, KnownStep, Q, Depth);
1935 Known.Zero |= KnownStart.Zero;
1936 Known.One |= KnownStart.One & KnownStep.One;
1937 break;
1938 }
1939
1940 case Instruction::Or: {
1941 // Bits that are zero in both the start value and the step stay zero,
1942 // and bits that are one in the start value stay one.
1943 KnownBits KnownStep(BitWidth);
1944 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1945 KnownStart, KnownStep, Q, Depth);
1946 Known.Zero |= KnownStart.Zero & KnownStep.Zero;
1947 Known.One |= KnownStart.One;
1948 break;
1949 }
1950
1951 // Check for operations that have the property that if
1952 // both their operands have low zero bits, the result
1953 // will have low zero bits.
1954 case Instruction::Add:
1955 case Instruction::Sub:
1956 case Instruction::Mul: {
1957 // Ok, we have a recurrence of the form {Start,op,Step}. Check for low
1958 // zero bits.
1959 KnownBits KnownStep(BitWidth);
1960 computeKnownBitsForRecurrenceOperands(P, Start, Step, DemandedElts,
1961 KnownStart, KnownStep, Q, Depth);
1962
1963 Known.Zero.setLowBits(std::min(KnownStart.countMinTrailingZeros(),
1964 KnownStep.countMinTrailingZeros()));
1965
1966 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1967 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1968 break;
1969
1970 switch (Opcode) {
1971 // If initial value of recurrence is nonnegative, and we are adding
1972 // a nonnegative number with nsw, the result can only be nonnegative
1973 // or poison value regardless of the number of times we execute the
1974 // add in phi recurrence. If initial value is negative and we are
1975 // adding a negative number with nsw, the result can only be
1976 // negative or poison value. Similar arguments apply to sub and mul.
1977 //
1978 // (add non-negative, non-negative) --> non-negative
1979 // (add negative, negative) --> negative
1980 case Instruction::Add: {
1981 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
1982 Known.makeNonNegative();
1983 else if (KnownStart.isNegative() && KnownStep.isNegative())
1984 Known.makeNegative();
1985 break;
1986 }
1987
1988 // (sub nsw non-negative, negative) --> non-negative
1989 // (sub nsw negative, non-negative) --> negative
1990 case Instruction::Sub: {
1991 if (BO->getOperand(0) != I)
1992 break;
1993 if (KnownStart.isNonNegative() && KnownStep.isNegative())
1994 Known.makeNonNegative();
1995 else if (KnownStart.isNegative() && KnownStep.isNonNegative())
1996 Known.makeNegative();
1997 break;
1998 }
1999
2000 // (mul nsw non-negative, non-negative) --> non-negative
2001 case Instruction::Mul:
2002 if (KnownStart.isNonNegative() && KnownStep.isNonNegative())
2003 Known.makeNonNegative();
2004 break;
2005
2006 default:
2007 break;
2008 }
2009 break;
2010 }
2011
2012 default:
2013 break;
2014 }
2015 } else {
2016 IntrinsicInst *II = nullptr;
2017 if (matchTwoInputRecurrence<IntrinsicInst>(P, II, Start, Step)) {
2018 // %iv = [<Start>, %entry], [%iv.next, %backedge]
2019 //
2020 // %iv.next = <II>(%iv, <Step>)
2021 // or
2022 // %iv.next = <II>(<Step>, %iv)
2023 Intrinsic::ID IntrinsicID = II->getIntrinsicID();
2024 if (IntrinsicID == Intrinsic::umin || IntrinsicID == Intrinsic::umax) {
2025 KnownBits KnownStep(BitWidth);
2027 P, Start, Step, DemandedElts, KnownStart, KnownStep, Q, Depth);
2028
2029 if (IntrinsicID == Intrinsic::umin) {
2030 Known.Zero.setHighBits(KnownStart.countMinLeadingZeros());
2031 Known.One.setHighBits(std::min(KnownStart.countMinLeadingOnes(),
2032 KnownStep.countMinLeadingOnes()));
2033 } else {
2034 // umax
2035 Known.Zero.setHighBits(std::min(KnownStart.countMinLeadingZeros(),
2036 KnownStep.countMinLeadingZeros()));
2037 Known.One.setHighBits(KnownStart.countMinLeadingOnes());
2038 }
2039 }
2040 }
2041 }
2042
2043 // Unreachable blocks may have zero-operand PHI nodes.
2044 if (P->getNumIncomingValues() == 0)
2045 break;
2046
2047 // Otherwise take the unions of the known bit sets of the operands,
2048 // taking conservative care to avoid excessive recursion.
2049 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
2050 // Skip if every incoming value references to ourself.
2051 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
2052 break;
2053
2054 Known.setAllConflict();
2055 for (const Use &U : P->operands()) {
2056 Value *IncValue;
2057 const PHINode *CtxPhi;
2058 Instruction *CtxI;
2059 breakSelfRecursivePHI(&U, P, IncValue, CtxI, &CtxPhi);
2060 // Skip direct self references.
2061 if (IncValue == P)
2062 continue;
2063
2064 // Change the context instruction to the "edge" that flows into the
2065 // phi. This is important because that is where the value is actually
2066 // "evaluated" even though it is used later somewhere else. (see also
2067 // D69571).
2069
2070 Known2 = KnownBits(BitWidth);
2071
2072 // Recurse, but cap the recursion to one level, because we don't
2073 // want to waste time spinning around in loops.
2074 // TODO: See if we can base recursion limiter on number of incoming phi
2075 // edges so we don't overly clamp analysis.
2076 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
2078
2079 // See if we can further use a conditional branch into the phi
2080 // to help us determine the range of the value.
2081 if (!Known2.isConstant()) {
2082 CmpPredicate Pred;
2083 const APInt *RHSC;
2084 BasicBlock *TrueSucc, *FalseSucc;
2085 // TODO: Use RHS Value and compute range from its known bits.
2086 if (match(RecQ.CtxI,
2087 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
2088 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
2089 // Check for cases of duplicate successors.
2090 if ((TrueSucc == CtxPhi->getParent()) !=
2091 (FalseSucc == CtxPhi->getParent())) {
2092 // If we're using the false successor, invert the predicate.
2093 if (FalseSucc == CtxPhi->getParent())
2094 Pred = CmpInst::getInversePredicate(Pred);
2095 // Get the knownbits implied by the incoming phi condition.
2096 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
2097 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
2098 // We can have conflicts here if we are analyzing deadcode (its
2099 // impossible for us reach this BB based the icmp).
2100 if (KnownUnion.hasConflict()) {
2101 // No reason to continue analyzing in a known dead region, so
2102 // just resetAll and break. This will cause us to also exit the
2103 // outer loop.
2104 Known.resetAll();
2105 break;
2106 }
2107 Known2 = KnownUnion;
2108 }
2109 }
2110 }
2111
2112 Known = Known.intersectWith(Known2);
2113 // If all bits have been ruled out, there's no need to check
2114 // more operands.
2115 if (Known.isUnknown())
2116 break;
2117 }
2118 }
2119 break;
2120 }
2121 case Instruction::Call:
2122 case Instruction::Invoke: {
2123 // If range metadata is attached to this call, set known bits from that,
2124 // and then intersect with known bits based on other properties of the
2125 // function.
2126 if (MDNode *MD =
2127 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2129
2130 const auto *CB = cast<CallBase>(I);
2131
2132 if (std::optional<ConstantRange> Range = CB->getRange())
2133 Known = Known.unionWith(Range->toKnownBits());
2134
2135 if (const Value *RV = CB->getReturnedArgOperand()) {
2136 if (RV->getType() == I->getType()) {
2137 computeKnownBits(RV, Known2, Q, Depth + 1);
2138 Known = Known.unionWith(Known2);
2139 // If the function doesn't return properly for all input values
2140 // (e.g. unreachable exits) then there might be conflicts between the
2141 // argument value and the range metadata. Simply discard the known bits
2142 // in case of conflicts.
2143 if (Known.hasConflict())
2144 Known.resetAll();
2145 }
2146 }
2147 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2148 switch (II->getIntrinsicID()) {
2149 default:
2150 break;
2151 case Intrinsic::abs: {
2152 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2153 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2154 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2155 break;
2156 }
2157 case Intrinsic::bitreverse:
2158 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2159 Known = Known.unionWith(Known2.reverseBits());
2160 break;
2161 case Intrinsic::bswap:
2162 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2163 Known = Known.unionWith(Known2.byteSwap());
2164 break;
2165 case Intrinsic::ctlz: {
2166 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2167 // If we have a known 1, its position is our upper bound.
2168 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2169 // If this call is poison for 0 input, the result will be less than 2^n.
2170 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2171 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2172 unsigned LowBits = llvm::bit_width(PossibleLZ);
2173 Known.Zero.setBitsFrom(LowBits);
2174 break;
2175 }
2176 case Intrinsic::cttz: {
2177 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2178 // If we have a known 1, its position is our upper bound.
2179 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2180 // If this call is poison for 0 input, the result will be less than 2^n.
2181 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2182 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2183 unsigned LowBits = llvm::bit_width(PossibleTZ);
2184 Known.Zero.setBitsFrom(LowBits);
2185 break;
2186 }
2187 case Intrinsic::ctpop: {
2188 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2189 // We can bound the space the count needs. Also, bits known to be zero
2190 // can't contribute to the population.
2191 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2192 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2193 Known.Zero.setBitsFrom(LowBits);
2194 // TODO: we could bound KnownOne using the lower bound on the number
2195 // of bits which might be set provided by popcnt KnownOne2.
2196 break;
2197 }
2198 case Intrinsic::fshr:
2199 case Intrinsic::fshl: {
2200 const APInt *SA;
2201 if (!match(I->getOperand(2), m_APInt(SA)))
2202 break;
2203
2204 KnownBits Known3(BitWidth);
2205 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2206 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2207 Known = II->getIntrinsicID() == Intrinsic::fshl
2208 ? KnownBits::fshl(Known2, Known3, *SA)
2209 : KnownBits::fshr(Known2, Known3, *SA);
2210 break;
2211 }
2212 case Intrinsic::clmul:
2213 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2214 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2215 Known = KnownBits::clmul(Known, Known2);
2216 break;
2217 case Intrinsic::pext:
2218 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2219 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2220 Known = KnownBits::pext(Known, Known2);
2221 break;
2222 case Intrinsic::pdep:
2223 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2224 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2225 Known = KnownBits::pdep(Known, Known2);
2226 break;
2227 case Intrinsic::smulh:
2228 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2229 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2230 Known = KnownBits::mulhs(Known, Known2);
2231 break;
2232 case Intrinsic::umulh:
2233 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2234 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2235 Known = KnownBits::mulhu(Known, Known2);
2236 break;
2237 case Intrinsic::uadd_sat:
2238 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2239 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2240 Known = KnownBits::uadd_sat(Known, Known2);
2241 break;
2242 case Intrinsic::usub_sat:
2243 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2244 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2245 Known = KnownBits::usub_sat(Known, Known2);
2246 break;
2247 case Intrinsic::sadd_sat:
2248 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2249 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2250 Known = KnownBits::sadd_sat(Known, Known2);
2251 break;
2252 case Intrinsic::ssub_sat:
2253 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2254 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2255 Known = KnownBits::ssub_sat(Known, Known2);
2256 break;
2257 // Vec reverse preserves bits from input vec.
2258 case Intrinsic::vector_reverse:
2259 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2260 Depth + 1);
2261 break;
2262 // for min/max/and/or reduce, any bit common to each element in the
2263 // input vec is set in the output.
2264 case Intrinsic::vector_reduce_and:
2265 case Intrinsic::vector_reduce_or:
2266 case Intrinsic::vector_reduce_umax:
2267 case Intrinsic::vector_reduce_umin:
2268 case Intrinsic::vector_reduce_smax:
2269 case Intrinsic::vector_reduce_smin:
2270 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2271 break;
2272 case Intrinsic::vector_reduce_xor: {
2273 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2274 // The zeros common to all vecs are zero in the output.
2275 // If the number of elements is odd, then the common ones remain. If the
2276 // number of elements is even, then the common ones becomes zeros.
2277 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2278 // Even, so the ones become zeros.
2279 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2280 if (EvenCnt)
2281 Known.Zero |= Known.One;
2282 // Maybe even element count so need to clear ones.
2283 if (VecTy->isScalableTy() || EvenCnt)
2284 Known.One.clearAllBits();
2285 break;
2286 }
2287 case Intrinsic::vector_reduce_add: {
2288 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2289 if (!VecTy)
2290 break;
2291 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2292 Known = Known.reduceAdd(VecTy->getNumElements());
2293 break;
2294 }
2295 case Intrinsic::umin:
2296 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2297 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2298 Known = KnownBits::umin(Known, Known2);
2299 break;
2300 case Intrinsic::umax:
2301 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2302 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2303 Known = KnownBits::umax(Known, Known2);
2304 break;
2305 case Intrinsic::smin:
2306 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2307 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2308 Known = KnownBits::smin(Known, Known2);
2310 break;
2311 case Intrinsic::smax:
2312 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2313 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2314 Known = KnownBits::smax(Known, Known2);
2316 break;
2317 case Intrinsic::ptrmask: {
2318 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2319
2320 const Value *Mask = I->getOperand(1);
2321 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2322 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2323 // TODO: 1-extend would be more precise.
2324 Known &= Known2.anyextOrTrunc(BitWidth);
2325 break;
2326 }
2327 case Intrinsic::x86_sse42_crc32_64_64:
2328 Known.Zero.setBitsFrom(32);
2329 break;
2330 case Intrinsic::x86_ssse3_phadd_d_128:
2331 case Intrinsic::x86_ssse3_phadd_w_128:
2332 case Intrinsic::x86_avx2_phadd_d:
2333 case Intrinsic::x86_avx2_phadd_w: {
2335 I, DemandedElts, Q, Depth,
2336 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2337 return KnownBits::add(KnownLHS, KnownRHS);
2338 });
2339 break;
2340 }
2341 case Intrinsic::x86_ssse3_phadd_sw_128:
2342 case Intrinsic::x86_avx2_phadd_sw: {
2344 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2345 break;
2346 }
2347 case Intrinsic::x86_ssse3_phsub_d_128:
2348 case Intrinsic::x86_ssse3_phsub_w_128:
2349 case Intrinsic::x86_avx2_phsub_d:
2350 case Intrinsic::x86_avx2_phsub_w: {
2352 I, DemandedElts, Q, Depth,
2353 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2354 return KnownBits::sub(KnownLHS, KnownRHS);
2355 });
2356 break;
2357 }
2358 case Intrinsic::x86_ssse3_phsub_sw_128:
2359 case Intrinsic::x86_avx2_phsub_sw: {
2361 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2362 break;
2363 }
2364 case Intrinsic::riscv_vsetvli:
2365 case Intrinsic::riscv_vsetvlimax: {
2366 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2367 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2369 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2370 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2371 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2372 uint64_t MaxVLEN =
2373 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2374 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2375
2376 // Result of vsetvli must be not larger than AVL.
2377 if (HasAVL)
2378 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2379 MaxVL = std::min(MaxVL, CI->getZExtValue());
2380
2381 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2382 if (BitWidth > KnownZeroFirstBit)
2383 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2384 break;
2385 }
2386 case Intrinsic::amdgcn_mbcnt_hi:
2387 case Intrinsic::amdgcn_mbcnt_lo: {
2388 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2389 // most 31 + src1.
2390 KnownBits MbcntKnown(BitWidth);
2391 MbcntKnown.Zero.setBitsFrom(
2392 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2393 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2394 Known = Known.unionWith(KnownBits::add(MbcntKnown, Known2));
2395 break;
2396 }
2397 case Intrinsic::vscale: {
2398 if (!II->getParent() || !II->getFunction())
2399 break;
2400
2401 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2402 break;
2403 }
2404 case Intrinsic::stepvector: {
2405 auto *VecTy = cast<VectorType>(II->getType());
2406 unsigned MinNumElts = VecTy->getElementCount().getKnownMinValue();
2407 if (!isUIntN(BitWidth, MinNumElts))
2408 break;
2409
2410 bool Overflow = false;
2411 APInt MaxNumElts(BitWidth, MinNumElts);
2412 if (VecTy->isScalableTy()) {
2413 if (!II->getParent() || !II->getFunction())
2414 break;
2415 MaxNumElts = getVScaleRange(II->getFunction(), BitWidth)
2417 .umul_ov(MaxNumElts, Overflow);
2418 }
2419
2420 // Give up if the lane count could wrap. Stepvector truncates lane
2421 // indices that do not fit in the element type.
2422 if (Overflow)
2423 break;
2424
2425 Known.Zero.setHighBits((MaxNumElts - 1).countl_zero());
2426 break;
2427 }
2428 }
2429 }
2430 break;
2431 }
2432 case Instruction::ShuffleVector: {
2433 if (auto *Splat = getSplatValue(I)) {
2435 break;
2436 }
2437
2438 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2439 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2440 if (!Shuf) {
2441 Known.resetAll();
2442 return;
2443 }
2444 // For undef elements, we don't know anything about the common state of
2445 // the shuffle result.
2446 APInt DemandedLHS, DemandedRHS;
2447 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2448 Known.resetAll();
2449 return;
2450 }
2451 Known.setAllConflict();
2452 if (!!DemandedLHS) {
2453 const Value *LHS = Shuf->getOperand(0);
2454 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2455 // If we don't know any bits, early out.
2456 if (Known.isUnknown())
2457 break;
2458 }
2459 if (!!DemandedRHS) {
2460 const Value *RHS = Shuf->getOperand(1);
2461 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2462 Known = Known.intersectWith(Known2);
2463 }
2464 break;
2465 }
2466 case Instruction::InsertElement: {
2467 if (isa<ScalableVectorType>(I->getType())) {
2468 Known.resetAll();
2469 return;
2470 }
2471 const Value *Vec = I->getOperand(0);
2472 const Value *Elt = I->getOperand(1);
2473 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2474 unsigned NumElts = DemandedElts.getBitWidth();
2475 APInt DemandedVecElts = DemandedElts;
2476 bool NeedsElt = true;
2477 // If we know the index we are inserting too, clear it from Vec check.
2478 if (CIdx && CIdx->getValue().ult(NumElts)) {
2479 DemandedVecElts.clearBit(CIdx->getZExtValue());
2480 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2481 }
2482
2483 Known.setAllConflict();
2484 if (NeedsElt) {
2485 computeKnownBits(Elt, Known, Q, Depth + 1);
2486 // If we don't know any bits, early out.
2487 if (Known.isUnknown())
2488 break;
2489 }
2490
2491 if (!DemandedVecElts.isZero()) {
2492 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2493 Known = Known.intersectWith(Known2);
2494 }
2495 break;
2496 }
2497 case Instruction::ExtractElement: {
2498 // Look through extract element. If the index is non-constant or
2499 // out-of-range demand all elements, otherwise just the extracted element.
2500 const Value *Vec = I->getOperand(0);
2501 const Value *Idx = I->getOperand(1);
2502 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2503 if (isa<ScalableVectorType>(Vec->getType())) {
2504 // FIXME: there's probably *something* we can do with scalable vectors
2505 Known.resetAll();
2506 break;
2507 }
2508 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2509 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2510 if (CIdx && CIdx->getValue().ult(NumElts))
2511 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2512 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2513 break;
2514 }
2515 case Instruction::ExtractValue:
2516 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2518 if (EVI->getNumIndices() != 1) break;
2519 if (EVI->getIndices()[0] == 0) {
2520 switch (II->getIntrinsicID()) {
2521 default: break;
2522 case Intrinsic::uadd_with_overflow:
2523 case Intrinsic::sadd_with_overflow:
2525 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2526 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2527 break;
2528 case Intrinsic::usub_with_overflow:
2529 case Intrinsic::ssub_with_overflow:
2531 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2532 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2533 break;
2534 case Intrinsic::umul_with_overflow:
2535 case Intrinsic::smul_with_overflow:
2536 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2537 false, DemandedElts, Known, Known2, Q, Depth);
2538 break;
2539 }
2540 }
2541 }
2542 break;
2543 case Instruction::Freeze:
2544 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
2545 Depth + 1))
2546 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2547 break;
2548 }
2549}
2550
2551/// Determine which bits of V are known to be either zero or one and return
2552/// them.
2553KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2554 const SimplifyQuery &Q, unsigned Depth) {
2555 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2556 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2557 return Known;
2558}
2559
2560/// Determine which bits of V are known to be either zero or one and return
2561/// them.
2563 unsigned Depth) {
2564 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2566 return Known;
2567}
2568
2569/// Determine which bits of V are known to be either zero or one and return
2570/// them in the Known bit set.
2571///
2572/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2573/// we cannot optimize based on the assumption that it is zero without changing
2574/// it to be an explicit zero. If we don't change it to zero, other code could
2575/// optimized based on the contradictory assumption that it is non-zero.
2576/// Because instcombine aggressively folds operations with undef args anyway,
2577/// this won't lose us code quality.
2578///
2579/// This function is defined on values with integer type, values with pointer
2580/// type, and vectors of integers. In the case
2581/// where V is a vector, known zero, and known one values are the
2582/// same width as the vector element, and the bit is set only if it is true
2583/// for all of the demanded elements in the vector specified by DemandedElts.
2584void computeKnownBits(const Value *V, const APInt &DemandedElts,
2585 KnownBits &Known, const SimplifyQuery &Q,
2586 unsigned Depth) {
2587 if (!DemandedElts) {
2588 // No demanded elts, better to assume we don't know anything.
2589 Known.resetAll();
2590 return;
2591 }
2592
2593 assert(V && "No Value?");
2594 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2595
2596#ifndef NDEBUG
2597 Type *Ty = V->getType();
2598 unsigned BitWidth = Known.getBitWidth();
2599
2600 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2601 "Not integer or pointer type!");
2602
2603 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2604 assert(
2605 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2606 "DemandedElt width should equal the fixed vector number of elements");
2607 } else {
2608 assert(DemandedElts == APInt(1, 1) &&
2609 "DemandedElt width should be 1 for scalars or scalable vectors");
2610 }
2611
2612 Type *ScalarTy = Ty->getScalarType();
2613 if (ScalarTy->isPointerTy()) {
2614 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2615 "V and Known should have same BitWidth");
2616 } else {
2617 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2618 "V and Known should have same BitWidth");
2619 }
2620#endif
2621
2622 const APInt *C;
2623 if (match(V, m_APInt(C))) {
2624 // We know all of the bits for a scalar constant or a splat vector constant!
2626 return;
2627 }
2628 // Null and aggregate-zero are all-zeros.
2630 Known.setAllZero();
2631 return;
2632 }
2633 // Handle a constant vector by taking the intersection of the known bits of
2634 // each element.
2636 assert(!isa<ScalableVectorType>(V->getType()));
2637 // We know that CDV must be a vector of integers. Take the intersection of
2638 // each element.
2639 Known.setAllConflict();
2640 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2641 if (!DemandedElts[i])
2642 continue;
2643 APInt Elt = CDV->getElementAsAPInt(i);
2644 Known.Zero &= ~Elt;
2645 Known.One &= Elt;
2646 }
2647 if (Known.hasConflict())
2648 Known.resetAll();
2649 return;
2650 }
2651
2652 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2653 assert(!isa<ScalableVectorType>(V->getType()));
2654 // We know that CV must be a vector of integers. Take the intersection of
2655 // each element.
2656 Known.setAllConflict();
2657 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2658 if (!DemandedElts[i])
2659 continue;
2660 Constant *Element = CV->getAggregateElement(i);
2661 if (isa<PoisonValue>(Element))
2662 continue;
2663 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2664 if (!ElementCI) {
2665 Known.resetAll();
2666 return;
2667 }
2668 const APInt &Elt = ElementCI->getValue();
2669 Known.Zero &= ~Elt;
2670 Known.One &= Elt;
2671 }
2672 if (Known.hasConflict())
2673 Known.resetAll();
2674 return;
2675 }
2676
2677 // Start out not knowing anything.
2678 Known.resetAll();
2679
2680 // We can't imply anything about undefs.
2681 if (isa<UndefValue>(V))
2682 return;
2683
2684 // There's no point in looking through other users of ConstantData for
2685 // assumptions. Confirm that we've handled them all.
2686 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2687
2688 if (const auto *A = dyn_cast<Argument>(V))
2689 if (std::optional<ConstantRange> Range = A->getRange())
2690 Known = Range->toKnownBits();
2691
2692 // All recursive calls that increase depth must come after this.
2694 return;
2695
2696 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2697 // the bits of its aliasee.
2698 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2699 if (!GA->isInterposable())
2700 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2701 return;
2702 }
2703
2704 if (const Operator *I = dyn_cast<Operator>(V))
2705 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2706 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2707 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2708 Known = CR->toKnownBits();
2709 }
2710
2711 // Aligned pointers have trailing zeros - refine Known.Zero set
2712 if (isa<PointerType>(V->getType())) {
2713 Align Alignment = V->getPointerAlignment(Q.DL);
2714 Known.Zero.setLowBits(Log2(Alignment));
2715 }
2716
2717 // computeKnownBitsFromContext strictly refines Known.
2718 // Therefore, we run them after computeKnownBitsFromOperator.
2719
2720 // Check whether we can determine known bits from context such as assumes.
2722}
2723
2724/// Try to detect a recurrence that the value of the induction variable is
2725/// always a power of two (or zero).
2726static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2727 SimplifyQuery &Q, unsigned Depth) {
2728 BinaryOperator *BO = nullptr;
2729 Value *Start = nullptr, *Step = nullptr;
2730 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2731 return false;
2732
2733 // Initial value must be a power of two.
2734 for (const Use &U : PN->operands()) {
2735 if (U.get() == Start) {
2736 // Initial value comes from a different BB, need to adjust context
2737 // instruction for analysis.
2738 Q.CtxI = PN->getIncomingBlock(U)->getTerminator();
2739 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2740 return false;
2741 }
2742 }
2743
2744 // Except for Mul, the induction variable must be on the left side of the
2745 // increment expression, otherwise its value can be arbitrary.
2746 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2747 return false;
2748
2749 Q.CtxI = BO->getParent()->getTerminator();
2750 switch (BO->getOpcode()) {
2751 case Instruction::Mul:
2752 // Power of two is closed under multiplication.
2753 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2754 Q.IIQ.hasNoSignedWrap(BO)) &&
2755 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2756 case Instruction::SDiv:
2757 // Start value must not be signmask for signed division, so simply being a
2758 // power of two is not sufficient, and it has to be a constant.
2759 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2760 return false;
2761 [[fallthrough]];
2762 case Instruction::UDiv:
2763 // Divisor must be a power of two.
2764 // If OrZero is false, cannot guarantee induction variable is non-zero after
2765 // division, same for Shr, unless it is exact division.
2766 return (OrZero || Q.IIQ.isExact(BO)) &&
2767 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2768 case Instruction::Shl:
2769 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2770 case Instruction::AShr:
2771 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2772 return false;
2773 [[fallthrough]];
2774 case Instruction::LShr:
2775 return OrZero || Q.IIQ.isExact(BO);
2776 default:
2777 return false;
2778 }
2779}
2780
2781/// Return true if we can infer that \p V is known to be a power of 2 from
2782/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2783static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2784 const Value *Cond,
2785 bool CondIsTrue) {
2786 CmpPredicate Pred;
2787 const APInt *RHSC;
2788 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2789 return false;
2790 if (!CondIsTrue)
2791 Pred = ICmpInst::getInversePredicate(Pred);
2792 // ctpop(V) u< 2
2793 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2794 return true;
2795 // ctpop(V) == 1
2796 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2797}
2798
2799/// Return true if the given value is known to have exactly one
2800/// bit set when defined. For vectors return true if every element is known to
2801/// be a power of two when defined. Supports values with integer or pointer
2802/// types and vectors of integers.
2803bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2804 const SimplifyQuery &Q, unsigned Depth) {
2805 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2806
2807 if (isa<Constant>(V))
2808 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2809
2810 // i1 is by definition a power of 2 or zero.
2811 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2812 return true;
2813
2814 // Try to infer from assumptions.
2815 if (Q.AC && Q.CtxI) {
2816 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2817 if (!AssumeVH)
2818 continue;
2819 CallInst *I = cast<CallInst>(AssumeVH);
2820 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2821 /*CondIsTrue=*/true) &&
2823 return true;
2824 }
2825 }
2826
2827 // Handle dominating conditions.
2828 if (Q.DC && Q.CtxI && Q.DT) {
2829 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2830 Value *Cond = BI->getCondition();
2831
2832 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2834 /*CondIsTrue=*/true) &&
2835 Q.DT->dominates(Edge0, Q.CtxI->getParent()))
2836 return true;
2837
2838 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2840 /*CondIsTrue=*/false) &&
2841 Q.DT->dominates(Edge1, Q.CtxI->getParent()))
2842 return true;
2843 }
2844 }
2845
2846 auto *I = dyn_cast<Instruction>(V);
2847 if (!I)
2848 return false;
2849
2850 if (Q.CtxI && match(V, m_VScale())) {
2851 const Function *F = Q.CtxI->getFunction();
2852 // The vscale_range indicates vscale is a power-of-two.
2853 return F->hasFnAttribute(Attribute::VScaleRange);
2854 }
2855
2856 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2857 // it is shifted off the end then the result is undefined.
2858 if (match(I, m_Shl(m_One(), m_Value())))
2859 return true;
2860
2861 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2862 // the bottom. If it is shifted off the bottom then the result is undefined.
2863 if (match(I, m_LShr(m_SignMask(), m_Value())))
2864 return true;
2865
2866 // The remaining tests are all recursive, so bail out if we hit the limit.
2868 return false;
2869
2870 switch (I->getOpcode()) {
2871 case Instruction::ZExt:
2872 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2873 case Instruction::Trunc:
2874 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2875 case Instruction::Shl:
2876 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2877 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2878 return false;
2879 case Instruction::LShr:
2880 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2881 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2882 return false;
2883 case Instruction::UDiv:
2885 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2886 return false;
2887 case Instruction::Mul:
2888 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2889 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2890 (OrZero || isKnownNonZero(I, Q, Depth));
2891 case Instruction::And:
2892 // A power of two and'd with anything is a power of two or zero.
2893 if (OrZero &&
2894 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2895 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2896 return true;
2897 // X & (-X) is always a power of two or zero.
2898 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2899 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2900 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2901 return false;
2902 case Instruction::Add: {
2903 // Adding a power-of-two or zero to the same power-of-two or zero yields
2904 // either the original power-of-two, a larger power-of-two or zero.
2906 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2907 Q.IIQ.hasNoSignedWrap(VOBO)) {
2908 if (match(I->getOperand(0),
2909 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2910 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2911 return true;
2912 if (match(I->getOperand(1),
2913 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2914 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2915 return true;
2916
2917 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2918 KnownBits LHSBits(BitWidth);
2919 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2920
2921 KnownBits RHSBits(BitWidth);
2922 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2923 // If i8 V is a power of two or zero:
2924 // ZeroBits: 1 1 1 0 1 1 1 1
2925 // ~ZeroBits: 0 0 0 1 0 0 0 0
2926 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2927 // If OrZero isn't set, we cannot give back a zero result.
2928 // Make sure either the LHS or RHS has a bit set.
2929 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2930 return true;
2931 }
2932
2933 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2934 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2935 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2936 return true;
2937 return false;
2938 }
2939 case Instruction::Select:
2940 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2941 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2942 case Instruction::PHI: {
2943 // A PHI node is power of two if all incoming values are power of two, or if
2944 // it is an induction variable where in each step its value is a power of
2945 // two.
2946 auto *PN = cast<PHINode>(I);
2948
2949 // Check if it is an induction variable and always power of two.
2950 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2951 return true;
2952
2953 // Recursively check all incoming values. Limit recursion to 2 levels, so
2954 // that search complexity is limited to number of operands^2.
2955 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2956 return llvm::all_of(PN->operands(), [&](const Use &U) {
2957 // Value is power of 2 if it is coming from PHI node itself by induction.
2958 if (U.get() == PN)
2959 return true;
2960
2961 // Change the context instruction to the incoming block where it is
2962 // evaluated.
2963 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
2964 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2965 });
2966 }
2967 case Instruction::Invoke:
2968 case Instruction::Call: {
2969 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2970 switch (II->getIntrinsicID()) {
2971 case Intrinsic::umax:
2972 case Intrinsic::smax:
2973 case Intrinsic::umin:
2974 case Intrinsic::smin:
2975 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2976 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2977 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2978 // thus dont change pow2/non-pow2 status.
2979 case Intrinsic::bitreverse:
2980 case Intrinsic::bswap:
2981 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2982 case Intrinsic::fshr:
2983 case Intrinsic::fshl:
2984 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2985 if (II->getArgOperand(0) == II->getArgOperand(1))
2986 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2987 break;
2988 case Intrinsic::riscv_vsetvlimax:
2989 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2990 // for any valid vtype, so it is a power of two regardless of OrZero.
2991 return true;
2992 case Intrinsic::read_register:
2993 case Intrinsic::read_volatile_register: {
2994 // The RISC-V vlenb CSR holds VLEN/8, which is always a non-zero power
2995 // of two, so it is a power of two regardless of OrZero.
2996 const Module *M = II->getModule();
2997 if (!M || !M->getTargetTriple().isRISCV())
2998 break;
2999 return isReadVLENB(*II);
3000 }
3001 default:
3002 break;
3003 }
3004 }
3005 return false;
3006 }
3007 default:
3008 return false;
3009 }
3010}
3011
3012/// Test whether a GEP's result is known to be non-null.
3013///
3014/// Uses properties inherent in a GEP to try to determine whether it is known
3015/// to be non-null.
3016///
3017/// Currently this routine does not support vector GEPs.
3018static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
3019 unsigned Depth) {
3020 const Function *F = nullptr;
3021 if (const Instruction *I = dyn_cast<Instruction>(GEP))
3022 F = I->getFunction();
3023
3024 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
3025 // may be null iff the base pointer is null and the offset is zero.
3026 if (!GEP->hasNoUnsignedWrap() &&
3027 !(GEP->isInBounds() &&
3028 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
3029 return false;
3030
3031 // FIXME: Support vector-GEPs.
3032 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
3033
3034 // If the base pointer is non-null, we cannot walk to a null address with an
3035 // inbounds GEP in address space zero.
3036 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
3037 return true;
3038
3039 // Walk the GEP operands and see if any operand introduces a non-zero offset.
3040 // If so, then the GEP cannot produce a null pointer, as doing so would
3041 // inherently violate the inbounds contract within address space zero.
3043 GTI != GTE; ++GTI) {
3044 // Struct types are easy -- they must always be indexed by a constant.
3045 if (StructType *STy = GTI.getStructTypeOrNull()) {
3046 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
3047 unsigned ElementIdx = OpC->getZExtValue();
3048 const StructLayout *SL = Q.DL.getStructLayout(STy);
3049 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
3050 if (ElementOffset > 0)
3051 return true;
3052 continue;
3053 }
3054
3055 // If we have a zero-sized type, the index doesn't matter. Keep looping.
3056 if (GTI.getSequentialElementStride(Q.DL).isZero())
3057 continue;
3058
3059 // Fast path the constant operand case both for efficiency and so we don't
3060 // increment Depth when just zipping down an all-constant GEP.
3061 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
3062 if (!OpC->isZero())
3063 return true;
3064 continue;
3065 }
3066
3067 // We post-increment Depth here because while isKnownNonZero increments it
3068 // as well, when we pop back up that increment won't persist. We don't want
3069 // to recurse 10k times just because we have 10k GEP operands. We don't
3070 // bail completely out because we want to handle constant GEPs regardless
3071 // of depth.
3073 continue;
3074
3075 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
3076 return true;
3077 }
3078
3079 return false;
3080}
3081
3083 const Instruction *CtxI,
3084 const DominatorTree *DT) {
3085 assert(!isa<Constant>(V) && "Called for constant?");
3086
3087 if (!CtxI || !DT)
3088 return false;
3089
3090 unsigned NumUsesExplored = 0;
3091 for (auto &U : V->uses()) {
3092 // Avoid massive lists
3093 if (NumUsesExplored >= DomConditionsMaxUses)
3094 break;
3095 NumUsesExplored++;
3096
3097 const Instruction *UI = cast<Instruction>(U.getUser());
3098 // If the value is used as an argument to a call or invoke, then argument
3099 // attributes may provide an answer about null-ness.
3100 if (V->getType()->isPointerTy()) {
3101 if (const auto *CB = dyn_cast<CallBase>(UI)) {
3102 if (CB->isArgOperand(&U) &&
3103 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
3104 /*AllowUndefOrPoison=*/false) &&
3105 DT->dominates(CB, CtxI))
3106 return true;
3107 }
3108 }
3109
3110 // If the value is used as a load/store, then the pointer must be non null.
3111 if (V == getLoadStorePointerOperand(UI)) {
3114 DT->dominates(UI, CtxI))
3115 return true;
3116 }
3117
3118 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
3119 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
3120 isValidAssumeForContext(UI, CtxI, DT))
3121 return true;
3122
3123 // Consider only compare instructions uniquely controlling a branch
3124 Value *RHS;
3125 CmpPredicate Pred;
3126 bool NonNullIfTrue;
3127 if (match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS)))) {
3128 if (cmpExcludesZero(Pred, RHS))
3129 NonNullIfTrue = true;
3131 NonNullIfTrue = false;
3132 else
3133 continue;
3134 } else if (UI->getType()->isIntegerTy(1) &&
3135 match(UI, m_Trunc(m_Specific(V)))) {
3136 NonNullIfTrue = true;
3137 } else
3138 continue;
3139
3142 for (const auto *CmpU : UI->users()) {
3143 assert(WorkList.empty() && "Should be!");
3144 if (Visited.insert(CmpU).second)
3145 WorkList.push_back(CmpU);
3146
3147 while (!WorkList.empty()) {
3148 auto *Curr = WorkList.pop_back_val();
3149
3150 // If a user is an AND, add all its users to the work list. We only
3151 // propagate "pred != null" condition through AND because it is only
3152 // correct to assume that all conditions of AND are met in true branch.
3153 // TODO: Support similar logic of OR and EQ predicate?
3154 if (NonNullIfTrue)
3155 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3156 for (const auto *CurrU : Curr->users())
3157 if (Visited.insert(CurrU).second)
3158 WorkList.push_back(CurrU);
3159 continue;
3160 }
3161
3162 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3163 BasicBlock *NonNullSuccessor =
3164 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3165 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3166 if (DT->dominates(Edge, CtxI->getParent()))
3167 return true;
3168 } else if (NonNullIfTrue && isGuard(Curr) &&
3169 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3170 return true;
3171 }
3172 }
3173 }
3174 }
3175
3176 return false;
3177}
3178
3179/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3180/// ensure that the value it's attached to is never Value? 'RangeType' is
3181/// is the type of the value described by the range.
3182static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3183 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3184 assert(NumRanges >= 1);
3185 for (unsigned i = 0; i < NumRanges; ++i) {
3187 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3189 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3190 ConstantRange Range(Lower->getValue(), Upper->getValue());
3191 if (Range.contains(Value))
3192 return false;
3193 }
3194 return true;
3195}
3196
3197/// Try to detect a recurrence that monotonically increases/decreases from a
3198/// non-zero starting value. These are common as induction variables.
3199static bool isNonZeroRecurrence(const PHINode *PN) {
3200 BinaryOperator *BO = nullptr;
3201 Value *Start = nullptr, *Step = nullptr;
3202 const APInt *StartC, *StepC;
3203 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3204 !match(Start, m_APInt(StartC)) || StartC->isZero())
3205 return false;
3206
3207 switch (BO->getOpcode()) {
3208 case Instruction::Add:
3209 // Starting from non-zero and stepping away from zero can never wrap back
3210 // to zero.
3211 return BO->hasNoUnsignedWrap() ||
3212 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3213 StartC->isNegative() == StepC->isNegative());
3214 case Instruction::Mul:
3215 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3216 match(Step, m_APInt(StepC)) && !StepC->isZero();
3217 case Instruction::Shl:
3218 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3219 case Instruction::AShr:
3220 case Instruction::LShr:
3221 return BO->isExact();
3222 case Instruction::Or:
3223 return true;
3224 default:
3225 return false;
3226 }
3227}
3228
3229static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3231 m_Specific(Op1), m_Zero()))) ||
3233 m_Specific(Op0), m_Zero())));
3234}
3235
3236/// Return true if "addr(P) + Off" cannot be zero. The object P points to
3237/// cannot cross the unsigned address space boundary, including the address one
3238/// past its end, so an offset that stays within the object cannot wrap around
3239/// to zero. This holds even if the object starts at the zero address, which is
3240/// all that null_pointer_is_valid permits, so a non-zero offset is enough.
3242 Value *Y) {
3243 const APInt *Off;
3244 if (!match(Y, m_APInt(Off)) || Off->isZero())
3245 return false;
3246
3247 // ptrtoaddr always produces the address. ptrtoint only does so when its
3248 // result is at least as wide as the address: a narrower result is truncated
3249 // and may wrap to zero, while bits above the address can only make the
3250 // result more non-zero.
3251 Value *P;
3252 if (!match(X, m_PtrToAddr(m_Value(P))) &&
3253 !(match(X, m_PtrToInt(m_Value(P))) &&
3254 X->getType()->getScalarSizeInBits() >=
3255 Q.DL.getAddressSizeInBits(P->getType())))
3256 return false;
3257
3258 // A vector of pointers has no single object whose size can be taken, and
3259 // getPointerDereferenceableBytes() requires a plain pointer.
3260 if (!P->getType()->isPointerTy())
3261 return false;
3262
3263 bool CanBeNull;
3264 uint64_t DerefBytes = P->getPointerDereferenceableBytes(
3265 Q.DL, CanBeNull, /*CanBeFreed=*/nullptr);
3266 if (CanBeNull || DerefBytes == 0 || !Off->ule(DerefBytes))
3267 return false;
3268
3269 return true;
3270}
3271
3272static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3273 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3274 bool NUW, unsigned Depth) {
3276 return true;
3277
3278 // (X + (X != 0)) is non zero
3279 if (matchOpWithOpEqZero(X, Y))
3280 return true;
3281
3282 if (NUW)
3283 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3284 isKnownNonZero(X, DemandedElts, Q, Depth);
3285
3286 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3287 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3288
3289 // If X and Y are both non-negative (as signed values) then their sum is not
3290 // zero unless both X and Y are zero.
3291 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3292 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3293 isKnownNonZero(X, DemandedElts, Q, Depth))
3294 return true;
3295
3296 // If X and Y are both negative (as signed values) then their sum is not
3297 // zero unless both X and Y equal INT_MIN.
3298 if (XKnown.isNegative() && YKnown.isNegative()) {
3300 // The sign bit of X is set. If some other bit is set then X is not equal
3301 // to INT_MIN.
3302 if (XKnown.One.intersects(Mask))
3303 return true;
3304 // The sign bit of Y is set. If some other bit is set then Y is not equal
3305 // to INT_MIN.
3306 if (YKnown.One.intersects(Mask))
3307 return true;
3308 }
3309
3310 // The sum of a non-negative number and a power of two is not zero.
3311 if (XKnown.isNonNegative() &&
3312 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3313 return true;
3314 if (YKnown.isNonNegative() &&
3315 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3316 return true;
3317
3318 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3319}
3320
3321static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3322 unsigned BitWidth, Value *X, Value *Y,
3323 unsigned Depth) {
3324 // (X - (X != 0)) is non zero
3325 // ((X != 0) - X) is non zero
3326 if (matchOpWithOpEqZero(X, Y))
3327 return true;
3328
3329 // TODO: Move this case into isKnownNonEqual().
3330 if (auto *C = dyn_cast<Constant>(X))
3331 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3332 return true;
3333
3334 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3335}
3336
3337static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3338 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3339 bool NUW, unsigned Depth) {
3340 // If X and Y are non-zero then so is X * Y as long as the multiplication
3341 // does not overflow.
3342 if (NSW || NUW)
3343 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3344 isKnownNonZero(Y, DemandedElts, Q, Depth);
3345
3346 // If either X or Y is odd, then if the other is non-zero the result can't
3347 // be zero.
3348 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3349 if (XKnown.One[0])
3350 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3351
3352 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3353 if (YKnown.One[0])
3354 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3355
3356 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3357 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3358 // the lowest known One of X and Y. If they are non-zero, the result
3359 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3360 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3361 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3362 BitWidth;
3363}
3364
3365static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3366 const SimplifyQuery &Q, const KnownBits &KnownVal,
3367 unsigned Depth) {
3368 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3369 switch (I->getOpcode()) {
3370 case Instruction::Shl:
3371 return Lhs.shl(Rhs);
3372 case Instruction::LShr:
3373 return Lhs.lshr(Rhs);
3374 case Instruction::AShr:
3375 return Lhs.ashr(Rhs);
3376 default:
3377 llvm_unreachable("Unknown Shift Opcode");
3378 }
3379 };
3380
3381 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3382 switch (I->getOpcode()) {
3383 case Instruction::Shl:
3384 return Lhs.lshr(Rhs);
3385 case Instruction::LShr:
3386 case Instruction::AShr:
3387 return Lhs.shl(Rhs);
3388 default:
3389 llvm_unreachable("Unknown Shift Opcode");
3390 }
3391 };
3392
3393 if (KnownVal.isUnknown())
3394 return false;
3395
3396 KnownBits KnownCnt =
3397 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3398 APInt MaxShift = KnownCnt.getMaxValue();
3399 unsigned NumBits = KnownVal.getBitWidth();
3400 if (MaxShift.uge(NumBits))
3401 return false;
3402
3403 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3404 return true;
3405
3406 // If all of the bits shifted out are known to be zero, and Val is known
3407 // non-zero then at least one non-zero bit must remain.
3408 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3409 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3410 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3411 return true;
3412
3413 return false;
3414}
3415
3417 const APInt &DemandedElts,
3418 const SimplifyQuery &Q, unsigned Depth) {
3419 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3420 switch (I->getOpcode()) {
3421 case Instruction::Alloca:
3422 // Alloca never returns null, malloc might.
3423 return I->getType()->getPointerAddressSpace() == 0;
3424 case Instruction::GetElementPtr:
3425 if (I->getType()->isPointerTy())
3427 break;
3428 case Instruction::BitCast: {
3429 // We need to be a bit careful here. We can only peek through the bitcast
3430 // if the scalar size of elements in the operand are smaller than and a
3431 // multiple of the size they are casting too. Take three cases:
3432 //
3433 // 1) Unsafe:
3434 // bitcast <2 x i16> %NonZero to <4 x i8>
3435 //
3436 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3437 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3438 // guranteed (imagine just sign bit set in the 2 i16 elements).
3439 //
3440 // 2) Unsafe:
3441 // bitcast <4 x i3> %NonZero to <3 x i4>
3442 //
3443 // Even though the scalar size of the src (`i3`) is smaller than the
3444 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3445 // its possible for the `3 x i4` elements to be zero because there are
3446 // some elements in the destination that don't contain any full src
3447 // element.
3448 //
3449 // 3) Safe:
3450 // bitcast <4 x i8> %NonZero to <2 x i16>
3451 //
3452 // This is always safe as non-zero in the 4 i8 elements implies
3453 // non-zero in the combination of any two adjacent ones. Since i8 is a
3454 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3455 // This all implies the 2 i16 elements are non-zero.
3456 Type *FromTy = I->getOperand(0)->getType();
3457 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3458 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3459 return isKnownNonZero(I->getOperand(0), Q, Depth);
3460 } break;
3461 case Instruction::IntToPtr:
3462 // Note that we have to take special care to avoid looking through
3463 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3464 // as casts that can alter the value, e.g., AddrSpaceCasts.
3465 if (!isa<ScalableVectorType>(I->getType()) &&
3466 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3467 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3468 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3469 break;
3470 case Instruction::PtrToAddr:
3471 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3472 // so we can directly forward.
3473 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3474 case Instruction::PtrToInt:
3475 // For inttoptr, make sure the result size is >= the address size. If the
3476 // address is non-zero, any larger value is also non-zero.
3477 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3478 I->getType()->getScalarSizeInBits())
3479 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3480 break;
3481 case Instruction::Trunc:
3482 // nuw/nsw trunc preserves zero/non-zero status of input.
3483 if (auto *TI = dyn_cast<TruncInst>(I))
3484 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3485 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3486 break;
3487
3488 // Iff x - y != 0, then x ^ y != 0
3489 // Therefore we can do the same exact checks
3490 case Instruction::Xor:
3491 case Instruction::Sub:
3492 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3493 I->getOperand(1), Depth);
3494 case Instruction::Or:
3495 // (X | (X != 0)) is non zero
3496 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3497 return true;
3498 // X | Y != 0 if X != Y.
3499 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3500 Depth))
3501 return true;
3502 // X | Y != 0 if X != 0 or Y != 0.
3503 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3504 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3505 case Instruction::SExt:
3506 case Instruction::ZExt:
3507 // ext X != 0 if X != 0.
3508 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3509
3510 case Instruction::Shl: {
3511 // shl nsw/nuw can't remove any non-zero bits.
3513 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3514 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3515
3516 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3517 // if the lowest bit is shifted off the end.
3519 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3520 if (Known.One[0])
3521 return true;
3522
3523 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3524 }
3525 case Instruction::LShr:
3526 case Instruction::AShr: {
3527 // shr exact can only shift out zero bits.
3529 if (BO->isExact())
3530 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3531
3532 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3533 // defined if the sign bit is shifted off the end.
3535 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3536 if (Known.isNegative())
3537 return true;
3538
3539 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3540 // position >= C, because the sum >= max(A, B).
3541 Value *A, *B;
3542 const APInt *C;
3543 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3544 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3545 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3546 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3547 if (!KnownA.One.lshr(*C).isZero())
3548 return true;
3549 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3550 if (!KnownB.One.lshr(*C).isZero())
3551 return true;
3552 }
3553
3554 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3555 }
3556 case Instruction::UDiv:
3557 case Instruction::SDiv: {
3558 // X / Y
3559 // div exact can only produce a zero if the dividend is zero.
3560 if (cast<PossiblyExactOperator>(I)->isExact())
3561 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3562
3563 KnownBits XKnown =
3564 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3565 // If X is fully unknown we won't be able to figure anything out so don't
3566 // both computing knownbits for Y.
3567 if (XKnown.isUnknown())
3568 return false;
3569
3570 KnownBits YKnown =
3571 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3572 if (I->getOpcode() == Instruction::SDiv) {
3573 // For signed division need to compare abs value of the operands.
3574 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3575 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3576 }
3577 // If X u>= Y then div is non zero (0/0 is UB).
3578 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3579 // If X is total unknown or X u< Y we won't be able to prove non-zero
3580 // with compute known bits so just return early.
3581 return XUgeY && *XUgeY;
3582 }
3583 case Instruction::Add: {
3584 // X + Y.
3585
3586 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3587 // non-zero.
3589 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3590 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3591 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3592 }
3593 case Instruction::Mul: {
3595 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3596 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3597 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3598 }
3599 case Instruction::Select: {
3600 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3601
3602 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3603 // then see if the select condition implies the arm is non-zero. For example
3604 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3605 // dominated by `X != 0`.
3606 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3607 Value *Op;
3608 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3609 // Op is trivially non-zero.
3610 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3611 return true;
3612
3613 // The condition of the select dominates the true/false arm. Check if the
3614 // condition implies that a given arm is non-zero.
3615 Value *X;
3616 CmpPredicate Pred;
3617 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3618 return false;
3619
3620 if (!IsTrueArm)
3621 Pred = ICmpInst::getInversePredicate(Pred);
3622
3623 return cmpExcludesZero(Pred, X);
3624 };
3625
3626 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3627 SelectArmIsNonZero(/* IsTrueArm */ false))
3628 return true;
3629 break;
3630 }
3631 case Instruction::PHI: {
3632 auto *PN = cast<PHINode>(I);
3634 return true;
3635
3636 // Check if all incoming values are non-zero using recursion.
3638 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3639 return llvm::all_of(PN->operands(), [&](const Use &U) {
3640 if (U.get() == PN)
3641 return true;
3642 RecQ.CtxI = PN->getIncomingBlock(U)->getTerminator();
3643 // Check if the branch on the phi excludes zero.
3644 CmpPredicate Pred;
3645 Value *X;
3646 BasicBlock *TrueSucc, *FalseSucc;
3647 if (match(RecQ.CtxI,
3648 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3649 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3650 // Check for cases of duplicate successors.
3651 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3652 // If we're using the false successor, invert the predicate.
3653 if (FalseSucc == PN->getParent())
3654 Pred = CmpInst::getInversePredicate(Pred);
3655 if (cmpExcludesZero(Pred, X))
3656 return true;
3657 }
3658 }
3659 // Finally recurse on the edge and check it directly.
3660 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3661 });
3662 }
3663 case Instruction::InsertElement: {
3664 if (isa<ScalableVectorType>(I->getType()))
3665 break;
3666
3667 const Value *Vec = I->getOperand(0);
3668 const Value *Elt = I->getOperand(1);
3669 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3670
3671 unsigned NumElts = DemandedElts.getBitWidth();
3672 APInt DemandedVecElts = DemandedElts;
3673 bool SkipElt = false;
3674 // If we know the index we are inserting too, clear it from Vec check.
3675 if (CIdx && CIdx->getValue().ult(NumElts)) {
3676 DemandedVecElts.clearBit(CIdx->getZExtValue());
3677 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3678 }
3679
3680 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3681 // are non-zero.
3682 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3683 (DemandedVecElts.isZero() ||
3684 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3685 }
3686 case Instruction::ExtractElement:
3687 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3688 const Value *Vec = EEI->getVectorOperand();
3689 const Value *Idx = EEI->getIndexOperand();
3690 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3691 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3692 unsigned NumElts = VecTy->getNumElements();
3693 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3694 if (CIdx && CIdx->getValue().ult(NumElts))
3695 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3696 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3697 }
3698 }
3699 break;
3700 case Instruction::ShuffleVector: {
3701 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3702 if (!Shuf)
3703 break;
3704 APInt DemandedLHS, DemandedRHS;
3705 // For undef elements, we don't know anything about the common state of
3706 // the shuffle result.
3707 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3708 break;
3709 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3710 return (DemandedRHS.isZero() ||
3711 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3712 (DemandedLHS.isZero() ||
3713 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3714 }
3715 case Instruction::Freeze:
3716 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3717 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CtxI, Q.DT,
3718 Depth);
3719 case Instruction::Load: {
3720 auto *LI = cast<LoadInst>(I);
3721 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3722 // is never null.
3723 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3724 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3725 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3726 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3727 return true;
3728 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3730 }
3731
3732 // No need to fall through to computeKnownBits as range metadata is already
3733 // handled in isKnownNonZero.
3734 return false;
3735 }
3736 case Instruction::ExtractValue: {
3737 const WithOverflowInst *WO;
3739 switch (WO->getBinaryOp()) {
3740 default:
3741 break;
3742 case Instruction::Add:
3743 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3744 WO->getArgOperand(1),
3745 /*NSW=*/false,
3746 /*NUW=*/false, Depth);
3747 case Instruction::Sub:
3748 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3749 WO->getArgOperand(1), Depth);
3750 case Instruction::Mul:
3751 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3752 WO->getArgOperand(1),
3753 /*NSW=*/false, /*NUW=*/false, Depth);
3754 break;
3755 }
3756 }
3757 break;
3758 }
3759 case Instruction::Call:
3760 case Instruction::Invoke: {
3761 const auto *Call = cast<CallBase>(I);
3762 if (I->getType()->isPointerTy()) {
3763 if (Call->isReturnNonNull())
3764 return true;
3765 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3766 Call, /*MustPreserveOffset=*/true))
3767 return isKnownNonZero(RP, Q, Depth);
3768 } else {
3769 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3771 if (std::optional<ConstantRange> Range = Call->getRange()) {
3772 const APInt ZeroValue(Range->getBitWidth(), 0);
3773 if (!Range->contains(ZeroValue))
3774 return true;
3775 }
3776 if (const Value *RV = Call->getReturnedArgOperand())
3777 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3778 return true;
3779 }
3780
3781 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3782 switch (II->getIntrinsicID()) {
3783 case Intrinsic::sshl_sat:
3784 case Intrinsic::ushl_sat:
3785 case Intrinsic::abs:
3786 case Intrinsic::bitreverse:
3787 case Intrinsic::bswap:
3788 case Intrinsic::ctpop:
3789 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3790 // NB: We don't do usub_sat here as in any case we can prove its
3791 // non-zero, we will fold it to `sub nuw` in InstCombine.
3792 case Intrinsic::ssub_sat:
3793 // For most types, if x != y then ssub.sat x, y != 0. But
3794 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3795 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3796 if (BitWidth == 1)
3797 return false;
3798 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3799 II->getArgOperand(1), Depth);
3800 case Intrinsic::sadd_sat:
3801 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3802 II->getArgOperand(1),
3803 /*NSW=*/true, /* NUW=*/false, Depth);
3804 // Vec reverse preserves zero/non-zero status from input vec.
3805 case Intrinsic::vector_reverse:
3806 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3807 Q, Depth);
3808 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3809 case Intrinsic::vector_reduce_or:
3810 case Intrinsic::vector_reduce_umax:
3811 case Intrinsic::vector_reduce_umin:
3812 case Intrinsic::vector_reduce_smax:
3813 case Intrinsic::vector_reduce_smin:
3814 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3815 case Intrinsic::umax:
3816 case Intrinsic::uadd_sat:
3817 // umax(X, (X != 0)) is non zero
3818 // X +usat (X != 0) is non zero
3819 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3820 return true;
3821
3822 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3823 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3824 case Intrinsic::smax: {
3825 // If either arg is strictly positive the result is non-zero. Otherwise
3826 // the result is non-zero if both ops are non-zero.
3827 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3828 const KnownBits &OpKnown) {
3829 if (!OpNonZero.has_value())
3830 OpNonZero = OpKnown.isNonZero() ||
3831 isKnownNonZero(Op, DemandedElts, Q, Depth);
3832 return *OpNonZero;
3833 };
3834 // Avoid re-computing isKnownNonZero.
3835 std::optional<bool> Op0NonZero, Op1NonZero;
3836 KnownBits Op1Known =
3837 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3838 if (Op1Known.isNonNegative() &&
3839 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3840 return true;
3841 KnownBits Op0Known =
3842 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3843 if (Op0Known.isNonNegative() &&
3844 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3845 return true;
3846 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3847 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3848 }
3849 case Intrinsic::smin: {
3850 // If either arg is negative the result is non-zero. Otherwise
3851 // the result is non-zero if both ops are non-zero.
3852 KnownBits Op1Known =
3853 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3854 if (Op1Known.isNegative())
3855 return true;
3856 KnownBits Op0Known =
3857 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3858 if (Op0Known.isNegative())
3859 return true;
3860
3861 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3862 return true;
3863 }
3864 [[fallthrough]];
3865 case Intrinsic::umin:
3866 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3867 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3868 case Intrinsic::cttz:
3869 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3870 .Zero[0];
3871 case Intrinsic::ctlz:
3872 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3873 .isNonNegative();
3874 case Intrinsic::fshr:
3875 case Intrinsic::fshl:
3876 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3877 if (II->getArgOperand(0) == II->getArgOperand(1))
3878 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3879 break;
3880 case Intrinsic::vscale:
3881 return true;
3882 case Intrinsic::experimental_get_vector_length:
3883 return isKnownNonZero(I->getOperand(0), Q, Depth);
3884 default:
3885 break;
3886 }
3887 break;
3888 }
3889
3890 return false;
3891 }
3892 }
3893
3895 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3896 return Known.One != 0;
3897}
3898
3899/// Return true if the given value is known to be non-zero when defined. For
3900/// vectors, return true if every demanded element is known to be non-zero when
3901/// defined. For pointers, if the context instruction and dominator tree are
3902/// specified, perform context-sensitive analysis and return true if the
3903/// pointer couldn't possibly be null at the specified instruction.
3904/// Supports values with integer or pointer type and vectors of integers.
3905bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3906 const SimplifyQuery &Q, unsigned Depth) {
3907 Type *Ty = V->getType();
3908
3909#ifndef NDEBUG
3910 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3911
3912 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3913 assert(
3914 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3915 "DemandedElt width should equal the fixed vector number of elements");
3916 } else {
3917 assert(DemandedElts == APInt(1, 1) &&
3918 "DemandedElt width should be 1 for scalars");
3919 }
3920#endif
3921
3922 if (auto *C = dyn_cast<Constant>(V)) {
3923 if (C->isNullValue())
3924 return false;
3925 if (isa<ConstantInt>(C))
3926 // Must be non-zero due to null test above.
3927 return true;
3928
3929 // For constant vectors, check that all elements are poison or known
3930 // non-zero to determine that the whole vector is known non-zero.
3931 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3932 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3933 if (!DemandedElts[i])
3934 continue;
3935 Constant *Elt = C->getAggregateElement(i);
3936 if (!Elt || Elt->isNullValue())
3937 return false;
3938 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3939 return false;
3940 }
3941 return true;
3942 }
3943
3944 // Constant ptrauth can be null, iff the base pointer can be.
3945 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3946 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3947
3948 // A global variable is non null unless extern weak or an absolute symbol
3949 // reference. An alias is also excluded, as it may resolve to a weak
3950 // undefined symbol and thus to the null address. Where null is a valid
3951 // address an allocation may start there, so nothing can be assumed; that
3952 // covers both null_pointer_is_valid and address spaces other than zero.
3953 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3955 GV->getType()->getAddressSpace()) &&
3956 !GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3957 !isa<GlobalAlias>(GV))
3958 return true;
3959 }
3960
3961 // For constant expressions, fall through to the Operator code below.
3962 if (!isa<ConstantExpr>(V))
3963 return false;
3964 }
3965
3966 if (const auto *A = dyn_cast<Argument>(V))
3967 if (std::optional<ConstantRange> Range = A->getRange()) {
3968 const APInt ZeroValue(Range->getBitWidth(), 0);
3969 if (!Range->contains(ZeroValue))
3970 return true;
3971 }
3972
3973 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3974 return true;
3975
3976 // Some of the tests below are recursive, so bail out if we hit the limit.
3978 return false;
3979
3980 // Check for pointer simplifications.
3981
3982 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3983 // A byval, inalloca may not be null in a non-default addres space. A
3984 // nonnull argument is assumed never 0.
3985 if (const Argument *A = dyn_cast<Argument>(V)) {
3986 if (((A->hasPassPointeeByValueCopyAttr() &&
3987 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3988 A->hasNonNullAttr()))
3989 return true;
3990 }
3991 }
3992
3993 if (const auto *I = dyn_cast<Operator>(V))
3994 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3995 return true;
3996
3997 if (!isa<Constant>(V) &&
3999 return true;
4000
4001 if (const Value *Stripped = stripNullTest(V))
4002 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
4003
4004 return false;
4005}
4006
4008 unsigned Depth) {
4009 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
4010 APInt DemandedElts =
4011 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
4012 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
4013}
4014
4015/// If the pair of operators are the same invertible function, return the
4016/// the operands of the function corresponding to each input. Otherwise,
4017/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
4018/// every input value to exactly one output value. This is equivalent to
4019/// saying that Op1 and Op2 are equal exactly when the specified pair of
4020/// operands are equal, (except that Op1 and Op2 may be poison more often.)
4021static std::optional<std::pair<Value*, Value*>>
4023 const Operator *Op2) {
4024 if (Op1->getOpcode() != Op2->getOpcode())
4025 return std::nullopt;
4026
4027 auto getOperands = [&](unsigned OpNum) -> auto {
4028 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
4029 };
4030
4031 switch (Op1->getOpcode()) {
4032 default:
4033 break;
4034 case Instruction::Or:
4035 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
4036 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
4037 break;
4038 [[fallthrough]];
4039 case Instruction::Xor:
4040 case Instruction::Add: {
4041 Value *Other;
4042 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
4043 return std::make_pair(Op1->getOperand(1), Other);
4044 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
4045 return std::make_pair(Op1->getOperand(0), Other);
4046 break;
4047 }
4048 case Instruction::Sub:
4049 if (Op1->getOperand(0) == Op2->getOperand(0))
4050 return getOperands(1);
4051 if (Op1->getOperand(1) == Op2->getOperand(1))
4052 return getOperands(0);
4053 break;
4054 case Instruction::Mul: {
4055 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
4056 // and N is the bitwdith. The nsw case is non-obvious, but proven by
4057 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
4058 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4059 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4060 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4061 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4062 break;
4063
4064 // Assume operand order has been canonicalized
4065 if (Op1->getOperand(1) == Op2->getOperand(1) &&
4066 isa<ConstantInt>(Op1->getOperand(1)) &&
4067 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
4068 return getOperands(0);
4069 break;
4070 }
4071 case Instruction::Shl: {
4072 // Same as multiplies, with the difference that we don't need to check
4073 // for a non-zero multiply. Shifts always multiply by non-zero.
4074 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
4075 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
4076 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
4077 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
4078 break;
4079
4080 if (Op1->getOperand(1) == Op2->getOperand(1))
4081 return getOperands(0);
4082 break;
4083 }
4084 case Instruction::AShr:
4085 case Instruction::LShr: {
4086 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
4087 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
4088 if (!PEO1->isExact() || !PEO2->isExact())
4089 break;
4090
4091 if (Op1->getOperand(1) == Op2->getOperand(1))
4092 return getOperands(0);
4093 break;
4094 }
4095 case Instruction::SExt:
4096 case Instruction::ZExt:
4097 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
4098 return getOperands(0);
4099 break;
4100 case Instruction::PHI: {
4101 const PHINode *PN1 = cast<PHINode>(Op1);
4102 const PHINode *PN2 = cast<PHINode>(Op2);
4103
4104 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
4105 // are a single invertible function of the start values? Note that repeated
4106 // application of an invertible function is also invertible
4107 BinaryOperator *BO1 = nullptr;
4108 Value *Start1 = nullptr, *Step1 = nullptr;
4109 BinaryOperator *BO2 = nullptr;
4110 Value *Start2 = nullptr, *Step2 = nullptr;
4111 if (PN1->getParent() != PN2->getParent() ||
4112 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
4113 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
4114 break;
4115
4117 cast<Operator>(BO2));
4118 if (!Values)
4119 break;
4120
4121 // We have to be careful of mutually defined recurrences here. Ex:
4122 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
4123 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
4124 // The invertibility of these is complicated, and not worth reasoning
4125 // about (yet?).
4126 if (Values->first != PN1 || Values->second != PN2)
4127 break;
4128
4129 return std::make_pair(Start1, Start2);
4130 }
4131 }
4132 return std::nullopt;
4133}
4134
4135/// Return true if V1 == (binop V2, X), where X is known non-zero.
4136/// Only handle a small subset of binops where (binop V2, X) with non-zero X
4137/// implies V2 != V1.
4138static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
4139 const APInt &DemandedElts,
4140 const SimplifyQuery &Q, unsigned Depth) {
4142 if (!BO)
4143 return false;
4144 switch (BO->getOpcode()) {
4145 default:
4146 break;
4147 case Instruction::Or:
4148 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
4149 break;
4150 [[fallthrough]];
4151 case Instruction::Xor:
4152 case Instruction::Add:
4153 Value *Op = nullptr;
4154 if (V2 == BO->getOperand(0))
4155 Op = BO->getOperand(1);
4156 else if (V2 == BO->getOperand(1))
4157 Op = BO->getOperand(0);
4158 else
4159 return false;
4160 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
4161 }
4162 return false;
4163}
4164
4165/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
4166/// the multiplication is nuw or nsw.
4167static bool isNonEqualMul(const Value *V1, const Value *V2,
4168 const APInt &DemandedElts, const SimplifyQuery &Q,
4169 unsigned Depth) {
4170 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4171 const APInt *C;
4172 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
4173 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4174 !C->isZero() && !C->isOne() &&
4175 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4176 }
4177 return false;
4178}
4179
4180/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
4181/// the shift is nuw or nsw.
4182static bool isNonEqualShl(const Value *V1, const Value *V2,
4183 const APInt &DemandedElts, const SimplifyQuery &Q,
4184 unsigned Depth) {
4185 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
4186 const APInt *C;
4187 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
4188 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
4189 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
4190 }
4191 return false;
4192}
4193
4194static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
4195 const APInt &DemandedElts, const SimplifyQuery &Q,
4196 unsigned Depth) {
4197 // Check two PHIs are in same block.
4198 if (PN1->getParent() != PN2->getParent())
4199 return false;
4200
4202 bool UsedFullRecursion = false;
4203 for (const BasicBlock *IncomBB : PN1->blocks()) {
4204 if (!VisitedBBs.insert(IncomBB).second)
4205 continue; // Don't reprocess blocks that we have dealt with already.
4206 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4207 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4208 const APInt *C1, *C2;
4209 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4210 continue;
4211
4212 // Only one pair of phi operands is allowed for full recursion.
4213 if (UsedFullRecursion)
4214 return false;
4215
4217 RecQ.CtxI = IncomBB->getTerminator();
4218 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4219 return false;
4220 UsedFullRecursion = true;
4221 }
4222 return true;
4223}
4224
4225static bool isNonEqualSelect(const Value *V1, const Value *V2,
4226 const APInt &DemandedElts, const SimplifyQuery &Q,
4227 unsigned Depth) {
4228 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4229 if (!SI1)
4230 return false;
4231
4232 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4233 const Value *Cond1 = SI1->getCondition();
4234 const Value *Cond2 = SI2->getCondition();
4235 if (Cond1 == Cond2)
4236 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4237 DemandedElts, Q, Depth + 1) &&
4238 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4239 DemandedElts, Q, Depth + 1);
4240 }
4241 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4242 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4243}
4244
4245// Check to see if A is both a GEP and is the incoming value for a PHI in the
4246// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4247// one of them being the recursive GEP A and the other a ptr at same base and at
4248// the same/higher offset than B we are only incrementing the pointer further in
4249// loop if offset of recursive GEP is greater than 0.
4251 const SimplifyQuery &Q) {
4252 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4253 return false;
4254
4255 auto *GEPA = dyn_cast<GEPOperator>(A);
4256 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4257 return false;
4258
4259 // Handle 2 incoming PHI values with one being a recursive GEP.
4260 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4261 if (!PN || PN->getNumIncomingValues() != 2)
4262 return false;
4263
4264 // Search for the recursive GEP as an incoming operand, and record that as
4265 // Step.
4266 Value *Start = nullptr;
4267 Value *Step = const_cast<Value *>(A);
4268 if (PN->getIncomingValue(0) == Step)
4269 Start = PN->getIncomingValue(1);
4270 else if (PN->getIncomingValue(1) == Step)
4271 Start = PN->getIncomingValue(0);
4272 else
4273 return false;
4274
4275 // Other incoming node base should match the B base.
4276 // StartOffset >= OffsetB && StepOffset > 0?
4277 // StartOffset <= OffsetB && StepOffset < 0?
4278 // Is non-equal if above are true.
4279 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4280 // optimisation to inbounds GEPs only.
4281 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4282 APInt StartOffset(IndexWidth, 0);
4283 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4284 APInt StepOffset(IndexWidth, 0);
4285 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4286
4287 // Check if Base Pointer of Step matches the PHI.
4288 if (Step != PN)
4289 return false;
4290 APInt OffsetB(IndexWidth, 0);
4291 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4292 return Start == B &&
4293 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4294 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4295}
4296
4297static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4298 const SimplifyQuery &Q, unsigned Depth) {
4299 if (!Q.CtxI)
4300 return false;
4301
4302 // Try to infer NonEqual based on information from dominating conditions.
4303 if (Q.DC && Q.DT) {
4304 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4305 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4306 Value *Cond = BI->getCondition();
4307 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4308 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()) &&
4310 /*LHSIsTrue=*/true, Depth)
4311 .value_or(false))
4312 return true;
4313
4314 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4315 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()) &&
4317 /*LHSIsTrue=*/false, Depth)
4318 .value_or(false))
4319 return true;
4320 }
4321
4322 return false;
4323 };
4324
4325 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4326 IsKnownNonEqualFromDominatingCondition(V2))
4327 return true;
4328 }
4329
4330 if (!Q.AC)
4331 return false;
4332
4333 // Try to infer NonEqual based on information from assumptions.
4334 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4335 if (!AssumeVH)
4336 continue;
4337 CallInst *I = cast<CallInst>(AssumeVH);
4338
4339 assert(I->getFunction() == Q.CtxI->getFunction() &&
4340 "Got assumption for the wrong function!");
4341 assert(I->getIntrinsicID() == Intrinsic::assume &&
4342 "must be an assume intrinsic");
4343
4344 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4345 /*LHSIsTrue=*/true, Depth)
4346 .value_or(false) &&
4348 return true;
4349 }
4350
4351 return false;
4352}
4353
4354static bool isNonEqualURem(const Value *X, const Value *Rem,
4355 const SimplifyQuery &Q) {
4356 const Value *Y;
4357 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4358 return false;
4359
4360 // For a defined urem, X != X urem Y exactly when X u>= Y.
4361 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4363 return true;
4364
4365 std::optional<bool> Implied =
4367 return Implied && *Implied;
4368}
4369
4370/// Return true if it is known that V1 != V2.
4371static bool isKnownNonEqual(const Value *V1, const Value *V2,
4372 const APInt &DemandedElts, const SimplifyQuery &Q,
4373 unsigned Depth) {
4374 if (V1 == V2)
4375 return false;
4376 if (V1->getType() != V2->getType())
4377 // We can't look through casts yet.
4378 return false;
4379
4381 return false;
4382
4383 // See if we can recurse through (exactly one of) our operands. This
4384 // requires our operation be 1-to-1 and map every input value to exactly
4385 // one output value. Such an operation is invertible.
4386 auto *O1 = dyn_cast<Operator>(V1);
4387 auto *O2 = dyn_cast<Operator>(V2);
4388 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4389 if (auto Values = getInvertibleOperands(O1, O2))
4390 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4391 Depth + 1);
4392
4393 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4394 const PHINode *PN2 = cast<PHINode>(V2);
4395 // FIXME: This is missing a generalization to handle the case where one is
4396 // a PHI and another one isn't.
4397 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4398 return true;
4399 };
4400 }
4401
4402 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4403 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4404 return true;
4405
4406 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4407 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4408 return true;
4409
4410 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4411 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4412 return true;
4413
4414 if (V1->getType()->isIntOrIntVectorTy()) {
4415 // Are any known bits in V1 contradictory to known bits in V2? If V1
4416 // has a known zero where V2 has a known one, they must not be equal.
4417 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4418 if (!Known1.isUnknown()) {
4419 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4420 if (Known1.Zero.intersects(Known2.One) ||
4421 Known2.Zero.intersects(Known1.One))
4422 return true;
4423 }
4424 }
4425
4426 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4427 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4428 return true;
4429
4432 return true;
4433
4434 Value *A, *B;
4435 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4436 // Check PtrToInt type matches the pointer size.
4437 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4439 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4440
4441 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4442 return true;
4443
4444 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4445 return true;
4446
4447 return false;
4448}
4449
4450/// For vector constants, loop over the elements and find the constant with the
4451/// minimum number of sign bits. Return 0 if the value is not a vector constant
4452/// or if any element was not analyzed; otherwise, return the count for the
4453/// element with the minimum number of sign bits.
4455 const APInt &DemandedElts,
4456 unsigned TyBits) {
4457 const auto *CV = dyn_cast<Constant>(V);
4458 if (!CV || !isa<FixedVectorType>(CV->getType()))
4459 return 0;
4460
4461 unsigned MinSignBits = TyBits;
4462 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4463 for (unsigned i = 0; i != NumElts; ++i) {
4464 if (!DemandedElts[i])
4465 continue;
4466 // If we find a non-ConstantInt, bail out.
4467 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4468 if (!Elt)
4469 return 0;
4470
4471 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4472 }
4473
4474 return MinSignBits;
4475}
4476
4477static unsigned ComputeNumSignBitsImpl(const Value *V,
4478 const APInt &DemandedElts,
4479 const SimplifyQuery &Q, unsigned Depth);
4480
4481static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4482 const SimplifyQuery &Q, unsigned Depth) {
4483 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4484 assert(Result > 0 && "At least one sign bit needs to be present!");
4485 return Result;
4486}
4487
4488/// Return the number of times the sign bit of the register is replicated into
4489/// the other bits. We know that at least 1 bit is always equal to the sign bit
4490/// (itself), but other cases can give us information. For example, immediately
4491/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4492/// other, so we return 3. For vectors, return the number of sign bits for the
4493/// vector element with the minimum number of known sign bits of the demanded
4494/// elements in the vector specified by DemandedElts.
4495static unsigned ComputeNumSignBitsImpl(const Value *V,
4496 const APInt &DemandedElts,
4497 const SimplifyQuery &Q, unsigned Depth) {
4498 Type *Ty = V->getType();
4499#ifndef NDEBUG
4500 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4501
4502 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4503 assert(
4504 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4505 "DemandedElt width should equal the fixed vector number of elements");
4506 } else {
4507 assert(DemandedElts == APInt(1, 1) &&
4508 "DemandedElt width should be 1 for scalars");
4509 }
4510#endif
4511
4512 // We return the minimum number of sign bits that are guaranteed to be present
4513 // in V, so for undef we have to conservatively return 1. We don't have the
4514 // same behavior for poison though -- that's a FIXME today.
4515
4516 Type *ScalarTy = Ty->getScalarType();
4517 unsigned TyBits = ScalarTy->isPointerTy() ?
4518 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4519 Q.DL.getTypeSizeInBits(ScalarTy);
4520
4521 unsigned Tmp, Tmp2;
4522 unsigned FirstAnswer = 1;
4523
4524 // Note that ConstantInt is handled by the general computeKnownBits case
4525 // below.
4526
4528 return 1;
4529
4530 if (auto *U = dyn_cast<Operator>(V)) {
4531 switch (Operator::getOpcode(V)) {
4532 default: break;
4533 case Instruction::BitCast: {
4534 Value *Src = U->getOperand(0);
4535 Type *SrcTy = Src->getType();
4536
4537 // Skip if the source type is not an integer or integer vector type
4538 // This ensures we only process integer-like types
4539 if (!SrcTy->isIntOrIntVectorTy())
4540 break;
4541
4542 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4543
4544 // Bitcast 'large element' scalar/vector to 'small element' vector.
4545 if ((SrcBits % TyBits) != 0)
4546 break;
4547
4548 // Only proceed if the destination type is a fixed-size vector
4549 if (isa<FixedVectorType>(Ty)) {
4550 // Fast case - sign splat can be simply split across the small elements.
4551 // This works for both vector and scalar sources
4552 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4553 if (Tmp == SrcBits)
4554 return TyBits;
4555 }
4556 break;
4557 }
4558 case Instruction::SExt:
4559 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4560 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4561 Tmp;
4562
4563 case Instruction::SDiv: {
4564 const APInt *Denominator;
4565 // sdiv X, C -> adds log(C) sign bits.
4566 if (match(U->getOperand(1), m_APInt(Denominator))) {
4567
4568 // Ignore non-positive denominator.
4569 if (!Denominator->isStrictlyPositive())
4570 break;
4571
4572 // Calculate the incoming numerator bits.
4573 unsigned NumBits =
4574 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4575
4576 // Add floor(log(C)) bits to the numerator bits.
4577 return std::min(TyBits, NumBits + Denominator->logBase2());
4578 }
4579 break;
4580 }
4581
4582 case Instruction::SRem: {
4583 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4584
4585 const APInt *Denominator;
4586 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4587 // positive constant. This let us put a lower bound on the number of sign
4588 // bits.
4589 if (match(U->getOperand(1), m_APInt(Denominator))) {
4590
4591 // Ignore non-positive denominator.
4592 if (Denominator->isStrictlyPositive()) {
4593 // Calculate the leading sign bit constraints by examining the
4594 // denominator. Given that the denominator is positive, there are two
4595 // cases:
4596 //
4597 // 1. The numerator is positive. The result range is [0,C) and
4598 // [0,C) u< (1 << ceilLogBase2(C)).
4599 //
4600 // 2. The numerator is negative. Then the result range is (-C,0] and
4601 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4602 //
4603 // Thus a lower bound on the number of sign bits is `TyBits -
4604 // ceilLogBase2(C)`.
4605
4606 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4607 Tmp = std::max(Tmp, ResBits);
4608 }
4609 }
4610 return Tmp;
4611 }
4612
4613 case Instruction::AShr: {
4614 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4615 // ashr X, C -> adds C sign bits. Vectors too.
4616 const APInt *ShAmt;
4617 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4618 if (ShAmt->uge(TyBits))
4619 break; // Bad shift.
4620 unsigned ShAmtLimited = ShAmt->getZExtValue();
4621 Tmp += ShAmtLimited;
4622 if (Tmp > TyBits) Tmp = TyBits;
4623 }
4624 return Tmp;
4625 }
4626 case Instruction::Shl: {
4627 const APInt *ShAmt;
4628 Value *X = nullptr;
4629 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4630 // shl destroys sign bits.
4631 if (ShAmt->uge(TyBits))
4632 break; // Bad shift.
4633 // We can look through a zext (more or less treating it as a sext) if
4634 // all extended bits are shifted out.
4635 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4636 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4637 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4638 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4639 } else
4640 Tmp =
4641 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4642 if (ShAmt->uge(Tmp))
4643 break; // Shifted all sign bits out.
4644 Tmp2 = ShAmt->getZExtValue();
4645 return Tmp - Tmp2;
4646 }
4647 break;
4648 }
4649 case Instruction::And:
4650 case Instruction::Or:
4651 case Instruction::Xor: // NOT is handled here.
4652 // Logical binary ops preserve the number of sign bits at the worst.
4653 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4654 if (Tmp != 1) {
4655 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4656 FirstAnswer = std::min(Tmp, Tmp2);
4657 // We computed what we know about the sign bits as our first
4658 // answer. Now proceed to the generic code that uses
4659 // computeKnownBits, and pick whichever answer is better.
4660 }
4661 break;
4662
4663 case Instruction::Select: {
4664 // If we have a clamp pattern, we know that the number of sign bits will
4665 // be the minimum of the clamp min/max range.
4666 const Value *X;
4667 const APInt *CLow, *CHigh;
4668 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4669 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4670
4671 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4672 if (Tmp == 1)
4673 break;
4674 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4675 return std::min(Tmp, Tmp2);
4676 }
4677
4678 case Instruction::Add:
4679 // Add can have at most one carry bit. Thus we know that the output
4680 // is, at worst, one more bit than the inputs.
4681 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4682 if (Tmp == 1) break;
4683
4684 // Special case decrementing a value (ADD X, -1):
4685 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4686 if (CRHS->isAllOnesValue()) {
4687 KnownBits Known(TyBits);
4688 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4689
4690 // If the input is known to be 0 or 1, the output is 0/-1, which is
4691 // all sign bits set.
4692 if ((Known.Zero | 1).isAllOnes())
4693 return TyBits;
4694
4695 // If we are subtracting one from a positive number, there is no carry
4696 // out of the result.
4697 if (Known.isNonNegative())
4698 return Tmp;
4699 }
4700
4701 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4702 if (Tmp2 == 1)
4703 break;
4704 return std::min(Tmp, Tmp2) - 1;
4705
4706 case Instruction::Sub:
4707 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4708 if (Tmp2 == 1)
4709 break;
4710
4711 // Handle NEG.
4712 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4713 if (CLHS->isNullValue()) {
4714 KnownBits Known(TyBits);
4715 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4716 // If the input is known to be 0 or 1, the output is 0/-1, which is
4717 // all sign bits set.
4718 if ((Known.Zero | 1).isAllOnes())
4719 return TyBits;
4720
4721 // If the input is known to be positive (the sign bit is known clear),
4722 // the output of the NEG has the same number of sign bits as the
4723 // input.
4724 if (Known.isNonNegative())
4725 return Tmp2;
4726
4727 // Otherwise, we treat this like a SUB.
4728 }
4729
4730 // Sub can have at most one carry bit. Thus we know that the output
4731 // is, at worst, one more bit than the inputs.
4732 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4733 if (Tmp == 1)
4734 break;
4735 return std::min(Tmp, Tmp2) - 1;
4736
4737 case Instruction::Mul: {
4738 // The output of the Mul can be at most twice the valid bits in the
4739 // inputs.
4740 unsigned SignBitsOp0 =
4741 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4742 if (SignBitsOp0 == 1)
4743 break;
4744 unsigned SignBitsOp1 =
4745 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4746 if (SignBitsOp1 == 1)
4747 break;
4748 unsigned OutValidBits =
4749 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4750 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4751 }
4752
4753 case Instruction::PHI: {
4754 const PHINode *PN = cast<PHINode>(U);
4755 unsigned NumIncomingValues = PN->getNumIncomingValues();
4756 // Don't analyze large in-degree PHIs.
4757 if (NumIncomingValues > 4) break;
4758 // Unreachable blocks may have zero-operand PHI nodes.
4759 if (NumIncomingValues == 0) break;
4760
4761 // Take the minimum of all incoming values. This can't infinitely loop
4762 // because of our depth threshold.
4764 Tmp = TyBits;
4765 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4766 if (Tmp == 1) return Tmp;
4767 RecQ.CtxI = PN->getIncomingBlock(i)->getTerminator();
4768 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4769 DemandedElts, RecQ, Depth + 1));
4770 }
4771 return Tmp;
4772 }
4773
4774 case Instruction::Trunc: {
4775 // If the input contained enough sign bits that some remain after the
4776 // truncation, then we can make use of that. Otherwise we don't know
4777 // anything.
4778 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4779 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4780 if (Tmp > (OperandTyBits - TyBits))
4781 return Tmp - (OperandTyBits - TyBits);
4782
4783 return 1;
4784 }
4785
4786 case Instruction::ExtractElement:
4787 // Look through extract element. At the moment we keep this simple and
4788 // skip tracking the specific element. But at least we might find
4789 // information valid for all elements of the vector (for example if vector
4790 // is sign extended, shifted, etc).
4791 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4792
4793 case Instruction::ShuffleVector: {
4794 // Collect the minimum number of sign bits that are shared by every vector
4795 // element referenced by the shuffle.
4796 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4797 if (!Shuf) {
4798 // FIXME: Add support for shufflevector constant expressions.
4799 return 1;
4800 }
4801 APInt DemandedLHS, DemandedRHS;
4802 // For undef elements, we don't know anything about the common state of
4803 // the shuffle result.
4804 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4805 return 1;
4806 Tmp = std::numeric_limits<unsigned>::max();
4807 if (!!DemandedLHS) {
4808 const Value *LHS = Shuf->getOperand(0);
4809 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4810 }
4811 // If we don't know anything, early out and try computeKnownBits
4812 // fall-back.
4813 if (Tmp == 1)
4814 break;
4815 if (!!DemandedRHS) {
4816 const Value *RHS = Shuf->getOperand(1);
4817 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4818 Tmp = std::min(Tmp, Tmp2);
4819 }
4820 // If we don't know anything, early out and try computeKnownBits
4821 // fall-back.
4822 if (Tmp == 1)
4823 break;
4824 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4825 return Tmp;
4826 }
4827 case Instruction::Call: {
4828 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4829 switch (II->getIntrinsicID()) {
4830 default:
4831 break;
4832 case Intrinsic::abs:
4833 Tmp =
4834 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4835 if (Tmp == 1)
4836 break;
4837
4838 // Absolute value reduces number of sign bits by at most 1.
4839 return Tmp - 1;
4840 case Intrinsic::smin:
4841 case Intrinsic::smax: {
4842 const APInt *CLow, *CHigh;
4843 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4844 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4845 }
4846 }
4847 }
4848 }
4849 }
4850 }
4851
4852 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4853 // use this information.
4854
4855 // If we can examine all elements of a vector constant successfully, we're
4856 // done (we can't do any better than that). If not, keep trying.
4857 if (unsigned VecSignBits =
4858 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4859 return VecSignBits;
4860
4861 KnownBits Known(TyBits);
4862 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4863
4864 // If we know that the sign bit is either zero or one, determine the number of
4865 // identical bits in the top of the input value.
4866 return std::max(FirstAnswer, Known.countMinSignBits());
4867}
4868
4870 const TargetLibraryInfo *TLI) {
4871 const Function *F = CB.getCalledFunction();
4872 if (!F)
4874
4875 if (F->isIntrinsic())
4876 return F->getIntrinsicID();
4877
4878 // We are going to infer semantics of a library function based on mapping it
4879 // to an LLVM intrinsic. Check that the library function is available from
4880 // this callbase and in this environment.
4881 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4883
4884 LibFunc Func = TLI->getLibFunc(CB);
4885 if (Func == NotLibFunc)
4887
4888 switch (Func) {
4889 default:
4890 break;
4891 case LibFunc_sin:
4892 case LibFunc_sinf:
4893 case LibFunc_sinl:
4894 return Intrinsic::sin;
4895 case LibFunc_cos:
4896 case LibFunc_cosf:
4897 case LibFunc_cosl:
4898 return Intrinsic::cos;
4899 case LibFunc_tan:
4900 case LibFunc_tanf:
4901 case LibFunc_tanl:
4902 return Intrinsic::tan;
4903 case LibFunc_asin:
4904 case LibFunc_asinf:
4905 case LibFunc_asinl:
4906 return Intrinsic::asin;
4907 case LibFunc_acos:
4908 case LibFunc_acosf:
4909 case LibFunc_acosl:
4910 return Intrinsic::acos;
4911 case LibFunc_atan:
4912 case LibFunc_atanf:
4913 case LibFunc_atanl:
4914 return Intrinsic::atan;
4915 case LibFunc_atan2:
4916 case LibFunc_atan2f:
4917 case LibFunc_atan2l:
4918 return Intrinsic::atan2;
4919 case LibFunc_sinh:
4920 case LibFunc_sinhf:
4921 case LibFunc_sinhl:
4922 return Intrinsic::sinh;
4923 case LibFunc_cosh:
4924 case LibFunc_coshf:
4925 case LibFunc_coshl:
4926 return Intrinsic::cosh;
4927 case LibFunc_tanh:
4928 case LibFunc_tanhf:
4929 case LibFunc_tanhl:
4930 return Intrinsic::tanh;
4931 case LibFunc_exp:
4932 case LibFunc_expf:
4933 case LibFunc_expl:
4934 return Intrinsic::exp;
4935 case LibFunc_exp2:
4936 case LibFunc_exp2f:
4937 case LibFunc_exp2l:
4938 return Intrinsic::exp2;
4939 case LibFunc_exp10:
4940 case LibFunc_exp10f:
4941 case LibFunc_exp10l:
4942 return Intrinsic::exp10;
4943 case LibFunc_log:
4944 case LibFunc_logf:
4945 case LibFunc_logl:
4946 return Intrinsic::log;
4947 case LibFunc_log10:
4948 case LibFunc_log10f:
4949 case LibFunc_log10l:
4950 return Intrinsic::log10;
4951 case LibFunc_log2:
4952 case LibFunc_log2f:
4953 case LibFunc_log2l:
4954 return Intrinsic::log2;
4955 case LibFunc_fabs:
4956 case LibFunc_fabsf:
4957 case LibFunc_fabsl:
4958 return Intrinsic::fabs;
4959 case LibFunc_fmin:
4960 case LibFunc_fminf:
4961 case LibFunc_fminl:
4962 return Intrinsic::minnum;
4963 case LibFunc_fmax:
4964 case LibFunc_fmaxf:
4965 case LibFunc_fmaxl:
4966 return Intrinsic::maxnum;
4967 case LibFunc_copysign:
4968 case LibFunc_copysignf:
4969 case LibFunc_copysignl:
4970 return Intrinsic::copysign;
4971 case LibFunc_floor:
4972 case LibFunc_floorf:
4973 case LibFunc_floorl:
4974 return Intrinsic::floor;
4975 case LibFunc_ceil:
4976 case LibFunc_ceilf:
4977 case LibFunc_ceill:
4978 return Intrinsic::ceil;
4979 case LibFunc_trunc:
4980 case LibFunc_truncf:
4981 case LibFunc_truncl:
4982 return Intrinsic::trunc;
4983 case LibFunc_rint:
4984 case LibFunc_rintf:
4985 case LibFunc_rintl:
4986 return Intrinsic::rint;
4987 case LibFunc_nearbyint:
4988 case LibFunc_nearbyintf:
4989 case LibFunc_nearbyintl:
4990 return Intrinsic::nearbyint;
4991 case LibFunc_round:
4992 case LibFunc_roundf:
4993 case LibFunc_roundl:
4994 return Intrinsic::round;
4995 case LibFunc_roundeven:
4996 case LibFunc_roundevenf:
4997 case LibFunc_roundevenl:
4998 return Intrinsic::roundeven;
4999 case LibFunc_pow:
5000 case LibFunc_powf:
5001 case LibFunc_powl:
5002 return Intrinsic::pow;
5003 case LibFunc_sqrt:
5004 case LibFunc_sqrtf:
5005 case LibFunc_sqrtl:
5006 return Intrinsic::sqrt;
5007 }
5008
5010}
5011
5012/// Given an exploded icmp instruction, return true if the comparison only
5013/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
5014/// the result of the comparison is true when the input value is signed.
5016 bool &TrueIfSigned) {
5017 switch (Pred) {
5018 case ICmpInst::ICMP_SLT: // True if LHS s< 0
5019 TrueIfSigned = true;
5020 return RHS.isZero();
5021 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
5022 TrueIfSigned = true;
5023 return RHS.isAllOnes();
5024 case ICmpInst::ICMP_SGT: // True if LHS s> -1
5025 TrueIfSigned = false;
5026 return RHS.isAllOnes();
5027 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
5028 TrueIfSigned = false;
5029 return RHS.isZero();
5030 case ICmpInst::ICMP_UGT:
5031 // True if LHS u> RHS and RHS == sign-bit-mask - 1
5032 TrueIfSigned = true;
5033 return RHS.isMaxSignedValue();
5034 case ICmpInst::ICMP_UGE:
5035 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5036 TrueIfSigned = true;
5037 return RHS.isMinSignedValue();
5038 case ICmpInst::ICMP_ULT:
5039 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
5040 TrueIfSigned = false;
5041 return RHS.isMinSignedValue();
5042 case ICmpInst::ICMP_ULE:
5043 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
5044 TrueIfSigned = false;
5045 return RHS.isMaxSignedValue();
5046 default:
5047 return false;
5048 }
5049}
5050
5052 bool CondIsTrue,
5053 const Instruction *CtxI,
5054 KnownFPClass &KnownFromContext,
5055 unsigned Depth = 0) {
5056 Value *A, *B;
5058 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
5059 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
5060 computeKnownFPClassFromCond(V, A, CondIsTrue, CtxI, KnownFromContext,
5061 Depth + 1);
5062 computeKnownFPClassFromCond(V, B, CondIsTrue, CtxI, KnownFromContext,
5063 Depth + 1);
5064 return;
5065 }
5067 computeKnownFPClassFromCond(V, A, !CondIsTrue, CtxI, KnownFromContext,
5068 Depth + 1);
5069 return;
5070 }
5071 CmpPredicate Pred;
5072 Value *LHS;
5073 uint64_t ClassVal = 0;
5074 const APFloat *CRHS;
5075 const APInt *RHS;
5076 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
5077 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
5078 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
5079 LHS != V);
5080 if (CmpVal == V)
5081 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
5083 m_Specific(V), m_ConstantInt(ClassVal)))) {
5084 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
5085 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
5086 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
5087 m_APInt(RHS)))) {
5088 bool TrueIfSigned;
5089 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
5090 return;
5091 if (TrueIfSigned == CondIsTrue)
5092 KnownFromContext.signBitMustBeOne();
5093 else
5094 KnownFromContext.signBitMustBeZero();
5095 }
5096}
5097
5098/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
5099/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
5100/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
5101/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
5102/// exponent range is [-149, -2], but the 0 edge case is above this range).
5103static std::tuple<int, int, int>
5105 if (!Q.CtxI || !Q.DC || !Q.DT)
5107
5108 // Intersect the bounds implied by every dominating condition, keeping the
5109 // tightest maximum. A value may participate in multiple compares
5110 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
5111 int MaxExp = APFloat::IEK_Inf;
5112 int MaxExpNonZero = APFloat::IEK_Inf;
5113
5114 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5115 CmpPredicate Pred;
5116 const APFloat *LimitC;
5117 if (!match(BI->getCondition(),
5118 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
5119 continue;
5120
5121 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
5122 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
5123 continue;
5124
5125 // If fabs(x) <= K, implies the exponent min exp range.
5126 // if fabs(x) >= K, swap the successor
5127 bool IsLessEqual =
5128 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
5129 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
5130 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
5131
5132 bool KnownStrictlyLess =
5133 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
5134 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
5135
5136 BasicBlockEdge Edge1(BI->getParent(),
5137 BI->getSuccessor(IsLessEqual ? 0 : 1));
5138 if (Q.DT->dominates(Edge1, Q.CtxI->getParent())) {
5139 // frexp returns an exponent one greater than ilogb.
5140 int Exp = ilogb(*LimitC) + 1;
5141
5142 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
5143 // exponent drops by one when K is exact power of two.
5144 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
5145 --Exp;
5146
5147 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
5148 // may exclude.
5149
5150 // TODO: Figure out lower bound to detect no-underflow.
5151 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
5152 MaxExp = std::min(MaxExp, std::max(Exp, 0));
5153 }
5154 }
5155
5156 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
5157}
5158
5160 const SimplifyQuery &Q) {
5161 KnownFPClass KnownFromContext;
5162
5163 if (Q.CC && Q.CC->AffectedValues.contains(V))
5165 KnownFromContext);
5166
5167 if (!Q.CtxI)
5168 return KnownFromContext;
5169
5170 if (Q.DC && Q.DT) {
5171 // Handle dominating conditions.
5172 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
5173 Value *Cond = BI->getCondition();
5174
5175 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
5176 if (Q.DT->dominates(Edge0, Q.CtxI->getParent()))
5177 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CtxI,
5178 KnownFromContext);
5179
5180 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
5181 if (Q.DT->dominates(Edge1, Q.CtxI->getParent()))
5182 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CtxI,
5183 KnownFromContext);
5184 }
5185 }
5186
5187 if (!Q.AC)
5188 return KnownFromContext;
5189
5190 // Try to restrict the floating-point classes based on information from
5191 // assumptions.
5192 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
5193 if (!AssumeVH)
5194 continue;
5195 CallInst *I = cast<CallInst>(AssumeVH);
5196
5197 assert(I->getFunction() == Q.CtxI->getParent()->getParent() &&
5198 "Got assumption for the wrong function!");
5199 assert(I->getIntrinsicID() == Intrinsic::assume &&
5200 "must be an assume intrinsic");
5201
5202 if (!isValidAssumeForContext(I, Q))
5203 continue;
5204
5205 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5206 /*CondIsTrue=*/true, Q.CtxI, KnownFromContext);
5207 }
5208
5209 return KnownFromContext;
5210}
5211
5213 Value *Arm, bool Invert,
5214 const SimplifyQuery &SQ,
5215 unsigned Depth) {
5216
5217 KnownFPClass KnownSrc;
5219 /*CondIsTrue=*/!Invert, SQ.CtxI, KnownSrc,
5220 Depth + 1);
5221 KnownSrc = KnownSrc.unionWith(Known);
5222 if (KnownSrc.isUnknown())
5223 return;
5224
5225 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CtxI, SQ.DT, Depth + 1))
5226 Known = KnownSrc;
5227}
5228
5229void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5230 FPClassTest InterestedClasses, KnownFPClass &Known,
5231 const SimplifyQuery &Q, unsigned Depth);
5232
5234 FPClassTest InterestedClasses,
5235 const SimplifyQuery &Q, unsigned Depth) {
5236 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5237 APInt DemandedElts =
5238 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5239 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5240}
5241
5243 const APInt &DemandedElts,
5244 FPClassTest InterestedClasses,
5246 const SimplifyQuery &Q,
5247 unsigned Depth) {
5248 if ((InterestedClasses &
5250 return;
5251
5252 KnownFPClass KnownSrc;
5253 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5254 KnownSrc, Q, Depth + 1);
5255
5256 const fltSemantics &DstTy = Op->getType()->getScalarType()->getFltSemantics();
5257 const fltSemantics &SrcTy =
5258 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
5259
5260 const auto *I = dyn_cast<Instruction>(Op);
5261 const Function *F = I ? I->getFunction() : nullptr;
5262 DenormalMode DstMode =
5263 F ? F->getDenormalMode(DstTy) : DenormalMode::getDynamic();
5264 DenormalMode SrcMode =
5265 F ? F->getDenormalMode(SrcTy) : DenormalMode::getDynamic();
5266
5267 Known = KnownFPClass::fptrunc(KnownSrc, DstTy, SrcTy, DstMode, SrcMode);
5268}
5269
5271 switch (IID) {
5272 case Intrinsic::minimum:
5274 case Intrinsic::maximum:
5276 case Intrinsic::minimumnum:
5278 case Intrinsic::maximumnum:
5280 case Intrinsic::minnum:
5282 case Intrinsic::maxnum:
5284 default:
5285 llvm_unreachable("not a floating-point min-max intrinsic");
5286 }
5287}
5288
5289/// \return true if this is a floating point value that is known to have a
5290/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5291static bool isAbsoluteValueULEOne(const Value *V) {
5292 // TODO: Handle frexp
5293 // TODO: Other rounding intrinsics?
5294 // TODO: Try computeKnownExponentRangeFromContext
5295
5296 // fabs(x - floor(x)) <= 1
5297 const Value *SubFloorX;
5298 if (match(V, m_FSub(m_Value(SubFloorX),
5300 return true;
5301
5304}
5305
5306void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5307 FPClassTest InterestedClasses, KnownFPClass &Known,
5308 const SimplifyQuery &Q, unsigned Depth) {
5309 assert(Known.isUnknown() && "should not be called with known information");
5310
5311 if (!DemandedElts) {
5312 // No demanded elts, better to assume we don't know anything.
5313 Known.resetAll();
5314 return;
5315 }
5316
5317 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5318
5319 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5320 Known = KnownFPClass(CFP->getValueAPF());
5321 return;
5322 }
5323
5325 Known.setKnownFPClasses(fcPosZero);
5326 return;
5327 }
5328
5329 if (isa<PoisonValue>(V)) {
5331 return;
5332 }
5333
5334 // Try to handle fixed width vector constants
5335 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5336 const Constant *CV = dyn_cast<Constant>(V);
5337 if (VFVTy && CV) {
5339
5340 // For vectors, verify that each element is not NaN.
5341 unsigned NumElts = VFVTy->getNumElements();
5342 for (unsigned i = 0; i != NumElts; ++i) {
5343 if (!DemandedElts[i])
5344 continue;
5345
5346 Constant *Elt = CV->getAggregateElement(i);
5347 if (!Elt) {
5348 Known = KnownFPClass();
5349 return;
5350 }
5351 if (isa<PoisonValue>(Elt))
5352 continue;
5353 auto *CElt = dyn_cast<ConstantFP>(Elt);
5354 if (!CElt) {
5355 Known = KnownFPClass();
5356 return;
5357 }
5358
5359 Known |= KnownFPClass(CElt->getValueAPF());
5360 }
5361 return;
5362 }
5363
5364 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5366 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5367 Known |= KnownFPClass(CDS->getElementAsAPFloat(I));
5368 return;
5369 }
5370
5371 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5372 // TODO: Handle complex aggregates
5374 for (const Use &Op : CA->operands()) {
5375 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5376 if (!CFP) {
5377 Known = KnownFPClass();
5378 return;
5379 }
5380
5381 Known |= KnownFPClass(CFP->getValueAPF());
5382 }
5383
5384 return;
5385 }
5386
5387 FPClassTest KnownNotFromFlags = fcNone;
5388 if (const auto *CB = dyn_cast<CallBase>(V))
5389 KnownNotFromFlags |= CB->getRetNoFPClass();
5390 else if (const auto *Arg = dyn_cast<Argument>(V))
5391 KnownNotFromFlags |= Arg->getNoFPClass();
5392
5393 const Operator *Op = dyn_cast<Operator>(V);
5395 if (FPOp->hasNoNaNs())
5396 KnownNotFromFlags |= fcNan;
5397 if (FPOp->hasNoInfs())
5398 KnownNotFromFlags |= fcInf;
5399 }
5400
5401 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5402 KnownNotFromFlags |= ~AssumedClasses.getKnownFPClasses();
5403
5404 // We no longer need to find out about these bits from inputs if we can
5405 // assume this from flags/attributes.
5406 InterestedClasses &= ~KnownNotFromFlags;
5407
5408 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5409 Known.knownNot(KnownNotFromFlags);
5410 if (!Known.getSignBit() && AssumedClasses.getSignBit()) {
5411 if (*AssumedClasses.getSignBit())
5412 Known.signBitMustBeOne();
5413 else
5414 Known.signBitMustBeZero();
5415 }
5416 });
5417
5418 if (!Op)
5419 return;
5420
5421 // All recursive calls that increase depth must come after this.
5423 return;
5424
5425 const unsigned Opc = Op->getOpcode();
5426 switch (Opc) {
5427 case Instruction::FNeg: {
5428 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5429 Known, Q, Depth + 1);
5430 Known.fneg();
5431 break;
5432 }
5433 case Instruction::Select: {
5434 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5435 KnownFPClass Res;
5436 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5437 Depth + 1);
5438 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5439 Depth);
5440 return Res;
5441 };
5442 // Only known if known in both the LHS and RHS.
5443 Known =
5444 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5445 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5446 break;
5447 }
5448 case Instruction::Load: {
5449 const MDNode *NoFPClass =
5450 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5451 if (!NoFPClass)
5452 break;
5453
5454 ConstantInt *MaskVal =
5456 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5457 break;
5458 }
5459 case Instruction::Call: {
5460 const CallInst *II = cast<CallInst>(Op);
5461 const Intrinsic::ID IID = II->getIntrinsicID();
5462 switch (IID) {
5463 case Intrinsic::fabs: {
5464 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5465 // If we only care about the sign bit we don't need to inspect the
5466 // operand.
5467 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5468 InterestedClasses, Known, Q, Depth + 1);
5469 }
5470
5471 Known.fabs();
5472 break;
5473 }
5474 case Intrinsic::copysign: {
5475 KnownFPClass KnownSign;
5476
5477 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5478 Known, Q, Depth + 1);
5479 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5480 KnownSign, Q, Depth + 1);
5481 Known.copysign(KnownSign);
5482 break;
5483 }
5484 case Intrinsic::fma:
5485 case Intrinsic::fmuladd: {
5486 if ((InterestedClasses & (fcNegative | fcNan)) == fcNone)
5487 break;
5488
5489 const bool IsFMA = IID == Intrinsic::fma;
5490
5491 // FIXME: This should check isGuaranteedNotToBeUndef
5492 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5493 KnownFPClass KnownSrc, KnownAddend;
5494 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5495 InterestedClasses, KnownAddend, Q, Depth + 1);
5496 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5497 InterestedClasses, KnownSrc, Q, Depth + 1);
5498
5499 const Function *F = II->getFunction();
5500 const fltSemantics &FltSem =
5501 II->getType()->getScalarType()->getFltSemantics();
5503 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5504
5505 if ((KnownNotFromFlags & fcNan) == fcNan) {
5506 KnownSrc.knownNot(fcNan);
5507 KnownAddend.knownNot(fcNan);
5508 }
5509
5510 if ((KnownNotFromFlags & fcInf) == fcInf) {
5511 KnownSrc.knownNot(fcInf);
5512 KnownAddend.knownNot(fcInf);
5513 }
5514
5515 Known = IsFMA
5516 ? KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode)
5517 : KnownFPClass::fmuladd_square(KnownSrc, KnownAddend, Mode);
5518 break;
5519 }
5520
5521 KnownFPClass KnownSrc[3];
5522 for (int I = 0; I != 3; ++I) {
5523 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5524 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5525 if (KnownSrc[I].isUnknown())
5526 return;
5527
5528 if ((KnownNotFromFlags & fcNan) == fcNan)
5529 KnownSrc[I].knownNot(fcNan);
5530 if ((KnownNotFromFlags & fcInf) == fcInf)
5531 KnownSrc[I].knownNot(fcInf);
5532 }
5533
5534 const Function *F = II->getFunction();
5535 const fltSemantics &FltSem =
5536 II->getType()->getScalarType()->getFltSemantics();
5538 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5539 Known =
5540 IsFMA ? KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode)
5541 : KnownFPClass::fmuladd(KnownSrc[0], KnownSrc[1], KnownSrc[2],
5542 Mode);
5543 break;
5544 }
5545 case Intrinsic::sqrt:
5546 case Intrinsic::experimental_constrained_sqrt: {
5547 KnownFPClass KnownSrc;
5548 FPClassTest InterestedSrcs = InterestedClasses;
5549 if (InterestedClasses & fcQNan)
5551 // Subnormals may flush to zero.
5552 if (InterestedClasses & fcZero)
5553 InterestedSrcs |= fcSubnormal;
5554
5555 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5556 KnownSrc, Q, Depth + 1);
5557
5559
5560 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5561 if (!HasNSZ) {
5562 const Function *F = II->getFunction();
5563 const fltSemantics &FltSem =
5564 II->getType()->getScalarType()->getFltSemantics();
5565 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5566 }
5567
5568 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5569 if (HasNSZ)
5570 Known.knownNot(fcNegZero);
5571
5572 break;
5573 }
5574 case Intrinsic::sin: {
5575 KnownFPClass KnownSrc;
5576 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5577 KnownSrc, Q, Depth + 1);
5578 Known = KnownFPClass::sin(KnownSrc);
5579 break;
5580 }
5581 case Intrinsic::cos: {
5582 KnownFPClass KnownSrc;
5583 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5584 KnownSrc, Q, Depth + 1);
5585 Known = KnownFPClass::cos(KnownSrc);
5586 break;
5587 }
5588 case Intrinsic::tan: {
5589 KnownFPClass KnownSrc;
5590 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5591 KnownSrc, Q, Depth + 1);
5592 Known = KnownFPClass::tan(KnownSrc);
5593 break;
5594 }
5595 case Intrinsic::sinh: {
5596 KnownFPClass KnownSrc;
5597 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5598 KnownSrc, Q, Depth + 1);
5599 Known = KnownFPClass::sinh(KnownSrc);
5600 break;
5601 }
5602 case Intrinsic::cosh: {
5603 KnownFPClass KnownSrc;
5604 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5605 KnownSrc, Q, Depth + 1);
5606 Known = KnownFPClass::cosh(KnownSrc);
5607 break;
5608 }
5609 case Intrinsic::tanh: {
5610 KnownFPClass KnownSrc;
5611 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5612 KnownSrc, Q, Depth + 1);
5613 Known = KnownFPClass::tanh(KnownSrc);
5614 break;
5615 }
5616 case Intrinsic::asin: {
5617 KnownFPClass KnownSrc;
5618 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5619 KnownSrc, Q, Depth + 1);
5620 Known = KnownFPClass::asin(KnownSrc);
5621 break;
5622 }
5623 case Intrinsic::acos: {
5624 KnownFPClass KnownSrc;
5625 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5626 KnownSrc, Q, Depth + 1);
5627 Known = KnownFPClass::acos(KnownSrc);
5628 break;
5629 }
5630 case Intrinsic::atan: {
5631 KnownFPClass KnownSrc;
5632 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5633 KnownSrc, Q, Depth + 1);
5634 Known = KnownFPClass::atan(KnownSrc);
5635 break;
5636 }
5637 case Intrinsic::atan2: {
5638 FPClassTest InterestedY = InterestedClasses;
5639 FPClassTest InterestedX = InterestedClasses;
5640
5641 // We can rule out negative values if y cannot have a negative value.
5642 if ((InterestedClasses & fcNegFinite) != fcNone)
5643 InterestedY |= fcNegative;
5644
5645 // We can rule out positive values if y cannot have a positive value.
5646 if ((InterestedClasses & fcPosFinite) != fcNone)
5647 InterestedY |= fcPositive | fcNegSubnormal;
5648
5649 // We can rule out zero and subnormal if x cannot have a positive value.
5650 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5651 InterestedX |= fcPositive | fcNegSubnormal;
5652
5653 KnownFPClass KnownY, KnownX;
5654 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5655 KnownY, Q, Depth + 1);
5656 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5657 KnownX, Q, Depth + 1);
5658
5659 const Function *F = II->getFunction();
5661 F ? F->getDenormalMode(
5662 II->getType()->getScalarType()->getFltSemantics())
5664 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5665 break;
5666 }
5667 case Intrinsic::maxnum:
5668 case Intrinsic::minnum:
5669 case Intrinsic::minimum:
5670 case Intrinsic::maximum:
5671 case Intrinsic::minimumnum:
5672 case Intrinsic::maximumnum: {
5673 KnownFPClass KnownLHS, KnownRHS;
5674 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5675 KnownLHS, Q, Depth + 1);
5676 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5677 KnownRHS, Q, Depth + 1);
5678
5679 const Function *F = II->getFunction();
5680
5682 F ? F->getDenormalMode(
5683 II->getType()->getScalarType()->getFltSemantics())
5685
5686 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5687 Mode);
5688 break;
5689 }
5690 case Intrinsic::canonicalize: {
5691 KnownFPClass KnownSrc;
5692 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5693 KnownSrc, Q, Depth + 1);
5694
5695 const Function *F = II->getFunction();
5696 DenormalMode DenormMode =
5697 F ? F->getDenormalMode(
5698 II->getType()->getScalarType()->getFltSemantics())
5700 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5701 break;
5702 }
5703 case Intrinsic::vector_reduce_fmax:
5704 case Intrinsic::vector_reduce_fmin:
5705 case Intrinsic::vector_reduce_fmaximum:
5706 case Intrinsic::vector_reduce_fminimum:
5707 case Intrinsic::vector_reduce_fmaximumnum:
5708 case Intrinsic::vector_reduce_fminimumnum: {
5709 // reduce min/max will choose an element from one of the vector elements,
5710 // so we can infer and class information that is common to all elements.
5711 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5712 InterestedClasses, Q, Depth + 1);
5713 // Can only propagate sign if output is never NaN.
5714 if (!Known.isKnownNeverNaN())
5715 Known.setSignBit(std::nullopt);
5716 break;
5717 }
5718 // reverse preserves all characteristics of the input vec's element.
5719 case Intrinsic::vector_reverse:
5721 II->getArgOperand(0), DemandedElts.reverseBits(),
5722 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5723 break;
5724 case Intrinsic::trunc:
5725 case Intrinsic::floor:
5726 case Intrinsic::ceil:
5727 case Intrinsic::rint:
5728 case Intrinsic::nearbyint:
5729 case Intrinsic::round:
5730 case Intrinsic::roundeven: {
5731 KnownFPClass KnownSrc;
5732 FPClassTest InterestedSrcs = InterestedClasses;
5733
5734 // Negative round ups towards zero produce negative zero.
5735 if (InterestedSrcs & fcNegFinite)
5736 InterestedSrcs |= fcNegFinite;
5737
5738 // Negative subnormals may flush to positive zero.
5739 if (InterestedSrcs & fcPosFinite)
5740 InterestedSrcs |= fcPosFinite | fcNegSubnormal;
5741
5742 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5743 KnownSrc, Q, Depth + 1);
5744
5745 const Function *F = II->getFunction();
5747 F ? F->getDenormalMode(
5748 II->getType()->getScalarType()->getFltSemantics())
5750 const bool IsMultiUnitFPType =
5751 V->getType()->getScalarType()->isMultiUnitFPType();
5752
5753 switch (IID) {
5754 case Intrinsic::trunc:
5755 Known = KnownFPClass::trunc(KnownSrc, Mode);
5756 break;
5757 case Intrinsic::floor:
5758 Known = KnownFPClass::floor(KnownSrc, IsMultiUnitFPType, Mode);
5759 break;
5760 case Intrinsic::ceil:
5761 Known = KnownFPClass::ceil(KnownSrc, IsMultiUnitFPType, Mode);
5762 break;
5763 default:
5764 Known =
5765 KnownFPClass::roundToIntegral(KnownSrc, IsMultiUnitFPType, Mode);
5766 break;
5767 }
5768 break;
5769 }
5770 case Intrinsic::exp:
5771 case Intrinsic::exp2:
5772 case Intrinsic::exp10:
5773 case Intrinsic::amdgcn_exp2: {
5774 KnownFPClass KnownSrc;
5775 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5776 KnownSrc, Q, Depth + 1);
5777
5778 Known = KnownFPClass::exp(KnownSrc);
5779
5780 Type *EltTy = II->getType()->getScalarType();
5781 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5782 Known.knownNot(fcSubnormal);
5783
5784 break;
5785 }
5786 case Intrinsic::fptrunc_round: {
5787 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5788 Q, Depth);
5789 break;
5790 }
5791 case Intrinsic::log:
5792 case Intrinsic::log10:
5793 case Intrinsic::log2:
5794 case Intrinsic::experimental_constrained_log:
5795 case Intrinsic::experimental_constrained_log10:
5796 case Intrinsic::experimental_constrained_log2:
5797 case Intrinsic::amdgcn_log: {
5798 FPClassTest InterestedSrcs = fcNone;
5799
5800 // log(negative) produces NaN.
5801 if ((InterestedClasses & fcNan) != fcNone)
5802 InterestedSrcs |= fcNan | fcNegative;
5803
5804 // log(logical-zero) produces negative infinity.
5805 if ((InterestedClasses & fcNegInf) != fcNone)
5806 InterestedSrcs |= fcZero | fcSubnormal;
5807
5808 // log(x) < -0.0 if x < +1.0
5809 if ((InterestedClasses & fcNegNormal) != fcNone)
5810 InterestedSrcs |= fcPosSubnormal | fcPosNormal;
5811
5812 // log(x) >= +0.0 if x >= +1.0
5813 if ((InterestedClasses & (fcPosZero | fcPosNormal)) != fcNone)
5814 InterestedSrcs |= fcPosNormal;
5815
5816 // log(x) is positive infinity iff x is positive infinity.
5817 if ((InterestedClasses & fcPosInf) != fcNone)
5818 InterestedSrcs |= fcPosInf;
5819
5820 KnownFPClass KnownSrc;
5821 if (InterestedSrcs != fcNone)
5822 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5823 KnownSrc, Q, Depth + 1);
5824 const Function *F = II->getFunction();
5826 F ? F->getDenormalMode(
5827 II->getType()->getScalarType()->getFltSemantics())
5829 const bool IsMultiUnitFPType =
5830 V->getType()->getScalarType()->isMultiUnitFPType();
5831 Known = KnownFPClass::log(KnownSrc, Mode, IsMultiUnitFPType);
5832 break;
5833 }
5834 case Intrinsic::pow: {
5835 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5836 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5837 if (!WantNaN && !WantNegative)
5838 break;
5839
5840 FPClassTest InterestedLHS = fcNone;
5841 FPClassTest InterestedRHS = fcNone;
5842 if (WantNaN) {
5843 // pow may return NaN if one of the arguments is NaN. NaN may also be
5844 // produced from a negative, non-zero finite base and a non-integer
5845 // exponent.
5846 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5847 InterestedRHS |= fcNan;
5848 }
5849 if (WantNegative) {
5850 // A negative value is returned when a negative base is raised to an odd
5851 // integer power. Only normal values can be odd integers.
5852 InterestedLHS |= fcNegative;
5853 InterestedRHS |= fcNormal;
5854 }
5855
5856 KnownFPClass KnownLHS;
5857 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5858 KnownLHS, Q, Depth + 1);
5859
5860 // If the LHS is unknown, then querying the RHS is only useful for rare
5861 // edge cases.
5862 if (KnownLHS.isUnknown())
5863 break;
5864
5865 KnownFPClass KnownRHS;
5866 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5867 KnownRHS, Q, Depth + 1);
5868 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5869 break;
5870 }
5871 case Intrinsic::powi: {
5872 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5873 break;
5874
5875 // The exponent is always a scalar, even when raising a vector to a power.
5876 const Value *Exp = II->getArgOperand(1);
5877 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5878 KnownBits ExponentKnownBits(BitWidth);
5879 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5880
5881 FPClassTest InterestedSrcs = fcNone;
5882 if (InterestedClasses & fcNan)
5883 InterestedSrcs |= fcNan;
5884 if (!ExponentKnownBits.isZero()) {
5885 if (InterestedClasses & fcInf)
5886 InterestedSrcs |= fcFinite | fcInf;
5887 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5888 InterestedSrcs |= fcNegative;
5889 }
5890
5891 KnownFPClass KnownSrc;
5892 if (InterestedSrcs != fcNone)
5893 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5894 KnownSrc, Q, Depth + 1);
5895
5896 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5897 break;
5898 }
5899 case Intrinsic::ldexp: {
5900 KnownFPClass KnownSrc;
5901 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5902 KnownSrc, Q, Depth + 1);
5903 // Can refine inf/zero handling based on the exponent operand.
5904 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5905
5906 const Value *ExpArg = II->getArgOperand(1);
5907 ConstantRange ExpKnownRange =
5908 ((KnownSrc.getKnownFPClasses() & ExpInfoMask) != fcNone)
5909 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5910 : ConstantRange::getFull(
5911 ExpArg->getType()->getScalarSizeInBits());
5912
5913 const fltSemantics &Flt =
5914 II->getType()->getScalarType()->getFltSemantics();
5915
5916 const Function *F = II->getFunction();
5918 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5919
5920 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5921 ExpKnownRange.getSignedMax(), Flt, Mode);
5922 break;
5923 }
5924 case Intrinsic::arithmetic_fence: {
5925 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5926 Known, Q, Depth + 1);
5927 break;
5928 }
5929 case Intrinsic::experimental_constrained_sitofp:
5930 case Intrinsic::experimental_constrained_uitofp:
5931 // Cannot produce nan
5932 Known.knownNot(fcNan);
5933
5934 // sitofp and uitofp turn into +0.0 for zero.
5935 Known.knownNot(fcNegZero);
5936
5937 // Integers cannot be subnormal
5938 Known.knownNot(fcSubnormal);
5939
5940 if (IID == Intrinsic::experimental_constrained_uitofp)
5941 Known.signBitMustBeZero();
5942
5943 // TODO: Copy inf handling from instructions
5944 break;
5945
5946 case Intrinsic::amdgcn_fract: {
5947 Known.knownNot(fcInf);
5948
5949 if (InterestedClasses & fcNan) {
5950 KnownFPClass KnownSrc;
5951 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5952 InterestedClasses, KnownSrc, Q, Depth + 1);
5953
5954 if (KnownSrc.isKnownNeverInfOrNaN())
5955 Known.knownNot(fcNan);
5956 else if (KnownSrc.isKnownNever(fcSNan))
5957 Known.knownNot(fcSNan);
5958 }
5959
5960 break;
5961 }
5962 case Intrinsic::amdgcn_rcp: {
5963 KnownFPClass KnownSrc;
5964 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5965 KnownSrc, Q, Depth + 1);
5966
5967 Known.propagateNonNaN(KnownSrc);
5968
5969 Type *EltTy = II->getType()->getScalarType();
5970
5971 // f32 denormal always flushed.
5972 if (EltTy->isFloatTy()) {
5973 Known.knownNot(fcSubnormal);
5974 KnownSrc.knownNot(fcSubnormal);
5975 }
5976
5977 if (KnownSrc.isKnownNever(fcNegative))
5978 Known.knownNot(fcNegative);
5979 if (KnownSrc.isKnownNever(fcPositive))
5980 Known.knownNot(fcPositive);
5981
5982 if (const Function *F = II->getFunction()) {
5983 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5984 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5985 Known.knownNot(fcPosInf);
5986 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5987 Known.knownNot(fcNegInf);
5988 }
5989
5990 break;
5991 }
5992 case Intrinsic::amdgcn_rsq: {
5993 KnownFPClass KnownSrc;
5994 // The only negative value that can be returned is -inf for -0 inputs.
5996
5997 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5998 KnownSrc, Q, Depth + 1);
5999
6000 // Negative -> nan
6001 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
6002 Known.knownNot(fcNan);
6003 else if (KnownSrc.isKnownNever(fcSNan))
6004 Known.knownNot(fcSNan);
6005
6006 // +inf -> +0
6007 if (KnownSrc.isKnownNeverPosInfinity())
6008 Known.knownNot(fcPosZero);
6009
6010 Type *EltTy = II->getType()->getScalarType();
6011
6012 // f32 denormal always flushed.
6013 if (EltTy->isFloatTy())
6014 Known.knownNot(fcPosSubnormal);
6015
6016 if (const Function *F = II->getFunction()) {
6017 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
6018
6019 // -0 -> -inf
6020 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
6021 Known.knownNot(fcNegInf);
6022
6023 // +0 -> +inf
6024 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
6025 Known.knownNot(fcPosInf);
6026 }
6027
6028 break;
6029 }
6030 case Intrinsic::amdgcn_trig_preop: {
6031 // Always returns a value [0, 1)
6032 Known.knownNot(fcNan | fcInf | fcNegative);
6033 break;
6034 }
6035 case Intrinsic::convert_from_arbitrary_fp: {
6036 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
6037 StringRef FormatStr = cast<MDString>(MD)->getString();
6038
6039 const fltSemantics *SrcSemantics =
6041 if (!SrcSemantics)
6042 break;
6043
6044 const fltSemantics DstSemantics =
6045 II->getType()->getScalarType()->getFltSemantics();
6046
6047 if (!APFloat::semanticsHasNaN(*SrcSemantics))
6048 Known.knownNot(fcNan);
6049
6050 // fcInf can only be cleared if the source format has no Inf encoding
6051 // and the dst max exp can accommodate src max exp.
6052 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
6053 APFloat::semanticsMaxExponent(*SrcSemantics) <=
6054 APFloat::semanticsMaxExponent(DstSemantics))
6055 Known.knownNot(fcInf);
6056
6057 // Check and clear all neg flags for formats that do not have signed
6058 // representation.
6059 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
6060 Known.knownNot(fcNegative);
6061
6062 // Check if format has no zero at all (Float8E8M0FNU), or no negative
6063 // zero.
6064 if (!APFloat::semanticsHasZero(*SrcSemantics))
6065 Known.knownNot(fcZero);
6066 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
6067 Known.knownNot(fcNegZero);
6068
6069 // If src lands normally in dest, the result can never be subnormal.
6070 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
6071 Known.knownNot(fcSubnormal);
6072 break;
6073 }
6074 default:
6075 break;
6076 }
6077
6078 break;
6079 }
6080 case Instruction::FAdd:
6081 case Instruction::FSub: {
6082 KnownFPClass KnownLHS, KnownRHS;
6083 bool WantNegative =
6084 Op->getOpcode() == Instruction::FAdd &&
6085 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
6086 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
6087 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
6088
6089 if (!WantNaN && !WantNegative && !WantNegZero)
6090 break;
6091
6092 FPClassTest InterestedSrcs = InterestedClasses;
6093 if (WantNegative)
6094 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
6095 if (InterestedClasses & fcNan)
6096 InterestedSrcs |= fcInf;
6097 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
6098 KnownRHS, Q, Depth + 1);
6099
6100 // Special case fadd x, x, which is the canonical form of fmul x, 2.
6101 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
6102 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT,
6103 Depth + 1);
6104 if (Self)
6105 KnownLHS = KnownRHS;
6106
6107 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
6108 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
6109 WantNegZero || Opc == Instruction::FSub) {
6110
6111 // FIXME: Context function should always be passed in separately
6112 const Function *F = cast<Instruction>(Op)->getFunction();
6113 const fltSemantics &FltSem =
6114 Op->getType()->getScalarType()->getFltSemantics();
6116 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6117
6118 if (Self && Opc == Instruction::FAdd) {
6119 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
6120 } else {
6121 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
6122 // there's no point.
6123
6124 if (!Self) {
6125 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6126 KnownLHS, Q, Depth + 1);
6127 }
6128
6129 Known = Opc == Instruction::FAdd
6130 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
6131 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
6132 }
6133 }
6134
6135 break;
6136 }
6137 case Instruction::FMul: {
6138 const Function *F = cast<Instruction>(Op)->getFunction();
6140 F ? F->getDenormalMode(
6141 Op->getType()->getScalarType()->getFltSemantics())
6143
6144 Value *LHS = Op->getOperand(0);
6145 Value *RHS = Op->getOperand(1);
6146 // X * X is always non-negative or a NaN.
6147 // FIXME: Should check isGuaranteedNotToBeUndef
6148 if (LHS == RHS) {
6149 KnownFPClass KnownSrc;
6150 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
6151 Depth + 1);
6152 Known = KnownFPClass::square(KnownSrc, Mode);
6153 break;
6154 }
6155
6156 KnownFPClass KnownLHS, KnownRHS;
6157
6158 const APFloat *CRHS;
6159 if (match(RHS, m_APFloat(CRHS))) {
6160 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6161 Depth + 1);
6162 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
6163 } else {
6164 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
6165 Depth + 1);
6166 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
6167 // additional not-nan if the addend is known-not negative infinity if the
6168 // multiply is known-not infinity.
6169
6170 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
6171 Depth + 1);
6172 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
6173 }
6174
6175 /// Propgate no-infs if the other source is known smaller than one, such
6176 /// that this cannot introduce overflow.
6177 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
6178 Known.knownNot(fcInf);
6179 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
6180 Known.knownNot(fcInf);
6181
6182 break;
6183 }
6184 case Instruction::FDiv: {
6185 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
6186
6187 const Function *F = cast<Instruction>(Op)->getFunction();
6188 const fltSemantics &FltSem =
6189 Op->getType()->getScalarType()->getFltSemantics();
6191 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
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 1.0 or a NaN.
6196 Known.setKnownFPClasses(fcNan | fcPosNormal);
6197
6198 if (!WantNan)
6199 break;
6200
6201 KnownFPClass KnownSrc;
6202 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6203 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6204 Depth + 1);
6205
6206 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
6207 break;
6208 }
6209
6210 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6211 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6212 if (!WantNan && !WantNegative && !WantPositive)
6213 break;
6214
6215 KnownFPClass KnownLHS, KnownRHS;
6216 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
6217 Q, Depth + 1);
6218
6219 bool KnowSomethingUseful =
6220 KnownRHS.isKnownNever(fcSNan) ||
6223
6224 if (KnowSomethingUseful)
6225 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6226 Q, Depth + 1);
6227
6228 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
6229 break;
6230 }
6231 case Instruction::FRem: {
6232 FPClassTest InterestedLHS = fcNone;
6233 FPClassTest InterestedRHS = fcNone;
6234
6235 // NaN is also generated for frem(Inf, x) and frem(x, 0.0).
6236 if (InterestedClasses & fcNan) {
6237 InterestedLHS |= fcNan | fcInf;
6238 InterestedRHS |= fcNan | fcZero | fcSubnormal;
6239 }
6240
6241 // The sign for frem is the same as the first operand.
6242 if (InterestedClasses & (fcPosNormal | fcPosSubnormal))
6243 InterestedLHS |= fcPosNormal | fcPosSubnormal;
6244 if (InterestedClasses & (fcNegNormal | fcNegSubnormal))
6245 InterestedLHS |= fcNegNormal | fcNegSubnormal;
6246
6247 // A negative zero result requires a negative finite first operand.
6248 if (InterestedClasses & fcNegZero)
6249 InterestedLHS |= fcNegFinite;
6250
6251 // A positive zero result can additionally come from a negative finite
6252 // result being flushed to positive zero.
6253 if (InterestedClasses & fcPosZero)
6254 InterestedLHS |= fcPosFinite | fcNegNormal | fcNegSubnormal;
6255
6256 const Function *F = cast<Instruction>(Op)->getFunction();
6258 F ? F->getDenormalMode(
6259 Op->getType()->getScalarType()->getFltSemantics())
6261
6262 if (Op->getOperand(0) == Op->getOperand(1) &&
6263 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CtxI, Q.DT)) {
6264 // X % X is always exactly [+-]0.0 or a NaN.
6265 FPClassTest InterestedSrcs = InterestedLHS | InterestedRHS;
6266 KnownFPClass KnownSrc;
6267 if (InterestedSrcs != fcNone)
6268 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
6269 KnownSrc, Q, Depth + 1);
6270 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6271 break;
6272 }
6273
6274 KnownFPClass KnownLHS;
6275 if (InterestedLHS != fcNone)
6276 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedLHS,
6277 KnownLHS, Q, Depth + 1);
6278
6279 KnownFPClass KnownRHS;
6280 // RHS is only useful for refining NaN classes.
6281 if (InterestedRHS != fcNone && KnownLHS.isKnownNever(fcSNan))
6282 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedRHS,
6283 KnownRHS, Q, Depth + 1);
6284
6285 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6286
6287 break;
6288 }
6289 case Instruction::FPExt: {
6290 KnownFPClass KnownSrc;
6291 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6292 KnownSrc, Q, Depth + 1);
6293
6294 const fltSemantics &DstTy =
6295 Op->getType()->getScalarType()->getFltSemantics();
6296 const fltSemantics &SrcTy =
6297 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6298
6299 const auto *I = dyn_cast<Instruction>(Op);
6300 const Function *F = I ? I->getFunction() : nullptr;
6301 DenormalMode DstMode =
6302 F ? F->getDenormalMode(DstTy) : DenormalMode::getDynamic();
6303 DenormalMode SrcMode =
6304 F ? F->getDenormalMode(SrcTy) : DenormalMode::getDynamic();
6305
6306 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy, DstMode, SrcMode);
6307 break;
6308 }
6309 case Instruction::FPTrunc: {
6310 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6311 Depth);
6312 break;
6313 }
6314 case Instruction::SIToFP:
6315 case Instruction::UIToFP: {
6316 // Cannot produce nan
6317 Known.knownNot(fcNan);
6318
6319 // Integers cannot be subnormal
6320 Known.knownNot(fcSubnormal);
6321
6322 // sitofp and uitofp turn into +0.0 for zero.
6323 Known.knownNot(fcNegZero);
6324
6325 // UIToFP is always non-negative regardless of known bits.
6326 if (Op->getOpcode() == Instruction::UIToFP)
6327 Known.signBitMustBeZero();
6328
6329 // Only compute known bits if we can learn something useful from them.
6330 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6331 break;
6332
6333 KnownBits IntKnown =
6334 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6335
6336 // If the integer is non-zero, the result cannot be +0.0
6337 if (IntKnown.isNonZero())
6338 Known.knownNot(fcPosZero);
6339
6340 if (Op->getOpcode() == Instruction::SIToFP) {
6341 // If the signed integer is known non-negative, the result is
6342 // non-negative. If the signed integer is known negative, the result is
6343 // negative.
6344 if (IntKnown.isNonNegative()) {
6345 Known.signBitMustBeZero();
6346 } else if (IntKnown.isNegative()) {
6347 Known.signBitMustBeOne();
6348 }
6349 }
6350
6351 // Guard kept for ilogb()
6352 if (InterestedClasses & fcInf) {
6353 // Get width of largest magnitude integer known.
6354 // This still works for a signed minimum value because the largest FP
6355 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6356 int IntSize = IntKnown.getBitWidth();
6357 if (Op->getOpcode() == Instruction::UIToFP)
6358 IntSize -= IntKnown.countMinLeadingZeros();
6359 else if (Op->getOpcode() == Instruction::SIToFP)
6360 IntSize -= IntKnown.countMinSignBits();
6361
6362 // If the exponent of the largest finite FP value can hold the largest
6363 // integer, the result of the cast must be finite.
6364 Type *FPTy = Op->getType()->getScalarType();
6365 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6366 Known.knownNot(fcInf);
6367 }
6368
6369 break;
6370 }
6371 case Instruction::ExtractElement: {
6372 // Look through extract element. If the index is non-constant or
6373 // out-of-range demand all elements, otherwise just the extracted element.
6374 const Value *Vec = Op->getOperand(0);
6375
6376 APInt DemandedVecElts;
6377 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6378 unsigned NumElts = VecTy->getNumElements();
6379 DemandedVecElts = APInt::getAllOnes(NumElts);
6380 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6381 if (CIdx && CIdx->getValue().ult(NumElts))
6382 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6383 } else {
6384 DemandedVecElts = APInt(1, 1);
6385 }
6386
6387 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6388 Q, Depth + 1);
6389 }
6390 case Instruction::InsertElement: {
6391 if (isa<ScalableVectorType>(Op->getType()))
6392 return;
6393
6394 const Value *Vec = Op->getOperand(0);
6395 const Value *Elt = Op->getOperand(1);
6396 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6397 unsigned NumElts = DemandedElts.getBitWidth();
6398 APInt DemandedVecElts = DemandedElts;
6399 bool NeedsElt = true;
6400 // If we know the index we are inserting to, clear it from Vec check.
6401 if (CIdx && CIdx->getValue().ult(NumElts)) {
6402 DemandedVecElts.clearBit(CIdx->getZExtValue());
6403 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6404 }
6405
6406 // Do we demand the inserted element?
6407 if (NeedsElt) {
6408 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6409 // If we don't know any bits, early out.
6410 if (Known.isUnknown())
6411 break;
6412 } else {
6414 }
6415
6416 // Do we need anymore elements from Vec?
6417 if (!DemandedVecElts.isZero()) {
6418 KnownFPClass Known2;
6419 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6420 Depth + 1);
6421 Known |= Known2;
6422 }
6423
6424 break;
6425 }
6426 case Instruction::ShuffleVector: {
6427 // Handle vector splat idiom
6428 if (Value *Splat = getSplatValue(V)) {
6429 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6430 break;
6431 }
6432
6433 // For undef elements, we don't know anything about the common state of
6434 // the shuffle result.
6435 APInt DemandedLHS, DemandedRHS;
6436 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6437 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6438 return;
6439
6440 if (!!DemandedLHS) {
6441 const Value *LHS = Shuf->getOperand(0);
6442 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6443 Depth + 1);
6444
6445 // If we don't know any bits, early out.
6446 if (Known.isUnknown())
6447 break;
6448 } else {
6450 }
6451
6452 if (!!DemandedRHS) {
6453 KnownFPClass Known2;
6454 const Value *RHS = Shuf->getOperand(1);
6455 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6456 Depth + 1);
6457 Known |= Known2;
6458 }
6459
6460 break;
6461 }
6462 case Instruction::ExtractValue: {
6463 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6464 ArrayRef<unsigned> Indices = Extract->getIndices();
6465 const Value *Src = Extract->getAggregateOperand();
6466 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6467 Indices[0] == 0) {
6468 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6469 switch (II->getIntrinsicID()) {
6470 case Intrinsic::frexp: {
6471 FPClassTest InterestedSrcs = InterestedClasses;
6472
6473 // Positive subnormals and negative subnormals could become positive
6474 // zero.
6475 if (InterestedClasses & fcPosZero)
6476 InterestedSrcs |= fcSubnormal;
6477
6478 // Negative subnormals could become negative zero.
6479 if (InterestedClasses & fcNegZero)
6480 InterestedSrcs |= fcNegSubnormal;
6481
6482 if (InterestedClasses & fcPosNormal)
6483 InterestedSrcs |= fcPosSubnormal;
6484
6485 if (InterestedClasses & fcNegNormal)
6486 InterestedSrcs |= fcNegSubnormal;
6487
6488 KnownFPClass KnownSrc;
6489 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6490 InterestedSrcs, KnownSrc, Q, Depth + 1);
6491
6492 const Function *F = cast<Instruction>(Op)->getFunction();
6493 const fltSemantics &FltSem =
6494 Op->getType()->getScalarType()->getFltSemantics();
6495
6497 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6498 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6499 return;
6500 }
6501 default:
6502 break;
6503 }
6504 }
6505 }
6506
6507 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6508 Depth + 1);
6509 break;
6510 }
6511 case Instruction::PHI: {
6512 const PHINode *P = cast<PHINode>(Op);
6513 // Unreachable blocks may have zero-operand PHI nodes.
6514 if (P->getNumIncomingValues() == 0)
6515 break;
6516
6517 // Otherwise take the unions of the known bit sets of the operands,
6518 // taking conservative care to avoid excessive recursion.
6519 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6520
6521 if (Depth < PhiRecursionLimit) {
6522 // Skip if every incoming value references to ourself.
6523 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6524 break;
6525
6526 bool First = true;
6527
6528 for (const Use &U : P->operands()) {
6529 Value *IncValue;
6530 Instruction *CtxI;
6531 breakSelfRecursivePHI(&U, P, IncValue, CtxI);
6532 // Skip direct self references.
6533 if (IncValue == P)
6534 continue;
6535
6536 KnownFPClass KnownSrc;
6537 // Recurse, but cap the recursion to two levels, because we don't want
6538 // to waste time spinning around in loops. We need at least depth 2 to
6539 // detect known sign bits.
6540 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6542 PhiRecursionLimit);
6543
6544 if (First) {
6545 Known = KnownSrc;
6546 First = false;
6547 } else {
6548 Known |= KnownSrc;
6549 }
6550
6551 if (Known.getKnownFPClasses() == fcAllFlags)
6552 break;
6553 }
6554 }
6555
6556 // Look for the case of a for loop which has a positive
6557 // initial value and is incremented by a squared value.
6558 // This will propagate sign information out of such loops.
6559 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6560 break;
6561 for (unsigned I = 0; I < 2; I++) {
6562 Value *RecurValue = P->getIncomingValue(1 - I);
6564 if (!II)
6565 continue;
6566 Value *R, *L, *Init;
6567 PHINode *PN;
6569 PN == P) {
6570 switch (II->getIntrinsicID()) {
6571 case Intrinsic::fma:
6572 case Intrinsic::fmuladd: {
6573 KnownFPClass KnownStart;
6574 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6575 Q, Depth + 1);
6576 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6577 isGuaranteedNotToBeUndef(L, Q.AC, Q.CtxI, Q.DT, Depth + 1))
6579 break;
6580 }
6581 }
6582 }
6583 }
6584 break;
6585 }
6586 case Instruction::BitCast: {
6587 const Value *Src;
6588 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6589 !Src->getType()->isIntOrIntVectorTy())
6590 break;
6591
6592 const Type *Ty = Op->getType();
6593
6594 Value *CastLHS, *CastRHS;
6595
6596 // Match bitcast(umax(bitcast(a), bitcast(b)))
6597 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6598 m_BitCast(m_Value(CastRHS)))) &&
6599 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6600 KnownFPClass KnownLHS, KnownRHS;
6601 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6602 Depth + 1);
6603 if (!KnownRHS.isUnknown()) {
6604 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6605 Q, Depth + 1);
6606 Known = KnownLHS | KnownRHS;
6607 }
6608
6609 return;
6610 }
6611
6612 const Type *EltTy = Ty->getScalarType();
6613 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6614 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6615
6617 break;
6618 }
6619 default:
6620 break;
6621 }
6622}
6623
6625 const APInt &DemandedElts,
6626 FPClassTest InterestedClasses,
6627 const SimplifyQuery &SQ,
6628 unsigned Depth) {
6629 KnownFPClass KnownClasses;
6630 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6631 Depth);
6632 return KnownClasses;
6633}
6634
6636 FPClassTest InterestedClasses,
6637 const SimplifyQuery &SQ,
6638 unsigned Depth) {
6640 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6641 return Known;
6642}
6643
6645 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6646 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CtxI,
6647 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6648 return computeKnownFPClass(V, InterestedClasses,
6649 SimplifyQuery(DL, TLI, DT, AC, CtxI, UseInstrInfo),
6650 Depth);
6651}
6652
6654llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6655 FastMathFlags FMF, FPClassTest InterestedClasses,
6656 const SimplifyQuery &SQ, unsigned Depth) {
6657 if (FMF.noNaNs())
6658 InterestedClasses &= ~fcNan;
6659 if (FMF.noInfs())
6660 InterestedClasses &= ~fcInf;
6661
6662 KnownFPClass Result =
6663 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6664
6665 if (FMF.noNaNs())
6666 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcNan);
6667 if (FMF.noInfs())
6668 Result.setKnownFPClasses(Result.getKnownFPClasses() & ~fcInf);
6669 return Result;
6670}
6671
6673 FPClassTest InterestedClasses,
6674 const SimplifyQuery &SQ,
6675 unsigned Depth) {
6676 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6677 APInt DemandedElts =
6678 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6679 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6680 Depth);
6681}
6682
6684 unsigned Depth) {
6686 return Known.isKnownNever(fcNegZero);
6687}
6688
6690 unsigned Depth) {
6693 return Known.cannotBeOrderedLessThanZero();
6694}
6695
6697 unsigned Depth) {
6699 return Known.isKnownNeverInfinity();
6700}
6701
6702/// Return true if the floating-point value can never contain a NaN or infinity.
6704 unsigned Depth) {
6706 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6707}
6708
6709/// Return true if the floating-point scalar value is not a NaN or if the
6710/// floating-point vector value has no NaN elements. Return false if a value
6711/// could ever be NaN.
6713 unsigned Depth) {
6715 return Known.isKnownNeverNaN();
6716}
6717
6718/// Return false if we can prove that the specified FP value's sign bit is 0.
6719/// Return true if we can prove that the specified FP value's sign bit is 1.
6720/// Otherwise return std::nullopt.
6721std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6722 const SimplifyQuery &SQ,
6723 unsigned Depth) {
6725 return Known.getSignBit();
6726}
6727
6729 auto *User = cast<Instruction>(U.getUser());
6730 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6731 if (FPOp->hasNoSignedZeros())
6732 return true;
6733 }
6734
6735 switch (User->getOpcode()) {
6736 case Instruction::FPToSI:
6737 case Instruction::FPToUI:
6738 return true;
6739 case Instruction::FRem:
6740 // frem(x, +-0.0) == NaN, and more generally frem(x, y) == frem(x, -y).
6741 return U.getOperandNo() == 1;
6742 case Instruction::FCmp:
6743 // fcmp treats both positive and negative zero as equal.
6744 return true;
6745 case Instruction::Call:
6746 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6747 switch (II->getIntrinsicID()) {
6748 case Intrinsic::fabs:
6749 case Intrinsic::exp:
6750 case Intrinsic::exp2:
6751 case Intrinsic::exp10:
6752 case Intrinsic::log:
6753 case Intrinsic::log2:
6754 case Intrinsic::log10:
6755 case Intrinsic::cos:
6756 case Intrinsic::acos:
6757 case Intrinsic::cosh:
6758 case Intrinsic::fptosi_sat:
6759 case Intrinsic::fptoui_sat:
6760 case Intrinsic::lround:
6761 case Intrinsic::llround:
6762 case Intrinsic::lrint:
6763 case Intrinsic::llrint:
6764 return true;
6765 case Intrinsic::copysign:
6766 return U.getOperandNo() == 0;
6767 case Intrinsic::pow:
6768 // pow(x, +-0.0) == +1.0 or NaN
6769 return U.getOperandNo() == 1;
6770 case Intrinsic::is_fpclass: {
6771 auto Test =
6772 static_cast<FPClassTest>(
6773 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6776 }
6777 default:
6778 return false;
6779 }
6780 }
6781 return false;
6782 default:
6783 return false;
6784 }
6785}
6786
6788 auto *User = cast<Instruction>(U.getUser());
6789 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6790 if (FPOp->hasNoNaNs())
6791 return true;
6792 }
6793
6794 switch (User->getOpcode()) {
6795 case Instruction::FPToSI:
6796 case Instruction::FPToUI:
6797 return true;
6798 // Proper FP math operations ignore the sign bit of NaN.
6799 case Instruction::FAdd:
6800 case Instruction::FSub:
6801 case Instruction::FMul:
6802 case Instruction::FDiv:
6803 case Instruction::FRem:
6804 case Instruction::FPTrunc:
6805 case Instruction::FPExt:
6806 case Instruction::FCmp:
6807 return true;
6808 // Bitwise FP operations should preserve the sign bit of NaN.
6809 case Instruction::FNeg:
6810 case Instruction::Select:
6811 case Instruction::PHI:
6812 return false;
6813 case Instruction::Ret:
6814 return User->getFunction()->getAttributes().getRetNoFPClass() &
6816 case Instruction::Call:
6817 case Instruction::Invoke: {
6818 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6819 switch (II->getIntrinsicID()) {
6820 case Intrinsic::fabs:
6821 return true;
6822 case Intrinsic::copysign:
6823 return U.getOperandNo() == 0;
6824 // Other proper FP math intrinsics ignore the sign bit of NaN.
6825 case Intrinsic::maxnum:
6826 case Intrinsic::minnum:
6827 case Intrinsic::maximum:
6828 case Intrinsic::minimum:
6829 case Intrinsic::maximumnum:
6830 case Intrinsic::minimumnum:
6831 case Intrinsic::canonicalize:
6832 case Intrinsic::fma:
6833 case Intrinsic::fmuladd:
6834 case Intrinsic::sqrt:
6835 case Intrinsic::pow:
6836 case Intrinsic::powi:
6837 case Intrinsic::fptoui_sat:
6838 case Intrinsic::fptosi_sat:
6839 case Intrinsic::is_fpclass:
6840 return true;
6841 default:
6842 return false;
6843 }
6844 }
6845
6846 FPClassTest NoFPClass =
6847 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6848 return NoFPClass & FPClassTest::fcNan;
6849 }
6850 default:
6851 return false;
6852 }
6853}
6854
6856 FastMathFlags FMF) {
6857 if (isa<PoisonValue>(V))
6858 return true;
6859 if (isa<UndefValue>(V))
6860 return false;
6861
6862 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6863 return true;
6864
6866 if (!I)
6867 return false;
6868
6869 switch (I->getOpcode()) {
6870 case Instruction::SIToFP:
6871 case Instruction::UIToFP:
6872 // TODO: Could check nofpclass(inf) on incoming argument
6873 if (FMF.noInfs())
6874 return true;
6875
6876 // Need to check int size cannot produce infinity, which computeKnownFPClass
6877 // knows how to do already.
6878 return isKnownNeverInfinity(I, SQ);
6879 case Instruction::Call: {
6880 const CallInst *CI = cast<CallInst>(I);
6881 switch (CI->getIntrinsicID()) {
6882 case Intrinsic::trunc:
6883 case Intrinsic::floor:
6884 case Intrinsic::ceil:
6885 case Intrinsic::rint:
6886 case Intrinsic::nearbyint:
6887 case Intrinsic::round:
6888 case Intrinsic::roundeven:
6889 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6890 default:
6891 break;
6892 }
6893
6894 break;
6895 }
6896 default:
6897 break;
6898 }
6899
6900 return false;
6901}
6902
6904
6905 // All byte-wide stores are splatable, even of arbitrary variables.
6906 if (V->getType()->isIntegerTy(8))
6907 return V;
6908
6909 LLVMContext &Ctx = V->getContext();
6910
6911 // Undef don't care.
6912 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6913 if (isa<UndefValue>(V))
6914 return UndefInt8;
6915
6916 // Return poison for zero-sized type.
6917 if (DL.getTypeStoreSize(V->getType()).isZero())
6918 return PoisonValue::get(Type::getInt8Ty(Ctx));
6919
6921 if (!C) {
6922 // Conceptually, we could handle things like:
6923 // %a = zext i8 %X to i16
6924 // %b = shl i16 %a, 8
6925 // %c = or i16 %a, %b
6926 // but until there is an example that actually needs this, it doesn't seem
6927 // worth worrying about.
6928 return nullptr;
6929 }
6930
6931 // Handle 'null' ConstantArrayZero etc.
6932 if (C->isNullValue())
6934
6935 // Constant floating-point values can be handled as integer values if the
6936 // corresponding integer value is "byteable". An important case is 0.0.
6937 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6938 Type *ScalarTy = CFP->getType()->getScalarType();
6939 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6940 return isBytewiseValue(
6941 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6942
6943 // Don't handle long double formats, which have strange constraints.
6944 return nullptr;
6945 }
6946
6947 // We can handle constant integers that are multiple of 8 bits.
6948 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6949 if (CI->getBitWidth() % 8 == 0) {
6950 if (!CI->getValue().isSplat(8))
6951 return nullptr;
6952 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6953 }
6954 }
6955
6956 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6957 if (CE->getOpcode() == Instruction::IntToPtr) {
6958 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6959 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6961 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6962 return isBytewiseValue(Op, DL);
6963 }
6964 }
6965 }
6966
6967 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6968 if (LHS == RHS)
6969 return LHS;
6970 if (!LHS || !RHS)
6971 return nullptr;
6972 if (LHS == UndefInt8)
6973 return RHS;
6974 if (RHS == UndefInt8)
6975 return LHS;
6976 return nullptr;
6977 };
6978
6980 Value *Val = UndefInt8;
6981 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6982 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6983 return nullptr;
6984 return Val;
6985 }
6986
6988 Value *Val = UndefInt8;
6989 for (Value *Op : C->operands())
6990 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6991 return nullptr;
6992 return Val;
6993 }
6994
6995 // Don't try to handle the handful of other constants.
6996 return nullptr;
6997}
6998
6999// This is the recursive version of BuildSubAggregate. It takes a few different
7000// arguments. Idxs is the index within the nested struct From that we are
7001// looking at now (which is of type IndexedType). IdxSkip is the number of
7002// indices from Idxs that should be left out when inserting into the resulting
7003// struct. To is the result struct built so far, new insertvalue instructions
7004// build on that.
7005static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
7007 unsigned IdxSkip,
7008 BasicBlock::iterator InsertBefore) {
7009 StructType *STy = dyn_cast<StructType>(IndexedType);
7010 if (STy) {
7011 // Save the original To argument so we can modify it
7012 Value *OrigTo = To;
7013 // General case, the type indexed by Idxs is a struct
7014 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
7015 // Process each struct element recursively
7016 Idxs.push_back(i);
7017 Value *PrevTo = To;
7018 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
7019 InsertBefore);
7020 Idxs.pop_back();
7021 if (!To) {
7022 // Couldn't find any inserted value for this index? Cleanup
7023 while (PrevTo != OrigTo) {
7025 PrevTo = Del->getAggregateOperand();
7026 Del->eraseFromParent();
7027 }
7028 // Stop processing elements
7029 break;
7030 }
7031 }
7032 // If we successfully found a value for each of our subaggregates
7033 if (To)
7034 return To;
7035 }
7036 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
7037 // the struct's elements had a value that was inserted directly. In the latter
7038 // case, perhaps we can't determine each of the subelements individually, but
7039 // we might be able to find the complete struct somewhere.
7040
7041 // Find the value that is at that particular spot
7042 Value *V = FindInsertedValue(From, Idxs);
7043
7044 if (!V)
7045 return nullptr;
7046
7047 // Insert the value in the new (sub) aggregate
7048 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
7049 InsertBefore);
7050}
7051
7052// This helper takes a nested struct and extracts a part of it (which is again a
7053// struct) into a new value. For example, given the struct:
7054// { a, { b, { c, d }, e } }
7055// and the indices "1, 1" this returns
7056// { c, d }.
7057//
7058// It does this by inserting an insertvalue for each element in the resulting
7059// struct, as opposed to just inserting a single struct. This will only work if
7060// each of the elements of the substruct are known (ie, inserted into From by an
7061// insertvalue instruction somewhere).
7062//
7063// All inserted insertvalue instructions are inserted before InsertBefore
7065 BasicBlock::iterator InsertBefore) {
7066 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
7067 idx_range);
7068 Value *To = PoisonValue::get(IndexedType);
7069 SmallVector<unsigned, 10> Idxs(idx_range);
7070 unsigned IdxSkip = Idxs.size();
7071
7072 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
7073}
7074
7075/// Given an aggregate and a sequence of indices, see if the scalar value
7076/// indexed is already around as a register, for example if it was inserted
7077/// directly into the aggregate.
7078///
7079/// If InsertBefore is not null, this function will duplicate (modified)
7080/// insertvalues when a part of a nested struct is extracted.
7081Value *
7083 std::optional<BasicBlock::iterator> InsertBefore) {
7084 // Nothing to index? Just return V then (this is useful at the end of our
7085 // recursion).
7086 if (idx_range.empty())
7087 return V;
7088 // We have indices, so V should have an indexable type.
7089 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
7090 "Not looking at a struct or array?");
7091 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
7092 "Invalid indices for type?");
7093
7094 if (Constant *C = dyn_cast<Constant>(V)) {
7095 C = C->getAggregateElement(idx_range[0]);
7096 if (!C) return nullptr;
7097 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
7098 }
7099
7101 // Loop the indices for the insertvalue instruction in parallel with the
7102 // requested indices
7103 const unsigned *req_idx = idx_range.begin();
7104 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
7105 i != e; ++i, ++req_idx) {
7106 if (req_idx == idx_range.end()) {
7107 // We can't handle this without inserting insertvalues
7108 if (!InsertBefore)
7109 return nullptr;
7110
7111 // The requested index identifies a part of a nested aggregate. Handle
7112 // this specially. For example,
7113 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
7114 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
7115 // %C = extractvalue {i32, { i32, i32 } } %B, 1
7116 // This can be changed into
7117 // %A = insertvalue {i32, i32 } undef, i32 10, 0
7118 // %C = insertvalue {i32, i32 } %A, i32 11, 1
7119 // which allows the unused 0,0 element from the nested struct to be
7120 // removed.
7121 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
7122 *InsertBefore);
7123 }
7124
7125 // This insert value inserts something else than what we are looking for.
7126 // See if the (aggregate) value inserted into has the value we are
7127 // looking for, then.
7128 if (*req_idx != *i)
7129 return FindInsertedValue(I->getAggregateOperand(), idx_range,
7130 InsertBefore);
7131 }
7132 // If we end up here, the indices of the insertvalue match with those
7133 // requested (though possibly only partially). Now we recursively look at
7134 // the inserted value, passing any remaining indices.
7135 return FindInsertedValue(I->getInsertedValueOperand(),
7136 ArrayRef(req_idx, idx_range.end()), InsertBefore);
7137 }
7138
7140 // If we're extracting a value from an aggregate that was extracted from
7141 // something else, we can extract from that something else directly instead.
7142 // However, we will need to chain I's indices with the requested indices.
7143
7144 // Calculate the number of indices required
7145 unsigned size = I->getNumIndices() + idx_range.size();
7146 // Allocate some space to put the new indices in
7148 Idxs.reserve(size);
7149 // Add indices from the extract value instruction
7150 Idxs.append(I->idx_begin(), I->idx_end());
7151
7152 // Add requested indices
7153 Idxs.append(idx_range.begin(), idx_range.end());
7154
7155 assert(Idxs.size() == size
7156 && "Number of indices added not correct?");
7157
7158 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
7159 }
7160 // Otherwise, we don't know (such as, extracting from a function return value
7161 // or load instruction)
7162 return nullptr;
7163}
7164
7165// If V refers to an initialized global constant, set Slice either to
7166// its initializer if the size of its elements equals ElementSize, or,
7167// for ElementSize == 8, to its representation as an array of unsiged
7168// char. Return true on success.
7169// Offset is in the unit "nr of ElementSize sized elements".
7172 unsigned ElementSize, uint64_t Offset) {
7173 assert(V && "V should not be null.");
7174 assert((ElementSize % 8) == 0 &&
7175 "ElementSize expected to be a multiple of the size of a byte.");
7176 unsigned ElementSizeInBytes = ElementSize / 8;
7177
7178 // Drill down into the pointer expression V, ignoring any intervening
7179 // casts, and determine the identity of the object it references along
7180 // with the cumulative byte offset into it.
7181 const GlobalVariable *GV =
7183 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7184 // Fail if V is not based on constant global object.
7185 return false;
7186
7187 const DataLayout &DL = GV->getDataLayout();
7188 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
7189
7191 /*AllowNonInbounds*/ true))
7192 // Fail if a constant offset could not be determined.
7193 return false;
7194
7195 uint64_t StartIdx = Off.getLimitedValue();
7196 if (StartIdx == UINT64_MAX)
7197 // Fail if the constant offset is excessive.
7198 return false;
7199
7200 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
7201 // elements. Simply bail out if that isn't possible.
7202 if ((StartIdx % ElementSizeInBytes) != 0)
7203 return false;
7204
7205 Offset += StartIdx / ElementSizeInBytes;
7206 ConstantDataArray *Array = nullptr;
7207 ArrayType *ArrayTy = nullptr;
7208
7209 if (GV->getInitializer()->isNullValue()) {
7210 Type *GVTy = GV->getValueType();
7211 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
7212 uint64_t Length = SizeInBytes / ElementSizeInBytes;
7213
7214 Slice.Array = nullptr;
7215 Slice.Offset = 0;
7216 // Return an empty Slice for undersized constants to let callers
7217 // transform even undefined library calls into simpler, well-defined
7218 // expressions. This is preferable to making the calls although it
7219 // prevents sanitizers from detecting such calls.
7220 Slice.Length = Length < Offset ? 0 : Length - Offset;
7221 return true;
7222 }
7223
7224 auto *Init = const_cast<Constant *>(GV->getInitializer());
7225 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
7226 Type *InitElTy = ArrayInit->getElementType();
7227 if (InitElTy->isIntegerTy(ElementSize)) {
7228 // If Init is an initializer for an array of the expected type
7229 // and size, use it as is.
7230 Array = ArrayInit;
7231 ArrayTy = ArrayInit->getType();
7232 }
7233 }
7234
7235 if (!Array) {
7236 if (ElementSize != 8)
7237 // TODO: Handle conversions to larger integral types.
7238 return false;
7239
7240 // Otherwise extract the portion of the initializer starting
7241 // at Offset as an array of bytes, and reset Offset.
7243 if (!Init)
7244 return false;
7245
7246 Offset = 0;
7248 ArrayTy = dyn_cast<ArrayType>(Init->getType());
7249 }
7250
7251 uint64_t NumElts = ArrayTy->getArrayNumElements();
7252 if (Offset > NumElts)
7253 return false;
7254
7255 Slice.Array = Array;
7256 Slice.Offset = Offset;
7257 Slice.Length = NumElts - Offset;
7258 return true;
7259}
7260
7261/// Extract bytes from the initializer of the constant array V, which need
7262/// not be a nul-terminated string. On success, store the bytes in Str and
7263/// return true. When TrimAtNul is set, Str will contain only the bytes up
7264/// to but not including the first nul. Return false on failure.
7266 bool TrimAtNul) {
7268 if (!getConstantDataArrayInfo(V, Slice, 8))
7269 return false;
7270
7271 if (Slice.Array == nullptr) {
7272 if (TrimAtNul) {
7273 // Return a nul-terminated string even for an empty Slice. This is
7274 // safe because all existing SimplifyLibcalls callers require string
7275 // arguments and the behavior of the functions they fold is undefined
7276 // otherwise. Folding the calls this way is preferable to making
7277 // the undefined library calls, even though it prevents sanitizers
7278 // from reporting such calls.
7279 Str = StringRef();
7280 return true;
7281 }
7282 if (Slice.Length == 1) {
7283 Str = StringRef("", 1);
7284 return true;
7285 }
7286 // We cannot instantiate a StringRef as we do not have an appropriate string
7287 // of 0s at hand.
7288 return false;
7289 }
7290
7291 // Start out with the entire array in the StringRef.
7292 Str = Slice.Array->getAsString();
7293 // Skip over 'offset' bytes.
7294 Str = Str.substr(Slice.Offset);
7295
7296 if (TrimAtNul) {
7297 // Trim off the \0 and anything after it. If the array is not nul
7298 // terminated, we just return the whole end of string. The client may know
7299 // some other way that the string is length-bound.
7300 Str = Str.substr(0, Str.find('\0'));
7301 }
7302 return true;
7303}
7304
7305// These next two are very similar to the above, but also look through PHI
7306// nodes.
7307// TODO: See if we can integrate these two together.
7308
7309/// If we can compute the length of the string pointed to by
7310/// the specified pointer, return 'len+1'. If we can't, return 0.
7313 unsigned CharSize) {
7314 // Look through noop bitcast instructions.
7315 V = V->stripPointerCasts();
7316
7317 // If this is a PHI node, there are two cases: either we have already seen it
7318 // or we haven't.
7319 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7320 if (!PHIs.insert(PN).second)
7321 return ~0ULL; // already in the set.
7322
7323 // If it was new, see if all the input strings are the same length.
7324 uint64_t LenSoFar = ~0ULL;
7325 for (Value *IncValue : PN->incoming_values()) {
7326 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7327 if (Len == 0) return 0; // Unknown length -> unknown.
7328
7329 if (Len == ~0ULL) continue;
7330
7331 if (Len != LenSoFar && LenSoFar != ~0ULL)
7332 return 0; // Disagree -> unknown.
7333 LenSoFar = Len;
7334 }
7335
7336 // Success, all agree.
7337 return LenSoFar;
7338 }
7339
7340 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7341 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7342 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7343 if (Len1 == 0) return 0;
7344 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7345 if (Len2 == 0) return 0;
7346 if (Len1 == ~0ULL) return Len2;
7347 if (Len2 == ~0ULL) return Len1;
7348 if (Len1 != Len2) return 0;
7349 return Len1;
7350 }
7351
7352 // Otherwise, see if we can read the string.
7354 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7355 return 0;
7356
7357 if (Slice.Array == nullptr)
7358 // Zeroinitializer (including an empty one).
7359 return 1;
7360
7361 // Search for the first nul character. Return a conservative result even
7362 // when there is no nul. This is safe since otherwise the string function
7363 // being folded such as strlen is undefined, and can be preferable to
7364 // making the undefined library call.
7365 unsigned NullIndex = 0;
7366 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7367 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7368 break;
7369 }
7370
7371 return NullIndex + 1;
7372}
7373
7374/// If we can compute the length of the string pointed to by
7375/// the specified pointer, return 'len+1'. If we can't, return 0.
7376uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7377 if (!V->getType()->isPointerTy())
7378 return 0;
7379
7381 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7382 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7383 // an empty string as a length.
7384 return Len == ~0ULL ? 1 : Len;
7385}
7386
7387const Value *
7389 bool MustPreserveOffset,
7390 bool MustPreserveProvenance) {
7391 assert(Call &&
7392 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7393 if (const Value *RV = Call->getReturnedArgOperand())
7394 return RV;
7395 // This can be used only as a aliasing property.
7397 Call, MustPreserveOffset, MustPreserveProvenance))
7398 return Call->getArgOperand(0);
7399 return nullptr;
7400}
7401
7403 const CallBase *Call, bool MustPreserveOffset,
7404 bool MustPreserveProvenance) {
7405 switch (Call->getIntrinsicID()) {
7406 case Intrinsic::launder_invariant_group:
7407 case Intrinsic::aarch64_irg:
7408 case Intrinsic::aarch64_tagp:
7409 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7410 // input pointer (and thus preserves the byte offset, which is the property
7411 // the MustPreserveOffset flag selects). However, it will not necessarily
7412 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7413 // descriptor", which has "all loads return 0, all stores are dropped"
7414 // semantics. Given the context of this intrinsic list, no one should be
7415 // relying on such a strict bit-exact null mapping (and, at time of
7416 // writing, they are not), but we document this fact out of an abundance
7417 // of caution.
7418 case Intrinsic::amdgcn_make_buffer_rsrc:
7419 return !MustPreserveProvenance;
7420 case Intrinsic::ptrmask:
7421 return !MustPreserveOffset;
7422 case Intrinsic::threadlocal_address:
7423 // The underlying variable changes with thread ID. The Thread ID may change
7424 // at coroutine suspend points.
7425 return !Call->getParent()->getParent()->isPresplitCoroutine();
7426 default:
7427 return false;
7428 }
7429}
7430
7431/// \p PN defines a loop-variant pointer to an object. Check if the
7432/// previous iteration of the loop was referring to the same object as \p PN.
7434 const LoopInfo *LI) {
7435 // Find the loop-defined value.
7436 Loop *L = LI->getLoopFor(PN->getParent());
7437 if (PN->getNumIncomingValues() != 2)
7438 return true;
7439
7440 // Find the value from previous iteration.
7441 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7442 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7443 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7444 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7445 return true;
7446
7447 // If a new pointer is loaded in the loop, the pointer references a different
7448 // object in every iteration. E.g.:
7449 // for (i)
7450 // int *p = a[i];
7451 // ...
7452 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7453 if (!L->isLoopInvariant(Load->getPointerOperand()))
7454 return false;
7455 return true;
7456}
7457
7458const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup,
7459 bool MustPreserveProvenance) {
7460 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7461 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7462 const Value *PtrOp = GEP->getPointerOperand();
7463 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7464 return V;
7465 V = PtrOp;
7466 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7467 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7468 Value *NewV = cast<Operator>(V)->getOperand(0);
7469 if (!NewV->getType()->isPointerTy())
7470 return V;
7471 V = NewV;
7472 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7473 if (GA->isInterposable())
7474 return V;
7475 V = GA->getAliasee();
7476 } else {
7477 if (auto *PHI = dyn_cast<PHINode>(V)) {
7478 // Look through single-arg phi nodes created by LCSSA.
7479 if (PHI->getNumIncomingValues() == 1) {
7480 V = PHI->getIncomingValue(0);
7481 continue;
7482 }
7483 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7484 // CaptureTracking can know about special capturing properties of some
7485 // intrinsics like launder.invariant.group, that can't be expressed with
7486 // the attributes, but have properties like returning aliasing pointer.
7487 // Because some analysis may assume that nocaptured pointer is not
7488 // returned from some special intrinsic (because function would have to
7489 // be marked with returns attribute), it is crucial to use this function
7490 // because it should be in sync with CaptureTracking. Not using it may
7491 // cause weird miscompilations where 2 aliasing pointers are assumed to
7492 // noalias.
7494 Call, /*MustPreserveOffset=*/false, MustPreserveProvenance)) {
7495 V = RP;
7496 continue;
7497 }
7498 }
7499
7500 return V;
7501 }
7502 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7503 }
7504 return V;
7505}
7506
7509 const LoopInfo *LI, unsigned MaxLookup) {
7512 Worklist.push_back(V);
7513 do {
7514 const Value *P = Worklist.pop_back_val();
7515 P = getUnderlyingObject(P, MaxLookup);
7516
7517 if (!Visited.insert(P).second)
7518 continue;
7519
7520 if (auto *SI = dyn_cast<SelectInst>(P)) {
7521 Worklist.push_back(SI->getTrueValue());
7522 Worklist.push_back(SI->getFalseValue());
7523 continue;
7524 }
7525
7526 if (auto *PN = dyn_cast<PHINode>(P)) {
7527 // If this PHI changes the underlying object in every iteration of the
7528 // loop, don't look through it. Consider:
7529 // int **A;
7530 // for (i) {
7531 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7532 // Curr = A[i];
7533 // *Prev, *Curr;
7534 //
7535 // Prev is tracking Curr one iteration behind so they refer to different
7536 // underlying objects.
7537 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7539 append_range(Worklist, PN->incoming_values());
7540 else
7541 Objects.push_back(P);
7542 continue;
7543 }
7544
7545 Objects.push_back(P);
7546 } while (!Worklist.empty());
7547}
7548
7550 bool MustPreserveProvenance) {
7551 const unsigned MaxVisited = 8;
7552
7555 Worklist.push_back(V);
7556 const Value *Object = nullptr;
7557 // Used as fallback if we can't find a common underlying object through
7558 // recursion.
7559 bool First = true;
7560 const Value *FirstObject =
7561 getUnderlyingObject(V, MaxLookupSearchDepth, MustPreserveProvenance);
7562 do {
7563 const Value *P = Worklist.pop_back_val();
7564 P = First ? FirstObject
7566 MustPreserveProvenance);
7567 First = false;
7568
7569 if (!Visited.insert(P).second)
7570 continue;
7571
7572 if (Visited.size() == MaxVisited)
7573 return FirstObject;
7574
7575 if (auto *SI = dyn_cast<SelectInst>(P)) {
7576 Worklist.push_back(SI->getTrueValue());
7577 Worklist.push_back(SI->getFalseValue());
7578 continue;
7579 }
7580
7581 if (auto *PN = dyn_cast<PHINode>(P)) {
7582 append_range(Worklist, PN->incoming_values());
7583 continue;
7584 }
7585
7586 if (!Object)
7587 Object = P;
7588 else if (Object != P)
7589 return FirstObject;
7590 } while (!Worklist.empty());
7591
7592 return Object ? Object : FirstObject;
7593}
7594
7595/// This is the function that does the work of looking through basic
7596/// ptrtoint+arithmetic+inttoptr sequences.
7597static const Value *getUnderlyingObjectFromInt(const Value *V) {
7598 do {
7599 if (const Operator *U = dyn_cast<Operator>(V)) {
7600 // If we find a ptrtoint, we can transfer control back to the
7601 // regular getUnderlyingObjectFromInt.
7602 if (U->getOpcode() == Instruction::PtrToInt)
7603 return U->getOperand(0);
7604 // If we find an add of a constant, a multiplied value, or a phi, it's
7605 // likely that the other operand will lead us to the base
7606 // object. We don't have to worry about the case where the
7607 // object address is somehow being computed by the multiply,
7608 // because our callers only care when the result is an
7609 // identifiable object.
7610 if (U->getOpcode() != Instruction::Add ||
7611 (!isa<ConstantInt>(U->getOperand(1)) &&
7612 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7613 !isa<PHINode>(U->getOperand(1))))
7614 return V;
7615 V = U->getOperand(0);
7616 } else {
7617 return V;
7618 }
7619 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7620 } while (true);
7621}
7622
7623/// This is a wrapper around getUnderlyingObjects and adds support for basic
7624/// ptrtoint+arithmetic+inttoptr sequences.
7625/// It returns false if unidentified object is found in getUnderlyingObjects.
7627 SmallVectorImpl<Value *> &Objects) {
7629 SmallVector<const Value *, 4> Working(1, V);
7630 bool AllObjectsIdentified = true;
7631 do {
7632 V = Working.pop_back_val();
7633
7635 getUnderlyingObjects(V, Objs);
7636
7637 for (const Value *V : Objs) {
7638 if (!Visited.insert(V).second)
7639 continue;
7640 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7641 const Value *O =
7642 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7643 if (O->getType()->isPointerTy()) {
7644 Working.push_back(O);
7645 continue;
7646 }
7647 }
7648 AllObjectsIdentified &= isIdentifiedObject(V);
7649 Objects.push_back(const_cast<Value *>(V));
7650 }
7651 } while (!Working.empty());
7652 return AllObjectsIdentified;
7653}
7654
7656 AllocaInst *Result = nullptr;
7658 SmallVector<Value *, 4> Worklist;
7659
7660 auto AddWork = [&](Value *V) {
7661 if (Visited.insert(V).second)
7662 Worklist.push_back(V);
7663 };
7664
7665 AddWork(V);
7666 do {
7667 V = Worklist.pop_back_val();
7668 assert(Visited.count(V));
7669
7670 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7671 if (Result && Result != AI)
7672 return nullptr;
7673 Result = AI;
7674 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7675 AddWork(CI->getOperand(0));
7676 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7677 for (Value *IncValue : PN->incoming_values())
7678 AddWork(IncValue);
7679 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7680 AddWork(SI->getTrueValue());
7681 AddWork(SI->getFalseValue());
7683 if (OffsetZero && !GEP->hasAllZeroIndices())
7684 return nullptr;
7685 AddWork(GEP->getPointerOperand());
7686 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7687 Value *Returned = CB->getReturnedArgOperand();
7688 if (Returned)
7689 AddWork(Returned);
7690 else
7691 return nullptr;
7692 } else {
7693 return nullptr;
7694 }
7695 } while (!Worklist.empty());
7696
7697 return Result;
7698}
7699
7701 if (auto *II = dyn_cast<IntrinsicInst>(I))
7702 return isTriviallyVectorizable(II->getIntrinsicID());
7703 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7704 return (!Shuffle || Shuffle->isSelect()) &&
7706}
7707
7709 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7710 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7711 bool IgnoreUBImplyingAttrs) {
7712 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7713 AC, DT, TLI, UseVariableInfo,
7714 IgnoreUBImplyingAttrs);
7715}
7716
7718 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7719 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7720 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7721#ifndef NDEBUG
7722 if (Inst->getOpcode() != Opcode) {
7723 // Check that the operands are actually compatible with the Opcode override.
7724 auto hasEqualReturnAndLeadingOperandTypes =
7725 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7726 if (Inst->getNumOperands() < NumLeadingOperands)
7727 return false;
7728 const Type *ExpectedType = Inst->getType();
7729 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7730 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7731 return false;
7732 return true;
7733 };
7735 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7736 assert(!Instruction::isUnaryOp(Opcode) ||
7737 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7738 }
7739#endif
7740
7741 switch (Opcode) {
7742 default:
7743 return true;
7744 case Instruction::UDiv:
7745 case Instruction::URem: {
7746 // x / y is undefined if y == 0.
7747 const APInt *V;
7748 if (match(Inst->getOperand(1), m_APInt(V)))
7749 return *V != 0;
7750 return false;
7751 }
7752 case Instruction::SDiv:
7753 case Instruction::SRem: {
7754 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7755 const APInt *Numerator, *Denominator;
7756 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7757 return false;
7758 // We cannot hoist this division if the denominator is 0.
7759 if (*Denominator == 0)
7760 return false;
7761 // It's safe to hoist if the denominator is not 0 or -1.
7762 if (!Denominator->isAllOnes())
7763 return true;
7764 // At this point we know that the denominator is -1. It is safe to hoist as
7765 // long we know that the numerator is not INT_MIN.
7766 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7767 return !Numerator->isMinSignedValue();
7768 // The numerator *might* be MinSignedValue.
7769 return false;
7770 }
7771 case Instruction::Load: {
7772 if (!UseVariableInfo)
7773 return false;
7774
7775 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7776 if (!LI)
7777 return false;
7778 if (mustSuppressSpeculation(*LI))
7779 return false;
7780 const DataLayout &DL = LI->getDataLayout();
7782 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7783 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7784 }
7785 case Instruction::Call: {
7786 auto *CI = dyn_cast<const CallInst>(Inst);
7787 if (!CI)
7788 return false;
7789 const Function *Callee = CI->getCalledFunction();
7790
7791 // The called function could have undefined behavior or side-effects, even
7792 // if marked readnone nounwind.
7793 if (!Callee || !Callee->isSpeculatable())
7794 return false;
7795 // Since the operands may be changed after hoisting, undefined behavior may
7796 // be triggered by some UB-implying attributes.
7797 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7798 }
7799 case Instruction::VAArg:
7800 case Instruction::Alloca:
7801 case Instruction::Invoke:
7802 case Instruction::CallBr:
7803 case Instruction::PHI:
7804 case Instruction::Store:
7805 case Instruction::Ret:
7806 case Instruction::UncondBr:
7807 case Instruction::CondBr:
7808 case Instruction::IndirectBr:
7809 case Instruction::Switch:
7810 case Instruction::Unreachable:
7811 case Instruction::Fence:
7812 case Instruction::AtomicRMW:
7813 case Instruction::AtomicCmpXchg:
7814 case Instruction::LandingPad:
7815 case Instruction::Resume:
7816 case Instruction::CatchSwitch:
7817 case Instruction::CatchPad:
7818 case Instruction::CatchRet:
7819 case Instruction::CleanupPad:
7820 case Instruction::CleanupRet:
7821 return false; // Misc instructions which have effects
7822 }
7823}
7824
7826 if (I.mayReadOrWriteMemory())
7827 // Memory dependency possible
7828 return true;
7830 // Can't move above a maythrow call or infinite loop. Or if an
7831 // inalloca alloca, above a stacksave call.
7832 return true;
7834 // 1) Can't reorder two inf-loop calls, even if readonly
7835 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7836 // safe to speculative execute. (Inverse of above)
7837 return true;
7838 return false;
7839}
7840
7841/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7855
7856/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7859 bool ForSigned,
7860 const SimplifyQuery &SQ) {
7861 ConstantRange CR1 =
7862 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7863 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7866 return CR1.intersectWith(CR2, RangeType);
7867}
7868
7870 const Value *RHS,
7871 const SimplifyQuery &SQ,
7872 bool IsNSW) {
7873 ConstantRange LHSRange =
7874 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7875 ConstantRange RHSRange =
7876 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7877
7878 // mul nsw of two non-negative numbers is also nuw.
7879 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7881
7882 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7883}
7884
7886 const Value *RHS,
7887 const SimplifyQuery &SQ) {
7888 // Multiplying n * m significant bits yields a result of n + m significant
7889 // bits. If the total number of significant bits does not exceed the
7890 // result bit width (minus 1), there is no overflow.
7891 // This means if we have enough leading sign bits in the operands
7892 // we can guarantee that the result does not overflow.
7893 // Ref: "Hacker's Delight" by Henry Warren
7894 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7895
7896 // Note that underestimating the number of sign bits gives a more
7897 // conservative answer.
7898 unsigned SignBits =
7899 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7900
7901 // First handle the easy case: if we have enough sign bits there's
7902 // definitely no overflow.
7903 if (SignBits > BitWidth + 1)
7905
7906 // There are two ambiguous cases where there can be no overflow:
7907 // SignBits == BitWidth + 1 and
7908 // SignBits == BitWidth
7909 // The second case is difficult to check, therefore we only handle the
7910 // first case.
7911 if (SignBits == BitWidth + 1) {
7912 // It overflows only when both arguments are negative and the true
7913 // product is exactly the minimum negative number.
7914 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7915 // For simplicity we just check if at least one side is not negative.
7916 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7917 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7918 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7920 }
7922}
7923
7926 const WithCache<const Value *> &RHS,
7927 const SimplifyQuery &SQ) {
7928 ConstantRange LHSRange =
7929 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7930 ConstantRange RHSRange =
7931 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7932 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7933}
7934
7935static OverflowResult
7938 const AddOperator *Add, const SimplifyQuery &SQ) {
7939 if (Add && Add->hasNoSignedWrap()) {
7941 }
7942
7943 // If LHS and RHS each have at least two sign bits, the addition will look
7944 // like
7945 //
7946 // XX..... +
7947 // YY.....
7948 //
7949 // If the carry into the most significant position is 0, X and Y can't both
7950 // be 1 and therefore the carry out of the addition is also 0.
7951 //
7952 // If the carry into the most significant position is 1, X and Y can't both
7953 // be 0 and therefore the carry out of the addition is also 1.
7954 //
7955 // Since the carry into the most significant position is always equal to
7956 // the carry out of the addition, there is no signed overflow.
7957 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7959
7960 ConstantRange LHSRange =
7961 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7962 ConstantRange RHSRange =
7963 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7964 OverflowResult OR =
7965 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7967 return OR;
7968
7969 // The remaining code needs Add to be available. Early returns if not so.
7970 if (!Add)
7972
7973 // If the sign of Add is the same as at least one of the operands, this add
7974 // CANNOT overflow. If this can be determined from the known bits of the
7975 // operands the above signedAddMayOverflow() check will have already done so.
7976 // The only other way to improve on the known bits is from an assumption, so
7977 // call computeKnownBitsFromContext() directly.
7978 bool LHSOrRHSKnownNonNegative =
7979 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7980 bool LHSOrRHSKnownNegative =
7981 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7982 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7983 KnownBits AddKnown(LHSRange.getBitWidth());
7984 computeKnownBitsFromContext(Add, AddKnown, SQ);
7985 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7986 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7988 }
7989
7991}
7992
7994 const Value *RHS,
7995 const SimplifyQuery &SQ) {
7996 // X - (X % ?)
7997 // The remainder of a value can't have greater magnitude than itself,
7998 // so the subtraction can't overflow.
7999
8000 // X - (X -nuw ?)
8001 // In the minimal case, this would simplify to "?", so there's no subtract
8002 // at all. But if this analysis is used to peek through casts, for example,
8003 // then determining no-overflow may allow other transforms.
8004
8005 // TODO: There are other patterns like this.
8006 // See simplifyICmpWithBinOpOnLHS() for candidates.
8007 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
8008 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
8009 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8011
8012 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CtxI,
8013 SQ.DL)) {
8014 if (*C)
8017 }
8018
8019 ConstantRange LHSRange =
8020 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
8021 ConstantRange RHSRange =
8022 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
8023 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
8024}
8025
8027 const Value *RHS,
8028 const SimplifyQuery &SQ) {
8029 // X - (X % ?)
8030 // The remainder of a value can't have greater magnitude than itself,
8031 // so the subtraction can't overflow.
8032
8033 // X - (X -nsw ?)
8034 // In the minimal case, this would simplify to "?", so there's no subtract
8035 // at all. But if this analysis is used to peek through casts, for example,
8036 // then determining no-overflow may allow other transforms.
8037 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
8038 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
8039 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CtxI, SQ.DT))
8041
8042 // If LHS and RHS each have at least two sign bits, the subtraction
8043 // cannot overflow.
8044 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
8046
8047 ConstantRange LHSRange =
8048 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
8049 ConstantRange RHSRange =
8050 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
8051 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
8052}
8053
8055 const DominatorTree &DT) {
8056 SmallVector<const CondBrInst *, 2> GuardingBranches;
8058
8059 for (const User *U : WO->users()) {
8060 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
8061 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
8062
8063 if (EVI->getIndices()[0] == 0)
8064 Results.push_back(EVI);
8065 else {
8066 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
8067
8068 for (const auto *U : EVI->users())
8069 if (const auto *B = dyn_cast<CondBrInst>(U))
8070 GuardingBranches.push_back(B);
8071 }
8072 } else {
8073 // We are using the aggregate directly in a way we don't want to analyze
8074 // here (storing it to a global, say).
8075 return false;
8076 }
8077 }
8078
8079 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
8080 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
8081
8082 // Check if all users of the add are provably no-wrap.
8083 for (const auto *Result : Results) {
8084 // If the extractvalue itself is not executed on overflow, the we don't
8085 // need to check each use separately, since domination is transitive.
8086 if (DT.dominates(NoWrapEdge, Result->getParent()))
8087 continue;
8088
8089 for (const auto &RU : Result->uses())
8090 if (!DT.dominates(NoWrapEdge, RU))
8091 return false;
8092 }
8093
8094 return true;
8095 };
8096
8097 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
8098}
8099
8100/// Shifts return poison if shiftwidth is larger than the bitwidth.
8101static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
8102 auto *C = dyn_cast<Constant>(ShiftAmount);
8103 if (!C)
8104 return false;
8105
8106 // Shifts return poison if shiftwidth is larger than the bitwidth.
8108 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
8109 unsigned NumElts = FVTy->getNumElements();
8110 for (unsigned i = 0; i < NumElts; ++i)
8111 ShiftAmounts.push_back(C->getAggregateElement(i));
8112 } else if (isa<ScalableVectorType>(C->getType()))
8113 return false; // Can't tell, just return false to be safe
8114 else
8115 ShiftAmounts.push_back(C);
8116
8117 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
8118 auto *CI = dyn_cast_or_null<ConstantInt>(C);
8119 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
8120 });
8121
8122 return Safe;
8123}
8124
8126 bool ConsiderFlagsAndMetadata) {
8127
8128 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
8129 Op->hasPoisonGeneratingAnnotations())
8130 return true;
8131
8132 unsigned Opcode = Op->getOpcode();
8133
8134 // Check whether opcode is a poison/undef-generating operation
8135 switch (Opcode) {
8136 case Instruction::Shl:
8137 case Instruction::AShr:
8138 case Instruction::LShr:
8139 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
8140 case Instruction::FPToSI:
8141 case Instruction::FPToUI:
8142 // fptosi/ui yields poison if the resulting value does not fit in the
8143 // destination type.
8144 return true;
8145 case Instruction::Call:
8146 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
8147 switch (II->getIntrinsicID()) {
8148 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
8149 case Intrinsic::ctlz:
8150 case Intrinsic::cttz:
8151 case Intrinsic::abs:
8152 // We're not considering flags so it is safe to just return false.
8153 return false;
8154 case Intrinsic::sshl_sat:
8155 case Intrinsic::ushl_sat:
8156 if (!includesPoison(Kind) ||
8157 shiftAmountKnownInRange(II->getArgOperand(1)))
8158 return false;
8159 break;
8160 }
8161 }
8162 [[fallthrough]];
8163 case Instruction::CallBr:
8164 case Instruction::Invoke: {
8165 const auto *CB = cast<CallBase>(Op);
8166 return !CB->hasRetAttr(Attribute::NoUndef) &&
8167 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
8168 }
8169 case Instruction::InsertElement:
8170 case Instruction::ExtractElement: {
8171 // If index exceeds the length of the vector, it returns poison
8172 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
8173 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
8174 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
8175 if (includesPoison(Kind))
8176 return !Idx ||
8177 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
8178 return false;
8179 }
8180 case Instruction::ShuffleVector: {
8182 ? cast<ConstantExpr>(Op)->getShuffleMask()
8183 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
8184 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
8185 }
8186 case Instruction::FNeg:
8187 case Instruction::PHI:
8188 case Instruction::Select:
8189 case Instruction::ExtractValue:
8190 case Instruction::InsertValue:
8191 case Instruction::Freeze:
8192 case Instruction::ICmp:
8193 case Instruction::FCmp:
8194 case Instruction::GetElementPtr:
8195 return false;
8196 case Instruction::AddrSpaceCast:
8197 return true;
8198 default: {
8199 const auto *CE = dyn_cast<ConstantExpr>(Op);
8200 if (isa<CastInst>(Op) || (CE && CE->isCast()))
8201 return false;
8202 else if (Instruction::isBinaryOp(Opcode))
8203 return false;
8204 // Be conservative and return true.
8205 return true;
8206 }
8207 }
8208}
8209
8211 bool ConsiderFlagsAndMetadata) {
8212 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
8213 ConsiderFlagsAndMetadata);
8214}
8215
8216bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
8217 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
8218 ConsiderFlagsAndMetadata);
8219}
8220
8221static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
8222 unsigned Depth) {
8223 if (ValAssumedPoison == V)
8224 return true;
8225
8226 const unsigned MaxDepth = 2;
8227 if (Depth >= MaxDepth)
8228 return false;
8229
8230 if (const auto *I = dyn_cast<Instruction>(V)) {
8231 if (any_of(I->operands(), [=](const Use &Op) {
8232 return propagatesPoison(Op) &&
8233 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
8234 }))
8235 return true;
8236
8237 // V = extractvalue V0, idx
8238 // V2 = extractvalue V0, idx2
8239 // V0's elements are all poison or not. (e.g., add_with_overflow)
8240 const WithOverflowInst *II;
8242 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
8243 llvm::is_contained(II->args(), ValAssumedPoison)))
8244 return true;
8245 }
8246 return false;
8247}
8248
8249static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
8250 unsigned Depth) {
8251 if (isGuaranteedNotToBePoison(ValAssumedPoison))
8252 return true;
8253
8254 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
8255 return true;
8256
8257 const unsigned MaxDepth = 2;
8258 if (Depth >= MaxDepth)
8259 return false;
8260
8261 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
8262 if (I && !canCreatePoison(cast<Operator>(I))) {
8263 return all_of(I->operands(), [=](const Value *Op) {
8264 return impliesPoison(Op, V, Depth + 1);
8265 });
8266 }
8267 return false;
8268}
8269
8270bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
8271 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
8272}
8273
8274static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
8275
8277 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8278 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8280 return false;
8281
8282 if (isa<MetadataAsValue>(V))
8283 return false;
8284
8285 if (const auto *A = dyn_cast<Argument>(V)) {
8286 if (A->hasAttribute(Attribute::NoUndef) ||
8287 A->hasAttribute(Attribute::Dereferenceable) ||
8288 A->hasAttribute(Attribute::DereferenceableOrNull))
8289 return true;
8290 }
8291
8292 if (auto *C = dyn_cast<Constant>(V)) {
8293 if (isa<PoisonValue>(C))
8294 return !includesPoison(Kind);
8295
8296 if (isa<UndefValue>(C))
8297 return !includesUndef(Kind);
8298
8301 return true;
8302
8303 if (C->getType()->isVectorTy() || C->getType()->isAggregateType()) {
8304 if (isa<ConstantExpr>(C)) {
8305 // Scalable vectors can use a ConstantExpr to build a splat.
8306 if (Constant *SplatC = C->getSplatValue())
8307 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8308 return true;
8309 } else if (auto *CA = dyn_cast<ConstantAggregate>(C)) {
8310 return all_of(CA->operands(), [&](const Use &Op) {
8311 return isGuaranteedNotToBeUndefOrPoison(Op.get(), AC, CtxI, DT,
8312 Depth + 1, Kind);
8313 });
8314 }
8315 }
8316 }
8317
8318 // Strip cast operations from a pointer value.
8319 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8320 // inbounds with zero offset. To guarantee that the result isn't poison, the
8321 // stripped pointer is checked as it has to be pointing into an allocated
8322 // object or be null `null` to ensure `inbounds` getelement pointers with a
8323 // zero offset could not produce poison.
8324 // It can strip off addrspacecast that do not change bit representation as
8325 // well. We believe that such addrspacecast is equivalent to no-op.
8326 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8327 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8328 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8329 return true;
8330
8331 auto OpCheck = [&](const Value *V) {
8332 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8333 };
8334
8335 if (auto *Opr = dyn_cast<Operator>(V)) {
8336 // If the value is a freeze instruction, then it can never
8337 // be undef or poison.
8338 if (isa<FreezeInst>(V))
8339 return true;
8340
8341 if (const auto *CB = dyn_cast<CallBase>(V)) {
8342 if (CB->hasRetAttr(Attribute::NoUndef) ||
8343 CB->hasRetAttr(Attribute::Dereferenceable) ||
8344 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8345 return true;
8346 }
8347
8348 if (!::canCreateUndefOrPoison(Opr, Kind,
8349 /*ConsiderFlagsAndMetadata=*/true)) {
8350 if (const auto *PN = dyn_cast<PHINode>(V)) {
8351 unsigned Num = PN->getNumIncomingValues();
8352 bool IsWellDefined = true;
8353 for (unsigned i = 0; i < Num; ++i) {
8354 if (PN == PN->getIncomingValue(i))
8355 continue;
8356 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8357 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8358 DT, Depth + 1, Kind)) {
8359 IsWellDefined = false;
8360 break;
8361 }
8362 }
8363 if (IsWellDefined)
8364 return true;
8365 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8366 : nullptr) {
8367 // For splats we only need to check the value being splatted.
8368 if (OpCheck(Splat))
8369 return true;
8370 } else if (all_of(Opr->operands(), OpCheck))
8371 return true;
8372 }
8373 }
8374
8375 if (auto *I = dyn_cast<LoadInst>(V))
8376 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8377 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8378 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8379 return true;
8380
8382 return true;
8383
8384 // CtxI may be null or a cloned instruction.
8385 if (!CtxI || !CtxI->getParent() || !DT)
8386 return false;
8387
8388 auto *DNode = DT->getNode(CtxI->getParent());
8389 if (!DNode)
8390 // Unreachable block
8391 return false;
8392
8393 // If V is used as a branch condition before reaching CtxI, V cannot be
8394 // undef or poison.
8395 // br V, BB1, BB2
8396 // BB1:
8397 // CtxI ; V cannot be undef or poison here
8398 auto *Dominator = DNode->getIDom();
8399 // This check is purely for compile time reasons: we can skip the IDom walk
8400 // if what we are checking for includes undef and the value is not an integer.
8401 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8402 while (Dominator) {
8403 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8404
8405 Value *Cond = nullptr;
8406 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8407 Cond = BI->getCondition();
8408 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8409 Cond = SI->getCondition();
8410 }
8411
8412 if (Cond) {
8413 if (Cond == V)
8414 return true;
8415 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8416 // For poison, we can analyze further
8417 auto *Opr = cast<Operator>(Cond);
8418 if (any_of(Opr->operands(), [V](const Use &U) {
8419 return V == U && propagatesPoison(U);
8420 }))
8421 return true;
8422 }
8423 }
8424
8425 Dominator = Dominator->getIDom();
8426 }
8427
8428 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8429 return true;
8430
8431 return false;
8432}
8433
8435 const Instruction *CtxI,
8436 const DominatorTree *DT,
8437 unsigned Depth) {
8438 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8440}
8441
8443 const Instruction *CtxI,
8444 const DominatorTree *DT, unsigned Depth) {
8445 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8447}
8448
8450 const Instruction *CtxI,
8451 const DominatorTree *DT, unsigned Depth) {
8452 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8454}
8455
8456/// Return true if undefined behavior would provably be executed on the path to
8457/// OnPathTo if Root produced a posion result. Note that this doesn't say
8458/// anything about whether OnPathTo is actually executed or whether Root is
8459/// actually poison. This can be used to assess whether a new use of Root can
8460/// be added at a location which is control equivalent with OnPathTo (such as
8461/// immediately before it) without introducing UB which didn't previously
8462/// exist. Note that a false result conveys no information.
8464 Instruction *OnPathTo,
8465 DominatorTree *DT) {
8466 // Basic approach is to assume Root is poison, propagate poison forward
8467 // through all users we can easily track, and then check whether any of those
8468 // users are provable UB and must execute before out exiting block might
8469 // exit.
8470
8471 // The set of all recursive users we've visited (which are assumed to all be
8472 // poison because of said visit)
8475 Worklist.push_back(Root);
8476 while (!Worklist.empty()) {
8477 const Instruction *I = Worklist.pop_back_val();
8478
8479 // If we know this must trigger UB on a path leading our target.
8480 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8481 return true;
8482
8483 // If we can't analyze propagation through this instruction, just skip it
8484 // and transitive users. Safe as false is a conservative result.
8485 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8486 return KnownPoison.contains(U) && propagatesPoison(U);
8487 }))
8488 continue;
8489
8490 if (KnownPoison.insert(I).second)
8491 for (const User *User : I->users())
8492 Worklist.push_back(cast<Instruction>(User));
8493 }
8494
8495 // Might be non-UB, or might have a path we couldn't prove must execute on
8496 // way to exiting bb.
8497 return false;
8498}
8499
8501 const SimplifyQuery &SQ) {
8502 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8503 Add, SQ);
8504}
8505
8508 const WithCache<const Value *> &RHS,
8509 const SimplifyQuery &SQ) {
8510 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8511}
8512
8514 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8515 // of time because it's possible for another thread to interfere with it for an
8516 // arbitrary length of time, but programs aren't allowed to rely on that.
8517
8518 // If there is no successor, then execution can't transfer to it.
8519 if (isa<ReturnInst>(I))
8520 return false;
8522 return false;
8523
8524 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8525 // Instruction::willReturn.
8526 //
8527 // FIXME: Move this check into Instruction::willReturn.
8528 if (isa<CatchPadInst>(I)) {
8529 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8530 default:
8531 // A catchpad may invoke exception object constructors and such, which
8532 // in some languages can be arbitrary code, so be conservative by default.
8533 return false;
8535 // For CoreCLR, it just involves a type test.
8536 return true;
8537 }
8538 }
8539
8540 // An instruction that returns without throwing must transfer control flow
8541 // to a successor.
8542 return !I->mayThrow() && I->willReturn();
8543}
8544
8546 // TODO: This is slightly conservative for invoke instruction since exiting
8547 // via an exception *is* normal control for them.
8548 for (const Instruction &I : *BB)
8550 return false;
8551 return true;
8552}
8553
8560
8563 assert(ScanLimit && "scan limit must be non-zero");
8564 for (const Instruction &I : Range) {
8565 if (--ScanLimit == 0)
8566 return false;
8568 return false;
8569 }
8570 return true;
8571}
8572
8574 const Loop *L) {
8575 // The loop header is guaranteed to be executed for every iteration.
8576 //
8577 // FIXME: Relax this constraint to cover all basic blocks that are
8578 // guaranteed to be executed at every iteration.
8579 if (I->getParent() != L->getHeader()) return false;
8580
8581 for (const Instruction &LI : *L->getHeader()) {
8582 if (&LI == I) return true;
8583 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8584 }
8585 llvm_unreachable("Instruction not contained in its own parent basic block.");
8586}
8587
8589 switch (IID) {
8590 // TODO: Add more intrinsics.
8591 case Intrinsic::sadd_with_overflow:
8592 case Intrinsic::ssub_with_overflow:
8593 case Intrinsic::smul_with_overflow:
8594 case Intrinsic::uadd_with_overflow:
8595 case Intrinsic::usub_with_overflow:
8596 case Intrinsic::umul_with_overflow:
8597 // If an input is a vector containing a poison element, the
8598 // two output vectors (calculated results, overflow bits)'
8599 // corresponding lanes are poison.
8600 return true;
8601 case Intrinsic::ctpop:
8602 case Intrinsic::ctlz:
8603 case Intrinsic::cttz:
8604 case Intrinsic::abs:
8605 case Intrinsic::smax:
8606 case Intrinsic::smin:
8607 case Intrinsic::umax:
8608 case Intrinsic::umin:
8609 case Intrinsic::scmp:
8610 case Intrinsic::smulh:
8611 case Intrinsic::umulh:
8612 case Intrinsic::is_fpclass:
8613 case Intrinsic::ptrmask:
8614 case Intrinsic::ucmp:
8615 case Intrinsic::bitreverse:
8616 case Intrinsic::bswap:
8617 case Intrinsic::sadd_sat:
8618 case Intrinsic::ssub_sat:
8619 case Intrinsic::sshl_sat:
8620 case Intrinsic::uadd_sat:
8621 case Intrinsic::usub_sat:
8622 case Intrinsic::ushl_sat:
8623 case Intrinsic::smul_fix:
8624 case Intrinsic::smul_fix_sat:
8625 case Intrinsic::umul_fix:
8626 case Intrinsic::umul_fix_sat:
8627 case Intrinsic::pow:
8628 case Intrinsic::powi:
8629 case Intrinsic::sin:
8630 case Intrinsic::sinh:
8631 case Intrinsic::cos:
8632 case Intrinsic::cosh:
8633 case Intrinsic::sincos:
8634 case Intrinsic::sincospi:
8635 case Intrinsic::tan:
8636 case Intrinsic::tanh:
8637 case Intrinsic::asin:
8638 case Intrinsic::acos:
8639 case Intrinsic::atan:
8640 case Intrinsic::atan2:
8641 case Intrinsic::canonicalize:
8642 case Intrinsic::sqrt:
8643 case Intrinsic::fma:
8644 case Intrinsic::fmuladd:
8645 case Intrinsic::exp:
8646 case Intrinsic::exp2:
8647 case Intrinsic::exp10:
8648 case Intrinsic::log:
8649 case Intrinsic::log2:
8650 case Intrinsic::log10:
8651 case Intrinsic::modf:
8652 case Intrinsic::floor:
8653 case Intrinsic::ceil:
8654 case Intrinsic::trunc:
8655 case Intrinsic::rint:
8656 case Intrinsic::nearbyint:
8657 case Intrinsic::round:
8658 case Intrinsic::roundeven:
8659 case Intrinsic::lrint:
8660 case Intrinsic::llrint:
8661 case Intrinsic::fshl:
8662 case Intrinsic::fshr:
8663 case Intrinsic::frexp:
8664 case Intrinsic::get_active_lane_mask:
8665 case Intrinsic::mask_beforefirst:
8666 return true;
8667 default:
8668 return false;
8669 }
8670}
8671
8672bool llvm::propagatesPoison(const Use &PoisonOp) {
8673 const Operator *I = cast<Operator>(PoisonOp.getUser());
8674 switch (I->getOpcode()) {
8675 case Instruction::Freeze:
8676 case Instruction::PHI:
8677 case Instruction::Invoke:
8678 return false;
8679 case Instruction::Select:
8680 return PoisonOp.getOperandNo() == 0;
8681 case Instruction::Call:
8682 if (auto *II = dyn_cast<IntrinsicInst>(I))
8683 return intrinsicPropagatesPoison(II->getIntrinsicID());
8684 return false;
8685 case Instruction::ICmp:
8686 case Instruction::FCmp:
8687 case Instruction::GetElementPtr:
8688 return true;
8689 default:
8691 return true;
8692
8693 // Be conservative and return false.
8694 return false;
8695 }
8696}
8697
8698/// Enumerates all operands of \p I that are guaranteed to not be undef or
8699/// poison. If the callback \p Handle returns true, stop processing and return
8700/// true. Otherwise, return false.
8701template <typename CallableT>
8703 const CallableT &Handle) {
8704 switch (I->getOpcode()) {
8705 case Instruction::Store:
8706 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8707 return true;
8708 break;
8709
8710 case Instruction::Load:
8711 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8712 return true;
8713 break;
8714
8715 // Since dereferenceable attribute imply noundef, atomic operations
8716 // also implicitly have noundef pointers too
8717 case Instruction::AtomicCmpXchg:
8719 return true;
8720 break;
8721
8722 case Instruction::AtomicRMW:
8723 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8724 return true;
8725 break;
8726
8727 case Instruction::Call:
8728 case Instruction::Invoke: {
8729 const CallBase *CB = cast<CallBase>(I);
8730 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8731 return true;
8732 for (unsigned i = 0; i < CB->arg_size(); ++i)
8733 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8734 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8735 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8736 Handle(CB->getArgOperand(i)))
8737 return true;
8738 break;
8739 }
8740 case Instruction::Ret:
8741 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8742 Handle(I->getOperand(0)))
8743 return true;
8744 break;
8745 case Instruction::Switch:
8746 if (Handle(cast<SwitchInst>(I)->getCondition()))
8747 return true;
8748 break;
8749 case Instruction::CondBr:
8750 if (Handle(cast<CondBrInst>(I)->getCondition()))
8751 return true;
8752 break;
8753 default:
8754 break;
8755 }
8756
8757 return false;
8758}
8759
8760/// Enumerates all operands of \p I that are guaranteed to not be poison.
8761template <typename CallableT>
8763 const CallableT &Handle) {
8764 if (handleGuaranteedWellDefinedOps(I, Handle))
8765 return true;
8766 switch (I->getOpcode()) {
8767 // Divisors of these operations are allowed to be partially undef.
8768 case Instruction::UDiv:
8769 case Instruction::SDiv:
8770 case Instruction::URem:
8771 case Instruction::SRem:
8772 return Handle(I->getOperand(1));
8773 default:
8774 return false;
8775 }
8776}
8777
8779 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8781 I, [&](const Value *V) { return KnownPoison.count(V); });
8782}
8783
8785 bool PoisonOnly) {
8786 // We currently only look for uses of values within the same basic
8787 // block, as that makes it easier to guarantee that the uses will be
8788 // executed given that Inst is executed.
8789 //
8790 // FIXME: Expand this to consider uses beyond the same basic block. To do
8791 // this, look out for the distinction between post-dominance and strong
8792 // post-dominance.
8793 const BasicBlock *BB = nullptr;
8795 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8796 BB = Inst->getParent();
8797 Begin = Inst->getIterator();
8798 Begin++;
8799 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8800 if (Arg->getParent()->isDeclaration())
8801 return false;
8802 BB = &Arg->getParent()->getEntryBlock();
8803 Begin = BB->begin();
8804 } else {
8805 return false;
8806 }
8807
8808 // Limit number of instructions we look at, to avoid scanning through large
8809 // blocks. The current limit is chosen arbitrarily.
8810 unsigned ScanLimit = 32;
8812
8813 if (!PoisonOnly) {
8814 // Since undef does not propagate eagerly, be conservative & just check
8815 // whether a value is directly passed to an instruction that must take
8816 // well-defined operands.
8817
8818 for (const auto &I : make_range(Begin, End)) {
8819 if (--ScanLimit == 0)
8820 break;
8821
8822 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8823 return WellDefinedOp == V;
8824 }))
8825 return true;
8826
8828 break;
8829 }
8830 return false;
8831 }
8832
8833 // Set of instructions that we have proved will yield poison if Inst
8834 // does.
8835 SmallPtrSet<const Value *, 16> YieldsPoison;
8837
8838 YieldsPoison.insert(V);
8839 Visited.insert(BB);
8840
8841 while (true) {
8842 for (const auto &I : make_range(Begin, End)) {
8843 if (--ScanLimit == 0)
8844 return false;
8845 if (mustTriggerUB(&I, YieldsPoison))
8846 return true;
8848 return false;
8849
8850 // If an operand is poison and propagates it, mark I as yielding poison.
8851 for (const Use &Op : I.operands()) {
8852 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8853 YieldsPoison.insert(&I);
8854 break;
8855 }
8856 }
8857
8858 // Special handling for select, which returns poison if its operand 0 is
8859 // poison (handled in the loop above) *or* if both its true/false operands
8860 // are poison (handled here).
8861 if (I.getOpcode() == Instruction::Select &&
8862 YieldsPoison.count(I.getOperand(1)) &&
8863 YieldsPoison.count(I.getOperand(2))) {
8864 YieldsPoison.insert(&I);
8865 }
8866 }
8867
8868 BB = BB->getSingleSuccessor();
8869 if (!BB || !Visited.insert(BB).second)
8870 break;
8871
8872 Begin = BB->getFirstNonPHIIt();
8873 End = BB->end();
8874 }
8875 return false;
8876}
8877
8879 return ::programUndefinedIfUndefOrPoison(Inst, false);
8880}
8881
8883 return ::programUndefinedIfUndefOrPoison(Inst, true);
8884}
8885
8886static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8887 if (FMF.noNaNs())
8888 return true;
8889
8890 if (auto *C = dyn_cast<ConstantFP>(V))
8891 return !C->isNaN();
8892
8893 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8894 if (!C->getElementType()->isFloatingPointTy())
8895 return false;
8896 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8897 if (C->getElementAsAPFloat(I).isNaN())
8898 return false;
8899 }
8900 return true;
8901 }
8902
8904 return true;
8905
8906 return false;
8907}
8908
8909static bool isKnownNonZero(const Value *V) {
8910 if (auto *C = dyn_cast<ConstantFP>(V))
8911 return !C->isZero();
8912
8913 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8914 if (!C->getElementType()->isFloatingPointTy())
8915 return false;
8916 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8917 if (C->getElementAsAPFloat(I).isZero())
8918 return false;
8919 }
8920 return true;
8921 }
8922
8923 return false;
8924}
8925
8926/// Match clamp pattern for float types without care about NaNs or signed zeros.
8927/// Given non-min/max outer cmp/select from the clamp pattern this
8928/// function recognizes if it can be substitued by a "canonical" min/max
8929/// pattern.
8931 Value *CmpLHS, Value *CmpRHS,
8932 Value *TrueVal, Value *FalseVal,
8933 Value *&LHS, Value *&RHS) {
8934 // Try to match
8935 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8936 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8937 // and return description of the outer Max/Min.
8938
8939 // First, check if select has inverse order:
8940 if (CmpRHS == FalseVal) {
8941 std::swap(TrueVal, FalseVal);
8942 Pred = CmpInst::getInversePredicate(Pred);
8943 }
8944
8945 // Assume success now. If there's no match, callers should not use these anyway.
8946 LHS = TrueVal;
8947 RHS = FalseVal;
8948
8949 const APFloat *FC1;
8950 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8951 return {SPF_UNKNOWN, SPNB_NA, false};
8952
8953 const APFloat *FC2;
8954 switch (Pred) {
8955 case CmpInst::FCMP_OLT:
8956 case CmpInst::FCMP_OLE:
8957 case CmpInst::FCMP_ULT:
8958 case CmpInst::FCMP_ULE:
8959 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8960 *FC1 < *FC2)
8961 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8962 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8963 *FC1 < *FC2)
8964 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8965 break;
8966 case CmpInst::FCMP_OGT:
8967 case CmpInst::FCMP_OGE:
8968 case CmpInst::FCMP_UGT:
8969 case CmpInst::FCMP_UGE:
8970 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8971 *FC1 > *FC2)
8972 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8973 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8974 *FC1 > *FC2)
8975 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8976 break;
8977 default:
8978 break;
8979 }
8980
8981 return {SPF_UNKNOWN, SPNB_NA, false};
8982}
8983
8984/// Recognize variations of:
8985/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8987 Value *CmpLHS, Value *CmpRHS,
8988 Value *TrueVal, Value *FalseVal) {
8989 // Swap the select operands and predicate to match the patterns below.
8990 if (CmpRHS != TrueVal) {
8991 Pred = ICmpInst::getSwappedPredicate(Pred);
8992 std::swap(TrueVal, FalseVal);
8993 }
8994 const APInt *C1;
8995 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8996 const APInt *C2;
8997 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8998 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8999 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
9000 return {SPF_SMAX, SPNB_NA, false};
9001
9002 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
9003 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9004 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
9005 return {SPF_SMIN, SPNB_NA, false};
9006
9007 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
9008 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
9009 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
9010 return {SPF_UMAX, SPNB_NA, false};
9011
9012 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
9013 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
9014 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
9015 return {SPF_UMIN, SPNB_NA, false};
9016 }
9017 return {SPF_UNKNOWN, SPNB_NA, false};
9018}
9019
9020/// If the input value is the result of a 'not' op, constant integer, or vector
9021/// splat of a constant integer, return the bitwise-not source value.
9022/// TODO: This could be extended to handle non-splat vector integer constants.
9024 Value *NotV;
9025 if (match(V, m_Not(m_Value(NotV))))
9026 return NotV;
9027
9028 const APInt *C;
9029 if (match(V, m_APInt(C)))
9030 return ConstantInt::get(V->getType(), ~(*C));
9031
9032 return nullptr;
9033}
9034
9035/// Match non-obvious integer minimum and maximum sequences.
9037 Value *CmpRHS, Value *TrueVal,
9038 Value *FalseVal, Value *&LHS,
9039 Value *&RHS) {
9040 // Assume success. If there's no match, callers should not use these anyway.
9041 LHS = TrueVal;
9042 RHS = FalseVal;
9043
9044 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
9046 return SPR;
9047
9048 // Look through 'not' ops to find disguised min/max.
9049 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
9050 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
9051 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
9052 switch (Pred) {
9053 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
9054 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
9055 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
9056 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
9057 default: break;
9058 }
9059 }
9060
9061 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
9062 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
9063 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
9064 switch (Pred) {
9065 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
9066 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
9067 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
9068 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
9069 default: break;
9070 }
9071 }
9072
9073 if (Pred != CmpInst::ICMP_SGT && Pred != CmpInst::ICMP_SLT)
9074 return {SPF_UNKNOWN, SPNB_NA, false};
9075
9076 const APInt *C1;
9077 if (!match(CmpRHS, m_APInt(C1)))
9078 return {SPF_UNKNOWN, SPNB_NA, false};
9079
9080 // An unsigned min/max can be written with a signed compare.
9081 const APInt *C2;
9082 if ((CmpLHS == TrueVal && match(FalseVal, m_APInt(C2))) ||
9083 (CmpLHS == FalseVal && match(TrueVal, m_APInt(C2)))) {
9084 // Is the sign bit set?
9085 // (X <s 0) ? X : MAXVAL ==> (X >u MAXVAL) ? X : MAXVAL ==> UMAX
9086 // (X <s 0) ? MAXVAL : X ==> (X >u MAXVAL) ? MAXVAL : X ==> UMIN
9087 if (Pred == CmpInst::ICMP_SLT && C1->isZero() && C2->isMaxSignedValue())
9088 return {CmpLHS == TrueVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9089
9090 // Is the sign bit clear?
9091 // (X >s -1) ? MINVAL : X ==> (X <u MINVAL) ? MINVAL : X ==> UMAX
9092 // (X >s -1) ? X : MINVAL ==> (X <u MINVAL) ? X : MINVAL ==> UMIN
9093 if (Pred == CmpInst::ICMP_SGT && C1->isAllOnes() && C2->isMinSignedValue())
9094 return {CmpLHS == FalseVal ? SPF_UMAX : SPF_UMIN, SPNB_NA, false};
9095 }
9096
9097 return {SPF_UNKNOWN, SPNB_NA, false};
9098}
9099
9100bool llvm::isKnownNegation(const Value *X, const Value *Y, bool NeedNSW,
9101 bool AllowPoison) {
9102 assert(X && Y && "Invalid operand");
9103
9104 auto IsNegationOf = [&](const Value *X, const Value *Y) {
9105 if (!match(X, m_Neg(m_Specific(Y))))
9106 return false;
9107
9108 auto *BO = cast<BinaryOperator>(X);
9109 if (NeedNSW && !BO->hasNoSignedWrap())
9110 return false;
9111
9112 auto *Zero = cast<Constant>(BO->getOperand(0));
9113 if (!AllowPoison && !Zero->isNullValue())
9114 return false;
9115
9116 return true;
9117 };
9118
9119 // X = -Y or Y = -X
9120 if (IsNegationOf(X, Y) || IsNegationOf(Y, X))
9121 return true;
9122
9123 // X = sub (A, B), Y = sub (B, A) || X = sub nsw (A, B), Y = sub nsw (B, A)
9124 Value *A, *B;
9125 return (!NeedNSW && (match(X, m_Sub(m_Value(A), m_Value(B))) &&
9126 match(Y, m_Sub(m_Specific(B), m_Specific(A))))) ||
9127 (NeedNSW && (match(X, m_NSWSub(m_Value(A), m_Value(B))) &&
9129}
9130
9131bool llvm::isKnownInversion(const Value *X, const Value *Y) {
9132 // Handle X = icmp pred A, B, Y = icmp pred A, C.
9133 Value *A, *B, *C;
9134 CmpPredicate Pred1, Pred2;
9135 if (!match(X, m_ICmp(Pred1, m_Value(A), m_Value(B))) ||
9136 !match(Y, m_c_ICmp(Pred2, m_Specific(A), m_Value(C))))
9137 return false;
9138
9139 // They must both have samesign flag or not.
9140 if (Pred1.hasSameSign() != Pred2.hasSameSign())
9141 return false;
9142
9143 if (B == C)
9144 return Pred1 == ICmpInst::getInversePredicate(Pred2);
9145
9146 // Try to infer the relationship from constant ranges.
9147 const APInt *RHSC1, *RHSC2;
9148 if (!match(B, m_APInt(RHSC1)) || !match(C, m_APInt(RHSC2)))
9149 return false;
9150
9151 // Sign bits of two RHSCs should match.
9152 if (Pred1.hasSameSign() && RHSC1->isNonNegative() != RHSC2->isNonNegative())
9153 return false;
9154
9155 const auto CR1 = ConstantRange::makeExactICmpRegion(Pred1, *RHSC1);
9156 const auto CR2 = ConstantRange::makeExactICmpRegion(Pred2, *RHSC2);
9157
9158 return CR1.inverse() == CR2;
9159}
9160
9162 SelectPatternNaNBehavior NaNBehavior,
9163 bool Ordered) {
9164 switch (Pred) {
9165 default:
9166 return {SPF_UNKNOWN, SPNB_NA, false}; // Equality.
9167 case ICmpInst::ICMP_UGT:
9168 case ICmpInst::ICMP_UGE:
9169 return {SPF_UMAX, SPNB_NA, false};
9170 case ICmpInst::ICMP_SGT:
9171 case ICmpInst::ICMP_SGE:
9172 return {SPF_SMAX, SPNB_NA, false};
9173 case ICmpInst::ICMP_ULT:
9174 case ICmpInst::ICMP_ULE:
9175 return {SPF_UMIN, SPNB_NA, false};
9176 case ICmpInst::ICMP_SLT:
9177 case ICmpInst::ICMP_SLE:
9178 return {SPF_SMIN, SPNB_NA, false};
9179 case FCmpInst::FCMP_UGT:
9180 case FCmpInst::FCMP_UGE:
9181 case FCmpInst::FCMP_OGT:
9182 case FCmpInst::FCMP_OGE:
9183 return {SPF_FMAXNUM, NaNBehavior, Ordered};
9184 case FCmpInst::FCMP_ULT:
9185 case FCmpInst::FCMP_ULE:
9186 case FCmpInst::FCMP_OLT:
9187 case FCmpInst::FCMP_OLE:
9188 return {SPF_FMINNUM, NaNBehavior, Ordered};
9189 }
9190}
9191
9192std::optional<std::pair<CmpPredicate, Constant *>>
9195 "Only for relational integer predicates.");
9196 if (isa<UndefValue>(C))
9197 return std::nullopt;
9198
9199 Type *Type = C->getType();
9200 bool IsSigned = ICmpInst::isSigned(Pred);
9201
9203 bool WillIncrement =
9204 UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
9205
9206 // Check if the constant operand can be safely incremented/decremented
9207 // without overflowing/underflowing.
9208 auto ConstantIsOk = [Pred, WillIncrement, IsSigned](ConstantInt *C) {
9209 if (WillIncrement ? C->isMaxValue(IsSigned) : C->isMinValue(IsSigned))
9210 return false;
9211
9212 if (!Pred.hasSameSign())
9213 return true;
9214
9215 // Crossing the corresponding boundary in the other ordering changes the
9216 // sign bit, and therefore changes the poison domain.
9217 return WillIncrement ? !C->isMaxValue(!IsSigned)
9218 : !C->isMinValue(!IsSigned);
9219 };
9220
9221 Constant *SafeReplacementConstant = nullptr;
9222 if (auto *CI = dyn_cast<ConstantInt>(C)) {
9223 // Bail out if the constant can't be safely incremented/decremented.
9224 if (!ConstantIsOk(CI))
9225 return std::nullopt;
9226 } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
9227 unsigned NumElts = FVTy->getNumElements();
9228 for (unsigned i = 0; i != NumElts; ++i) {
9229 Constant *Elt = C->getAggregateElement(i);
9230 if (!Elt)
9231 return std::nullopt;
9232
9233 if (isa<UndefValue>(Elt))
9234 continue;
9235
9236 // Bail out if we can't determine if this constant is min/max or if we
9237 // know that this constant is min/max.
9238 auto *CI = dyn_cast<ConstantInt>(Elt);
9239 if (!CI || !ConstantIsOk(CI))
9240 return std::nullopt;
9241
9242 if (!SafeReplacementConstant)
9243 SafeReplacementConstant = CI;
9244 }
9245 } else if (isa<VectorType>(C->getType())) {
9246 // Handle scalable splat
9247 Value *SplatC = C->getSplatValue();
9248 auto *CI = dyn_cast_or_null<ConstantInt>(SplatC);
9249 // Bail out if the constant can't be safely incremented/decremented.
9250 if (!CI || !ConstantIsOk(CI))
9251 return std::nullopt;
9252 } else {
9253 // ConstantExpr?
9254 return std::nullopt;
9255 }
9256
9257 // It may not be safe to change a compare predicate in the presence of
9258 // undefined elements, so replace those elements with the first safe constant
9259 // that we found.
9260 // TODO: in case of poison, it is safe; let's replace undefs only.
9261 if (C->containsUndefOrPoisonElement()) {
9262 assert(SafeReplacementConstant && "Replacement constant not set");
9263 C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
9264 }
9265
9267 Pred.hasSameSign());
9268
9269 // Increment or decrement the constant.
9270 Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
9271 Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
9272
9273 return std::make_pair(NewPred, NewC);
9274}
9275
9277 FastMathFlags FMF, Value *CmpLHS,
9278 Value *CmpRHS, Value *TrueVal,
9279 Value *FalseVal, Value *&LHS,
9280 Value *&RHS) {
9281 if (CmpInst::isFPPredicate(Pred)) {
9282 // IEEE-754 ignores the sign of 0.0 in comparisons. So if the select has one
9283 // 0.0 operand, set the compare's 0.0 operands to that same value for the
9284 // purpose of identifying min/max. Disregard vector constants with undefined
9285 // elements because those can not be back-propagated for analysis.
9286 Value *OutputZeroVal = nullptr;
9287 if (match(TrueVal, m_AnyZeroFP()) && !match(FalseVal, m_AnyZeroFP()) &&
9288 !cast<Constant>(TrueVal)->containsUndefOrPoisonElement())
9289 OutputZeroVal = TrueVal;
9290 else if (match(FalseVal, m_AnyZeroFP()) && !match(TrueVal, m_AnyZeroFP()) &&
9291 !cast<Constant>(FalseVal)->containsUndefOrPoisonElement())
9292 OutputZeroVal = FalseVal;
9293
9294 if (OutputZeroVal) {
9295 if (match(CmpLHS, m_AnyZeroFP()) && CmpLHS != OutputZeroVal)
9296 CmpLHS = OutputZeroVal;
9297 if (match(CmpRHS, m_AnyZeroFP()) && CmpRHS != OutputZeroVal)
9298 CmpRHS = OutputZeroVal;
9299 }
9300 }
9301
9302 LHS = CmpLHS;
9303 RHS = CmpRHS;
9304
9305 // Signed zero may return inconsistent results between implementations.
9306 // (0.0 <= -0.0) ? 0.0 : -0.0 // Returns 0.0
9307 // minNum(0.0, -0.0) // May return -0.0 or 0.0 (IEEE 754-2008 5.3.1)
9308 // Therefore, we behave conservatively and only proceed if at least one of the
9309 // operands is known to not be zero or if we don't care about signed zero.
9310 if (CmpInst::isFPPredicate(Pred)) {
9311 if (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9312 !isKnownNonZero(CmpRHS))
9313 return {SPF_UNKNOWN, SPNB_NA, false};
9314 }
9315
9316 SelectPatternNaNBehavior NaNBehavior = SPNB_NA;
9317 bool Ordered = false;
9318
9319 // When given one NaN and one non-NaN input:
9320 // - maxnum/minnum (C99 fmaxf()/fminf()) return the non-NaN input.
9321 // - A simple C99 (a < b ? a : b) construction will return 'b' (as the
9322 // ordered comparison fails), which could be NaN or non-NaN.
9323 // so here we discover exactly what NaN behavior is required/accepted.
9324 if (CmpInst::isFPPredicate(Pred)) {
9325 bool LHSSafe = isKnownNonNaN(CmpLHS, FMF);
9326 bool RHSSafe = isKnownNonNaN(CmpRHS, FMF);
9327
9328 if (LHSSafe && RHSSafe) {
9329 // Both operands are known non-NaN.
9330 NaNBehavior = SPNB_RETURNS_ANY;
9331 Ordered = CmpInst::isOrdered(Pred);
9332 } else if (CmpInst::isOrdered(Pred)) {
9333 // An ordered comparison will return false when given a NaN, so it
9334 // returns the RHS.
9335 Ordered = true;
9336 if (LHSSafe)
9337 // LHS is non-NaN, so if RHS is NaN then NaN will be returned.
9338 NaNBehavior = SPNB_RETURNS_NAN;
9339 else if (RHSSafe)
9340 NaNBehavior = SPNB_RETURNS_OTHER;
9341 else
9342 // Completely unsafe.
9343 return {SPF_UNKNOWN, SPNB_NA, false};
9344 } else {
9345 Ordered = false;
9346 // An unordered comparison will return true when given a NaN, so it
9347 // returns the LHS.
9348 if (LHSSafe)
9349 // LHS is non-NaN, so if RHS is NaN then non-NaN will be returned.
9350 NaNBehavior = SPNB_RETURNS_OTHER;
9351 else if (RHSSafe)
9352 NaNBehavior = SPNB_RETURNS_NAN;
9353 else
9354 // Completely unsafe.
9355 return {SPF_UNKNOWN, SPNB_NA, false};
9356 }
9357 }
9358
9359 if (TrueVal == CmpRHS && FalseVal == CmpLHS) {
9360 std::swap(CmpLHS, CmpRHS);
9361 Pred = CmpInst::getSwappedPredicate(Pred);
9362 if (NaNBehavior == SPNB_RETURNS_NAN)
9363 NaNBehavior = SPNB_RETURNS_OTHER;
9364 else if (NaNBehavior == SPNB_RETURNS_OTHER)
9365 NaNBehavior = SPNB_RETURNS_NAN;
9366 Ordered = !Ordered;
9367 }
9368
9369 // ([if]cmp X, Y) ? X : Y
9370 if (TrueVal == CmpLHS && FalseVal == CmpRHS)
9371 return getSelectPattern(Pred, NaNBehavior, Ordered);
9372
9373 if (isKnownNegation(TrueVal, FalseVal)) {
9374 // Sign-extending LHS does not change its sign, so TrueVal/FalseVal can
9375 // match against either LHS or sign-preserving operations on LHS, like
9376 // sext(LHS), or binary ops that do not wrap in signed sense.
9377 auto CmpLHSOrSExt =
9378 m_CombineOr(m_Specific(CmpLHS), m_SExt(m_Specific(CmpLHS)));
9379 auto MaybeSExtOrMulCmpLHS =
9380 m_CombineOr(CmpLHSOrSExt, m_NSWMul(CmpLHSOrSExt, m_StrictlyPositive()),
9381 m_NSWShl(CmpLHSOrSExt, m_Value()));
9382 auto ZeroOrAllOnes = m_CombineOr(m_ZeroInt(), m_AllOnes());
9383 auto ZeroOrOne = m_CombineOr(m_ZeroInt(), m_One());
9384 if (match(TrueVal, MaybeSExtOrMulCmpLHS)) {
9385 // Set the return values. If the compare uses the negated value (-X >s 0),
9386 // swap the return values because the negated value is always 'RHS'.
9387 LHS = TrueVal;
9388 RHS = FalseVal;
9389 if (match(CmpLHS, m_Neg(m_Specific(FalseVal))))
9390 std::swap(LHS, RHS);
9391
9392 // (X >s 0) ? X : -X or (X >s -1) ? X : -X --> ABS(X)
9393 // (-X >s 0) ? -X : X or (-X >s -1) ? -X : X --> ABS(X)
9394 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9395 return {SPF_ABS, SPNB_NA, false};
9396
9397 // (X >=s 0) ? X : -X or (X >=s 1) ? X : -X --> ABS(X)
9398 if (Pred == ICmpInst::ICMP_SGE && match(CmpRHS, ZeroOrOne))
9399 return {SPF_ABS, SPNB_NA, false};
9400
9401 // (X <s 0) ? X : -X or (X <s 1) ? X : -X --> NABS(X)
9402 // (-X <s 0) ? -X : X or (-X <s 1) ? -X : X --> NABS(X)
9403 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9404 return {SPF_NABS, SPNB_NA, false};
9405 } else if (match(FalseVal, MaybeSExtOrMulCmpLHS)) {
9406 // Set the return values. If the compare uses the negated value (-X >s 0),
9407 // swap the return values because the negated value is always 'RHS'.
9408 LHS = FalseVal;
9409 RHS = TrueVal;
9410 if (match(CmpLHS, m_Neg(m_Specific(TrueVal))))
9411 std::swap(LHS, RHS);
9412
9413 // (X >s 0) ? -X : X or (X >s -1) ? -X : X --> NABS(X)
9414 // (-X >s 0) ? X : -X or (-X >s -1) ? X : -X --> NABS(X)
9415 if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, ZeroOrAllOnes))
9416 return {SPF_NABS, SPNB_NA, false};
9417
9418 // (X <s 0) ? -X : X or (X <s 1) ? -X : X --> ABS(X)
9419 // (-X <s 0) ? X : -X or (-X <s 1) ? X : -X --> ABS(X)
9420 if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, ZeroOrOne))
9421 return {SPF_ABS, SPNB_NA, false};
9422 }
9423 }
9424
9425 if (CmpInst::isIntPredicate(Pred))
9426 return matchMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9427
9428 // According to (IEEE 754-2008 5.3.1), minNum(0.0, -0.0) and similar
9429 // may return either -0.0 or 0.0, so fcmp/select pair has stricter
9430 // semantics than minNum. Be conservative in such case.
9431 if (NaNBehavior != SPNB_RETURNS_ANY ||
9432 (!FMF.noSignedZeros() && !isKnownNonZero(CmpLHS) &&
9433 !isKnownNonZero(CmpRHS)))
9434 return {SPF_UNKNOWN, SPNB_NA, false};
9435
9436 return matchFastFloatClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS, RHS);
9437}
9438
9440 Instruction::CastOps *CastOp) {
9441 const DataLayout &DL = CmpI->getDataLayout();
9442
9443 Constant *CastedTo = nullptr;
9444 switch (*CastOp) {
9445 case Instruction::ZExt:
9446 if (CmpI->isUnsigned())
9447 CastedTo = ConstantExpr::getTrunc(C, SrcTy);
9448 break;
9449 case Instruction::SExt:
9450 if (CmpI->isSigned())
9451 CastedTo = ConstantExpr::getTrunc(C, SrcTy, true);
9452 break;
9453 case Instruction::Trunc:
9454 Constant *CmpConst;
9455 if (match(CmpI->getOperand(1), m_Constant(CmpConst)) &&
9456 CmpConst->getType() == SrcTy) {
9457 // Here we have the following case:
9458 //
9459 // %cond = cmp iN %x, CmpConst
9460 // %tr = trunc iN %x to iK
9461 // %narrowsel = select i1 %cond, iK %t, iK C
9462 //
9463 // We can always move trunc after select operation:
9464 //
9465 // %cond = cmp iN %x, CmpConst
9466 // %widesel = select i1 %cond, iN %x, iN CmpConst
9467 // %tr = trunc iN %widesel to iK
9468 //
9469 // Note that C could be extended in any way because we don't care about
9470 // upper bits after truncation. It can't be abs pattern, because it would
9471 // look like:
9472 //
9473 // select i1 %cond, x, -x.
9474 //
9475 // So only min/max pattern could be matched. Such match requires widened C
9476 // == CmpConst. That is why set widened C = CmpConst, condition trunc
9477 // CmpConst == C is checked below.
9478 CastedTo = CmpConst;
9479 } else {
9480 unsigned ExtOp = CmpI->isSigned() ? Instruction::SExt : Instruction::ZExt;
9481 CastedTo = ConstantFoldCastOperand(ExtOp, C, SrcTy, DL);
9482 }
9483 break;
9484 case Instruction::FPTrunc:
9485 CastedTo = ConstantFoldCastOperand(Instruction::FPExt, C, SrcTy, DL);
9486 break;
9487 case Instruction::FPExt:
9488 CastedTo = ConstantFoldCastOperand(Instruction::FPTrunc, C, SrcTy, DL);
9489 break;
9490 case Instruction::FPToUI:
9491 CastedTo = ConstantFoldCastOperand(Instruction::UIToFP, C, SrcTy, DL);
9492 break;
9493 case Instruction::FPToSI:
9494 CastedTo = ConstantFoldCastOperand(Instruction::SIToFP, C, SrcTy, DL);
9495 break;
9496 case Instruction::UIToFP:
9497 CastedTo = ConstantFoldCastOperand(Instruction::FPToUI, C, SrcTy, DL);
9498 break;
9499 case Instruction::SIToFP:
9500 CastedTo = ConstantFoldCastOperand(Instruction::FPToSI, C, SrcTy, DL);
9501 break;
9502 default:
9503 break;
9504 }
9505
9506 if (!CastedTo)
9507 return nullptr;
9508
9509 // Make sure the cast doesn't lose any information.
9510 Constant *CastedBack =
9511 ConstantFoldCastOperand(*CastOp, CastedTo, C->getType(), DL);
9512 if (CastedBack && CastedBack != C)
9513 return nullptr;
9514
9515 return CastedTo;
9516}
9517
9518/// Helps to match a select pattern in case of a type mismatch.
9519///
9520/// The function processes the case when type of true and false values of a
9521/// select instruction differs from type of the cmp instruction operands because
9522/// of a cast instruction. The function checks if it is legal to move the cast
9523/// operation after "select". If yes, it returns the new second value of
9524/// "select" (with the assumption that cast is moved):
9525/// 1. As operand of cast instruction when both values of "select" are same cast
9526/// instructions.
9527/// 2. As restored constant (by applying reverse cast operation) when the first
9528/// value of the "select" is a cast operation and the second value is a
9529/// constant. It is implemented in lookThroughCastConst().
9530/// 3. As one operand is cast instruction and the other is not. The operands in
9531/// sel(cmp) are in different type integer.
9532/// NOTE: We return only the new second value because the first value could be
9533/// accessed as operand of cast instruction.
9535 Instruction::CastOps *CastOp) {
9536 auto *Cast1 = dyn_cast<CastInst>(V1);
9537 if (!Cast1)
9538 return nullptr;
9539
9540 *CastOp = Cast1->getOpcode();
9541 Type *SrcTy = Cast1->getSrcTy();
9542 if (auto *Cast2 = dyn_cast<CastInst>(V2)) {
9543 // If V1 and V2 are both the same cast from the same type, look through V1.
9544 if (*CastOp == Cast2->getOpcode() && SrcTy == Cast2->getSrcTy())
9545 return Cast2->getOperand(0);
9546 return nullptr;
9547 }
9548
9549 auto *C = dyn_cast<Constant>(V2);
9550 if (C)
9551 return lookThroughCastConst(CmpI, SrcTy, C, CastOp);
9552
9553 Value *CastedTo = nullptr;
9554 if (*CastOp == Instruction::Trunc) {
9555 if (match(CmpI->getOperand(1), m_ZExtOrSExt(m_Specific(V2)))) {
9556 // Here we have the following case:
9557 // %y_ext = sext iK %y to iN
9558 // %cond = cmp iN %x, %y_ext
9559 // %tr = trunc iN %x to iK
9560 // %narrowsel = select i1 %cond, iK %tr, iK %y
9561 //
9562 // We can always move trunc after select operation:
9563 // %y_ext = sext iK %y to iN
9564 // %cond = cmp iN %x, %y_ext
9565 // %widesel = select i1 %cond, iN %x, iN %y_ext
9566 // %tr = trunc iN %widesel to iK
9567 assert(V2->getType() == Cast1->getType() &&
9568 "V2 and Cast1 should be the same type.");
9569 CastedTo = CmpI->getOperand(1);
9570 }
9571 }
9572
9573 return CastedTo;
9574}
9576 Instruction::CastOps *CastOp) {
9578 if (!SI) return {SPF_UNKNOWN, SPNB_NA, false};
9579
9580 CmpInst *CmpI = dyn_cast<CmpInst>(SI->getCondition());
9581 if (!CmpI) return {SPF_UNKNOWN, SPNB_NA, false};
9582
9583 Value *TrueVal = SI->getTrueValue();
9584 Value *FalseVal = SI->getFalseValue();
9585
9587 CmpI, TrueVal, FalseVal, LHS, RHS, SI->getFastMathFlagsOrNone(), CastOp);
9588}
9589
9591 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
9592 FastMathFlags FMF, Instruction::CastOps *CastOp) {
9593 CmpInst::Predicate Pred = CmpI->getPredicate();
9594 Value *CmpLHS = CmpI->getOperand(0);
9595 Value *CmpRHS = CmpI->getOperand(1);
9596 if (isa<FPMathOperator>(CmpI) && CmpI->hasNoNaNs())
9597 FMF.setNoNaNs();
9598
9599 // Bail out early.
9600 if (CmpI->isEquality())
9601 return {SPF_UNKNOWN, SPNB_NA, false};
9602
9603 // Deal with type mismatches.
9604 if (CastOp && CmpLHS->getType() != TrueVal->getType()) {
9605 if (Value *C = lookThroughCast(CmpI, TrueVal, FalseVal, CastOp)) {
9606 // If this is a potential fmin/fmax with a cast to integer, then ignore
9607 // -0.0 because there is no corresponding integer value.
9608 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9609 FMF.setNoSignedZeros();
9610 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS,
9611 cast<CastInst>(TrueVal)->getOperand(0), C,
9612 LHS, RHS);
9613 }
9614 if (Value *C = lookThroughCast(CmpI, FalseVal, TrueVal, CastOp)) {
9615 // If this is a potential fmin/fmax with a cast to integer, then ignore
9616 // -0.0 because there is no corresponding integer value.
9617 if (*CastOp == Instruction::FPToSI || *CastOp == Instruction::FPToUI)
9618 FMF.setNoSignedZeros();
9619 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, C,
9620 cast<CastInst>(FalseVal)->getOperand(0), LHS,
9621 RHS);
9622 }
9623 }
9624 return ::matchSelectPattern(Pred, FMF, CmpLHS, CmpRHS, TrueVal, FalseVal, LHS,
9625 RHS);
9626}
9627
9629 if (SPF == SPF_SMIN) return ICmpInst::ICMP_SLT;
9630 if (SPF == SPF_UMIN) return ICmpInst::ICMP_ULT;
9631 if (SPF == SPF_SMAX) return ICmpInst::ICMP_SGT;
9632 if (SPF == SPF_UMAX) return ICmpInst::ICMP_UGT;
9633 if (SPF == SPF_FMINNUM)
9634 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
9635 if (SPF == SPF_FMAXNUM)
9636 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
9637 llvm_unreachable("unhandled!");
9638}
9639
9641 switch (SPF) {
9643 return Intrinsic::umin;
9645 return Intrinsic::umax;
9647 return Intrinsic::smin;
9649 return Intrinsic::smax;
9650 default:
9651 llvm_unreachable("Unexpected SPF");
9652 }
9653}
9654
9656 if (SPF == SPF_SMIN) return SPF_SMAX;
9657 if (SPF == SPF_UMIN) return SPF_UMAX;
9658 if (SPF == SPF_SMAX) return SPF_SMIN;
9659 if (SPF == SPF_UMAX) return SPF_UMIN;
9660 llvm_unreachable("unhandled!");
9661}
9662
9664 switch (MinMaxID) {
9665 case Intrinsic::smax: return Intrinsic::smin;
9666 case Intrinsic::smin: return Intrinsic::smax;
9667 case Intrinsic::umax: return Intrinsic::umin;
9668 case Intrinsic::umin: return Intrinsic::umax;
9669 // Please note that next four intrinsics may produce the same result for
9670 // original and inverted case even if X != Y due to NaN is handled specially.
9671 case Intrinsic::maximum: return Intrinsic::minimum;
9672 case Intrinsic::minimum: return Intrinsic::maximum;
9673 case Intrinsic::maxnum: return Intrinsic::minnum;
9674 case Intrinsic::minnum: return Intrinsic::maxnum;
9675 case Intrinsic::maximumnum:
9676 return Intrinsic::minimumnum;
9677 case Intrinsic::minimumnum:
9678 return Intrinsic::maximumnum;
9679 default: llvm_unreachable("Unexpected intrinsic");
9680 }
9681}
9682
9684 switch (SPF) {
9687 case SPF_UMAX: return APInt::getMaxValue(BitWidth);
9688 case SPF_UMIN: return APInt::getMinValue(BitWidth);
9689 default: llvm_unreachable("Unexpected flavor");
9690 }
9691}
9692
9693std::pair<Intrinsic::ID, bool>
9695 // Check if VL contains select instructions that can be folded into a min/max
9696 // vector intrinsic and return the intrinsic if it is possible.
9697 // TODO: Support floating point min/max.
9698 bool AllCmpSingleUse = true;
9699 SelectPatternResult SelectPattern;
9700 SelectPattern.Flavor = SPF_UNKNOWN;
9701 if (all_of(VL, [&SelectPattern, &AllCmpSingleUse](Value *I) {
9702 Value *LHS, *RHS;
9703 auto CurrentPattern = matchSelectPattern(I, LHS, RHS);
9704 if (!SelectPatternResult::isMinOrMax(CurrentPattern.Flavor))
9705 return false;
9706 if (SelectPattern.Flavor != SPF_UNKNOWN &&
9707 SelectPattern.Flavor != CurrentPattern.Flavor)
9708 return false;
9709 SelectPattern = CurrentPattern;
9710 AllCmpSingleUse &=
9712 return true;
9713 })) {
9714 switch (SelectPattern.Flavor) {
9715 case SPF_SMIN:
9716 return {Intrinsic::smin, AllCmpSingleUse};
9717 case SPF_UMIN:
9718 return {Intrinsic::umin, AllCmpSingleUse};
9719 case SPF_SMAX:
9720 return {Intrinsic::smax, AllCmpSingleUse};
9721 case SPF_UMAX:
9722 return {Intrinsic::umax, AllCmpSingleUse};
9723 case SPF_FMAXNUM:
9724 return {Intrinsic::maxnum, AllCmpSingleUse};
9725 case SPF_FMINNUM:
9726 return {Intrinsic::minnum, AllCmpSingleUse};
9727 default:
9728 llvm_unreachable("unexpected select pattern flavor");
9729 }
9730 }
9731 return {Intrinsic::not_intrinsic, false};
9732}
9733
9734template <typename InstTy>
9735static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst,
9736 Value *&Init, Value *&OtherOp) {
9737 // Handle the case of a simple two-predecessor recurrence PHI.
9738 // There's a lot more that could theoretically be done here, but
9739 // this is sufficient to catch some interesting cases.
9740 // TODO: Expand list -- gep, uadd.sat etc.
9741 if (PN->getNumIncomingValues() != 2)
9742 return false;
9743
9744 for (unsigned I = 0; I != 2; ++I) {
9745 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9746 Operation && Operation->getNumOperands() >= 2) {
9747 Value *LHS = Operation->getOperand(0);
9748 Value *RHS = Operation->getOperand(1);
9749 if (LHS != PN && RHS != PN)
9750 continue;
9751
9752 Inst = Operation;
9753 Init = PN->getIncomingValue(!I);
9754 OtherOp = (LHS == PN) ? RHS : LHS;
9755 return true;
9756 }
9757 }
9758 return false;
9759}
9760
9761template <typename InstTy>
9762static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst,
9763 Value *&Init, Value *&OtherOp0,
9764 Value *&OtherOp1) {
9765 if (PN->getNumIncomingValues() != 2)
9766 return false;
9767
9768 for (unsigned I = 0; I != 2; ++I) {
9769 if (auto *Operation = dyn_cast<InstTy>(PN->getIncomingValue(I));
9770 Operation && Operation->getNumOperands() >= 3) {
9771 Value *Op0 = Operation->getOperand(0);
9772 Value *Op1 = Operation->getOperand(1);
9773 Value *Op2 = Operation->getOperand(2);
9774
9775 if (Op0 != PN && Op1 != PN && Op2 != PN)
9776 continue;
9777
9778 Inst = Operation;
9779 Init = PN->getIncomingValue(!I);
9780 if (Op0 == PN) {
9781 OtherOp0 = Op1;
9782 OtherOp1 = Op2;
9783 } else if (Op1 == PN) {
9784 OtherOp0 = Op0;
9785 OtherOp1 = Op2;
9786 } else {
9787 OtherOp0 = Op0;
9788 OtherOp1 = Op1;
9789 }
9790 return true;
9791 }
9792 }
9793 return false;
9794}
9796 Value *&Start, Value *&Step) {
9797 // We try to match a recurrence of the form:
9798 // %iv = [Start, %entry], [%iv.next, %backedge]
9799 // %iv.next = binop %iv, Step
9800 // Or:
9801 // %iv = [Start, %entry], [%iv.next, %backedge]
9802 // %iv.next = binop Step, %iv
9803 return matchTwoInputRecurrence(P, BO, Start, Step);
9804}
9805
9807 Value *&Start, Value *&Step) {
9808 BinaryOperator *BO = nullptr;
9809 return match(I, m_c_BinOp(m_Phi(P), m_Value())) &&
9810 matchSimpleRecurrence(P, BO, Start, Step) && BO == I;
9811}
9812
9814 PHINode *&P, Value *&Init,
9815 Value *&OtherOp) {
9816 // Binary intrinsics only supported for now.
9817 if (I->arg_size() != 2 || I->getType() != I->getArgOperand(0)->getType() ||
9818 I->getType() != I->getArgOperand(1)->getType())
9819 return false;
9820
9821 IntrinsicInst *II = nullptr;
9822 P = dyn_cast<PHINode>(I->getArgOperand(0));
9823 if (!P)
9824 P = dyn_cast<PHINode>(I->getArgOperand(1));
9825
9826 return P && matchTwoInputRecurrence(P, II, Init, OtherOp) && II == I;
9827}
9828
9830 PHINode *&P, Value *&Init,
9831 Value *&OtherOp0,
9832 Value *&OtherOp1) {
9833 if (I->arg_size() != 3 || I->getType() != I->getArgOperand(0)->getType() ||
9834 I->getType() != I->getArgOperand(1)->getType() ||
9835 I->getType() != I->getArgOperand(2)->getType())
9836 return false;
9837 IntrinsicInst *II = nullptr;
9838 P = dyn_cast<PHINode>(I->getArgOperand(0));
9839 if (!P) {
9840 P = dyn_cast<PHINode>(I->getArgOperand(1));
9841 if (!P)
9842 P = dyn_cast<PHINode>(I->getArgOperand(2));
9843 }
9844 return P && matchThreeInputRecurrence(P, II, Init, OtherOp0, OtherOp1) &&
9845 II == I;
9846}
9847
9848/// Return true if "icmp Pred LHS RHS" is always true.
9850 const Value *RHS) {
9851 if (ICmpInst::isTrueWhenEqual(Pred) && LHS == RHS)
9852 return true;
9853
9854 switch (Pred) {
9855 default:
9856 return false;
9857
9858 case CmpInst::ICMP_SLE: {
9859 const APInt *C;
9860
9861 // LHS s<= LHS +_{nsw} C if C >= 0
9862 // LHS s<= LHS | C if C >= 0
9863 if (match(RHS, m_NSWAdd(m_Specific(LHS), m_APInt(C))) ||
9865 return !C->isNegative();
9866
9867 // LHS s<= smax(LHS, V) for any V
9869 return true;
9870
9871 // smin(RHS, V) s<= RHS for any V
9873 return true;
9874
9875 // Match A to (X +_{nsw} CA) and B to (X +_{nsw} CB)
9876 const Value *X;
9877 const APInt *CLHS, *CRHS;
9878 if (match(LHS, m_NSWAddLike(m_Value(X), m_APInt(CLHS))) &&
9880 return CLHS->sle(*CRHS);
9881
9882 return false;
9883 }
9884
9885 case CmpInst::ICMP_ULE: {
9886 // LHS u<= LHS +_{nuw} V for any V
9887 if (match(RHS, m_c_Add(m_Specific(LHS), m_Value())) &&
9889 return true;
9890
9891 // LHS u<= LHS | V for any V
9892 if (match(RHS, m_c_Or(m_Specific(LHS), m_Value())))
9893 return true;
9894
9895 // LHS u<= umax(LHS, V) for any V
9897 return true;
9898
9899 // RHS >> V u<= RHS for any V
9900 if (match(LHS, m_LShr(m_Specific(RHS), m_Value())))
9901 return true;
9902
9903 // RHS u/ C_ugt_1 u<= RHS
9904 const APInt *C;
9905 if (match(LHS, m_UDiv(m_Specific(RHS), m_APInt(C))) && C->ugt(1))
9906 return true;
9907
9908 // RHS & V u<= RHS for any V
9910 return true;
9911
9912 // umin(RHS, V) u<= RHS for any V
9914 return true;
9915
9916 // Match A to (X +_{nuw} CA) and B to (X +_{nuw} CB)
9917 const Value *X;
9918 const APInt *CLHS, *CRHS;
9919 if (match(LHS, m_NUWAddLike(m_Value(X), m_APInt(CLHS))) &&
9921 return CLHS->ule(*CRHS);
9922
9923 return false;
9924 }
9925 }
9926}
9927
9928/// Return true if "icmp Pred BLHS BRHS" is true whenever "icmp Pred
9929/// ALHS ARHS" is true. Otherwise, return std::nullopt.
9930static std::optional<bool>
9932 const Value *ARHS, const Value *BLHS, const Value *BRHS) {
9933 switch (Pred) {
9934 default:
9935 return std::nullopt;
9936
9937 case CmpInst::ICMP_SLT:
9938 case CmpInst::ICMP_SLE:
9939 if (isTruePredicate(CmpInst::ICMP_SLE, BLHS, ALHS) &&
9941 return true;
9942 return std::nullopt;
9943
9944 case CmpInst::ICMP_SGT:
9945 case CmpInst::ICMP_SGE:
9946 if (isTruePredicate(CmpInst::ICMP_SLE, ALHS, BLHS) &&
9948 return true;
9949 return std::nullopt;
9950
9951 case CmpInst::ICMP_ULT:
9952 case CmpInst::ICMP_ULE:
9953 if (isTruePredicate(CmpInst::ICMP_ULE, BLHS, ALHS) &&
9955 return true;
9956 return std::nullopt;
9957
9958 case CmpInst::ICMP_UGT:
9959 case CmpInst::ICMP_UGE:
9960 if (isTruePredicate(CmpInst::ICMP_ULE, ALHS, BLHS) &&
9962 return true;
9963 return std::nullopt;
9964 }
9965}
9966
9967/// Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
9968/// Return false if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is false.
9969/// Otherwise, return std::nullopt if we can't infer anything.
9970static std::optional<bool>
9972 CmpPredicate RPred, const ConstantRange &RCR) {
9973 auto CRImpliesPred = [&](ConstantRange CR,
9974 CmpInst::Predicate Pred) -> std::optional<bool> {
9975 // If all true values for lhs and true for rhs, lhs implies rhs
9976 if (CR.icmp(Pred, RCR))
9977 return true;
9978
9979 // If there is no overlap, lhs implies not rhs
9980 if (CR.icmp(CmpInst::getInversePredicate(Pred), RCR))
9981 return false;
9982
9983 return std::nullopt;
9984 };
9985 if (auto Res = CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9986 RPred))
9987 return Res;
9988 if (LPred.hasSameSign() ^ RPred.hasSameSign()) {
9990 : LPred.dropSameSign();
9992 : RPred.dropSameSign();
9993 return CRImpliesPred(ConstantRange::makeAllowedICmpRegion(LPred, LCR),
9994 RPred);
9995 }
9996 return std::nullopt;
9997}
9998
9999/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10000/// is true. Return false if LHS implies RHS is false. Otherwise, return
10001/// std::nullopt if we can't infer anything.
10002static std::optional<bool>
10003isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1,
10004 CmpPredicate RPred, const Value *R0, const Value *R1,
10005 const DataLayout &DL, bool LHSIsTrue) {
10006 // The rest of the logic assumes the LHS condition is true. If that's not the
10007 // case, invert the predicate to make it so.
10008 if (!LHSIsTrue)
10009 LPred = ICmpInst::getInverseCmpPredicate(LPred);
10010
10011 // We can have non-canonical operands, so try to normalize any common operand
10012 // to L0/R0.
10013 if (L0 == R1) {
10014 std::swap(R0, R1);
10015 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10016 }
10017 if (R0 == L1) {
10018 std::swap(L0, L1);
10019 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10020 }
10021 if (L1 == R1) {
10022 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10023 if (L0 != R0 || match(L0, m_ImmConstant())) {
10024 std::swap(L0, L1);
10025 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10026 std::swap(R0, R1);
10027 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10028 }
10029 }
10030
10031 // See if we can infer anything if operand-0 matches and we have at least one
10032 // constant.
10033 const APInt *Unused;
10034 if (L0 == R0 && (match(L1, m_APInt(Unused)) || match(R1, m_APInt(Unused)))) {
10035 // Potential TODO: We could also further use the constant range of L0/R0 to
10036 // further constraint the constant ranges. At the moment this leads to
10037 // several regressions related to not transforming `multi_use(A + C0) eq/ne
10038 // C1` (see discussion: D58633).
10039 SimplifyQuery SQ(DL);
10044
10045 // Even if L1/R1 are not both constant, we can still sometimes deduce
10046 // relationship from a single constant. For example X u> Y implies X != 0.
10047 if (auto R = isImpliedCondCommonOperandWithCR(LPred, LCR, RPred, RCR))
10048 return R;
10049 // If both L1/R1 were exact constant ranges and we didn't get anything
10050 // here, we won't be able to deduce this.
10051 if (match(L1, m_APInt(Unused)) && match(R1, m_APInt(Unused)))
10052 return std::nullopt;
10053 }
10054
10055 // Can we infer anything when the two compares have matching operands?
10056 if (L0 == R0 && L1 == R1)
10057 return ICmpInst::isImpliedByMatchingCmp(LPred, RPred);
10058
10059 // It only really makes sense in the context of signed comparison for "X - Y
10060 // must be positive if X >= Y and no overflow".
10061 // Take SGT as an example: L0:x > L1:y and C >= 0
10062 // ==> R0:(x -nsw y) < R1:(-C) is false
10063 CmpInst::Predicate SignedLPred = LPred.getPreferredSignedPredicate();
10064 if ((SignedLPred == ICmpInst::ICMP_SGT ||
10065 SignedLPred == ICmpInst::ICMP_SGE) &&
10066 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10067 if (match(R1, m_NonPositive()) &&
10068 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == false)
10069 return false;
10070 }
10071
10072 // Take SLT as an example: L0:x < L1:y and C <= 0
10073 // ==> R0:(x -nsw y) < R1:(-C) is true
10074 if ((SignedLPred == ICmpInst::ICMP_SLT ||
10075 SignedLPred == ICmpInst::ICMP_SLE) &&
10076 match(R0, m_NSWSub(m_Specific(L0), m_Specific(L1)))) {
10077 if (match(R1, m_NonNegative()) &&
10078 ICmpInst::isImpliedByMatchingCmp(SignedLPred, RPred) == true)
10079 return true;
10080 }
10081
10082 // (a - b) pred C -> a != b, if 0 pred C is false
10083 // (ptrtoint(a) - ptrtoint(b)) pred C -> a != b, if 0 pred C is false
10084 Value *A, *B;
10085 if (ICmpInst::isEquality(RPred) && cmpExcludesZero(LPred, L1) &&
10086 match(L0, m_Sub(m_Value(A), m_Value(B))) &&
10087 ((A == R0 && B == R1) || (A == R1 && B == R0) ||
10092 return RPred.dropSameSign() == ICmpInst::ICMP_NE;
10093 }
10094
10095 // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 <u L1 implies R0 <u R1
10096 if (L0 == R0 &&
10097 (LPred == ICmpInst::ICMP_ULT || LPred == ICmpInst::ICMP_UGE) &&
10098 (RPred == ICmpInst::ICMP_ULT || RPred == ICmpInst::ICMP_UGE) &&
10099 match(L0, m_c_Add(m_Specific(L1), m_Specific(R1))))
10100 return CmpPredicate::getMatching(LPred, RPred).has_value();
10101
10102 if (auto P = CmpPredicate::getMatching(LPred, RPred))
10103 return isImpliedCondOperands(*P, L0, L1, R0, R1);
10104
10105 // L0 u< C sets limits to L0's bits which may imply (L0 & Mask) pred RC
10106 // Example: L0 u< 13 => (L0 & 16) == 0
10107 const APInt *LC, *RC, *MaskC;
10108 if (match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)) &&
10109 match(R0, m_And(m_Specific(L0), m_APInt(MaskC)))) {
10111 ConstantRange MaskedCRange = LCRange.binaryAnd(*MaskC);
10112 if (MaskedCRange.icmp(RPred, ConstantRange(*RC)))
10113 return true;
10114 if (MaskedCRange.icmp(ICmpInst::getInversePredicate(RPred),
10115 ConstantRange(*RC)))
10116 return false;
10117 }
10118
10119 return std::nullopt;
10120}
10121
10122/// Return true if LHS implies RHS (expanded to its components as "R0 RPred R1")
10123/// is true. Return false if LHS implies RHS is false. Otherwise, return
10124/// std::nullopt if we can't infer anything.
10125static std::optional<bool>
10127 FCmpInst::Predicate RPred, const Value *R0, const Value *R1,
10128 const DataLayout &DL, bool LHSIsTrue) {
10129 // The rest of the logic assumes the LHS condition is true. If that's not the
10130 // case, invert the predicate to make it so.
10131 if (!LHSIsTrue)
10132 LPred = FCmpInst::getInversePredicate(LPred);
10133
10134 // We can have non-canonical operands, so try to normalize any common operand
10135 // to L0/R0.
10136 if (L0 == R1) {
10137 std::swap(R0, R1);
10138 RPred = FCmpInst::getSwappedPredicate(RPred);
10139 }
10140 if (R0 == L1) {
10141 std::swap(L0, L1);
10142 LPred = FCmpInst::getSwappedPredicate(LPred);
10143 }
10144 if (L1 == R1) {
10145 // If we have L0 == R0 and L1 == R1, then make L1/R1 the constants.
10146 if (L0 != R0 || match(L0, m_ImmConstant())) {
10147 std::swap(L0, L1);
10148 LPred = ICmpInst::getSwappedCmpPredicate(LPred);
10149 std::swap(R0, R1);
10150 RPred = ICmpInst::getSwappedCmpPredicate(RPred);
10151 }
10152 }
10153
10154 // Can we infer anything when the two compares have matching operands?
10155 if (L0 == R0 && L1 == R1) {
10156 if ((LPred & RPred) == LPred)
10157 return true;
10158 if ((LPred & ~RPred) == LPred)
10159 return false;
10160 }
10161
10162 // See if we can infer anything if operand-0 matches and we have at least one
10163 // constant.
10164 const APFloat *L1C, *R1C;
10165 if (L0 == R0 && match(L1, m_APFloat(L1C)) && match(R1, m_APFloat(R1C))) {
10166 if (std::optional<ConstantFPRange> DomCR =
10168 if (std::optional<ConstantFPRange> ImpliedCR =
10170 if (ImpliedCR->contains(*DomCR))
10171 return true;
10172 }
10173 if (std::optional<ConstantFPRange> ImpliedCR =
10175 FCmpInst::getInversePredicate(RPred), *R1C)) {
10176 if (ImpliedCR->contains(*DomCR))
10177 return false;
10178 }
10179 }
10180 }
10181
10182 return std::nullopt;
10183}
10184
10185/// Return true if LHS implies RHS is true. Return false if LHS implies RHS is
10186/// false. Otherwise, return std::nullopt if we can't infer anything. We
10187/// expect the RHS to be an icmp and the LHS to be an 'and', 'or', or a 'select'
10188/// instruction.
10189static std::optional<bool>
10191 const Value *RHSOp0, const Value *RHSOp1,
10192 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10193 // The LHS must be an 'or', 'and', or a 'select' instruction.
10194 assert((LHS->getOpcode() == Instruction::And ||
10195 LHS->getOpcode() == Instruction::Or ||
10196 LHS->getOpcode() == Instruction::Select) &&
10197 "Expected LHS to be 'and', 'or', or 'select'.");
10198
10199 assert(Depth <= MaxAnalysisRecursionDepth && "Hit recursion limit");
10200
10201 // If the result of an 'or' is false, then we know both legs of the 'or' are
10202 // false. Similarly, if the result of an 'and' is true, then we know both
10203 // legs of the 'and' are true.
10204 const Value *ALHS, *ARHS;
10205 if ((!LHSIsTrue && match(LHS, m_LogicalOr(m_Value(ALHS), m_Value(ARHS)))) ||
10206 (LHSIsTrue && match(LHS, m_LogicalAnd(m_Value(ALHS), m_Value(ARHS))))) {
10207 // FIXME: Make this non-recursion.
10208 if (std::optional<bool> Implication = isImpliedCondition(
10209 ALHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10210 return Implication;
10211 if (std::optional<bool> Implication = isImpliedCondition(
10212 ARHS, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue, Depth + 1))
10213 return Implication;
10214 return std::nullopt;
10215 }
10216 return std::nullopt;
10217}
10218
10219std::optional<bool>
10221 const Value *RHSOp0, const Value *RHSOp1,
10222 const DataLayout &DL, bool LHSIsTrue, unsigned Depth) {
10223 // Bail out when we hit the limit.
10225 return std::nullopt;
10226
10227 // A mismatch occurs when we compare a scalar cmp to a vector cmp, for
10228 // example.
10229 if (RHSOp0->getType()->isVectorTy() != LHS->getType()->isVectorTy())
10230 return std::nullopt;
10231
10232 assert(LHS->getType()->isIntOrIntVectorTy(1) &&
10233 "Expected integer type only!");
10234
10235 // Match not
10236 if (match(LHS, m_Not(m_Value(LHS))))
10237 LHSIsTrue = !LHSIsTrue;
10238
10239 // Both LHS and RHS are icmps.
10240 if (RHSOp0->getType()->getScalarType()->isIntOrPtrTy()) {
10241 CmpPredicate LHSPred;
10242 Value *LHSOp0, *LHSOp1;
10243 if (match(LHS, m_ICmpLike(LHSPred, m_Value(LHSOp0), m_Value(LHSOp1))))
10244 return isImpliedCondICmps(LHSPred, LHSOp0, LHSOp1, RHSPred, RHSOp0,
10245 RHSOp1, DL, LHSIsTrue);
10246 } else {
10247 assert(RHSOp0->getType()->isFPOrFPVectorTy() &&
10248 "Expected floating point type only!");
10249 if (const auto *LHSCmp = dyn_cast<FCmpInst>(LHS))
10250 return isImpliedCondFCmps(LHSCmp->getPredicate(), LHSCmp->getOperand(0),
10251 LHSCmp->getOperand(1), RHSPred, RHSOp0, RHSOp1,
10252 DL, LHSIsTrue);
10253 }
10254
10255 /// The LHS should be an 'or', 'and', or a 'select' instruction. We expect
10256 /// the RHS to be an icmp.
10257 /// FIXME: Add support for and/or/select on the RHS.
10258 if (const Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
10259 if ((LHSI->getOpcode() == Instruction::And ||
10260 LHSI->getOpcode() == Instruction::Or ||
10261 LHSI->getOpcode() == Instruction::Select))
10262 return isImpliedCondAndOr(LHSI, RHSPred, RHSOp0, RHSOp1, DL, LHSIsTrue,
10263 Depth);
10264 }
10265 return std::nullopt;
10266}
10267
10268std::optional<bool> llvm::isImpliedCondition(const Value *LHS, const Value *RHS,
10269 const DataLayout &DL,
10270 bool LHSIsTrue, unsigned Depth) {
10271 // LHS ==> RHS by definition
10272 if (LHS == RHS)
10273 return LHSIsTrue;
10274
10275 // Match not
10276 bool InvertRHS = false;
10277 if (match(RHS, m_Not(m_Value(RHS)))) {
10278 if (LHS == RHS)
10279 return !LHSIsTrue;
10280 InvertRHS = true;
10281 }
10282
10283 CmpPredicate RHSPred;
10284 Value *RHSOp0, *RHSOp1;
10285 if (match(RHS, m_ICmpLike(RHSPred, m_Value(RHSOp0), m_Value(RHSOp1)))) {
10286 if (auto Implied = isImpliedCondition(LHS, RHSPred, RHSOp0, RHSOp1, DL,
10287 LHSIsTrue, Depth))
10288 return InvertRHS ? !*Implied : *Implied;
10289 return std::nullopt;
10290 }
10291 if (const FCmpInst *RHSCmp = dyn_cast<FCmpInst>(RHS)) {
10292 if (auto Implied = isImpliedCondition(
10293 LHS, RHSCmp->getPredicate(), RHSCmp->getOperand(0),
10294 RHSCmp->getOperand(1), DL, LHSIsTrue, Depth))
10295 return InvertRHS ? !*Implied : *Implied;
10296 return std::nullopt;
10297 }
10298
10300 return std::nullopt;
10301
10302 // LHS ==> (RHS1 || RHS2) if LHS ==> RHS1 or LHS ==> RHS2
10303 // LHS ==> !(RHS1 && RHS2) if LHS ==> !RHS1 or LHS ==> !RHS2
10304 const Value *RHS1, *RHS2;
10305 if (match(RHS, m_LogicalOr(m_Value(RHS1), m_Value(RHS2)))) {
10306 if (std::optional<bool> Imp =
10307 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10308 if (*Imp == true)
10309 return !InvertRHS;
10310 if (std::optional<bool> Imp =
10311 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10312 if (*Imp == true)
10313 return !InvertRHS;
10314 }
10315 if (match(RHS, m_LogicalAnd(m_Value(RHS1), m_Value(RHS2)))) {
10316 if (std::optional<bool> Imp =
10317 isImpliedCondition(LHS, RHS1, DL, LHSIsTrue, Depth + 1))
10318 if (*Imp == false)
10319 return InvertRHS;
10320 if (std::optional<bool> Imp =
10321 isImpliedCondition(LHS, RHS2, DL, LHSIsTrue, Depth + 1))
10322 if (*Imp == false)
10323 return InvertRHS;
10324 }
10325
10326 return std::nullopt;
10327}
10328
10329// Returns a pair (Condition, ConditionIsTrue), where Condition is a branch
10330// condition dominating ContextI or nullptr, if no condition is found.
10331static std::pair<Value *, bool>
10333 if (!ContextI || !ContextI->getParent())
10334 return {nullptr, false};
10335
10336 // TODO: This is a poor/cheap way to determine dominance. Should we use a
10337 // dominator tree (eg, from a SimplifyQuery) instead?
10338 const BasicBlock *ContextBB = ContextI->getParent();
10339 const BasicBlock *PredBB = ContextBB->getSinglePredecessor();
10340 if (!PredBB)
10341 return {nullptr, false};
10342
10343 // We need a conditional branch in the predecessor.
10344 Value *PredCond;
10345 BasicBlock *TrueBB, *FalseBB;
10346 if (!match(PredBB->getTerminator(), m_Br(m_Value(PredCond), TrueBB, FalseBB)))
10347 return {nullptr, false};
10348
10349 // The branch should get simplified. Don't bother simplifying this condition.
10350 if (TrueBB == FalseBB)
10351 return {nullptr, false};
10352
10353 assert((TrueBB == ContextBB || FalseBB == ContextBB) &&
10354 "Predecessor block does not point to successor?");
10355
10356 // Is this condition implied by the predecessor condition?
10357 return {PredCond, TrueBB == ContextBB};
10358}
10359
10360std::optional<bool> llvm::isImpliedByDomCondition(const Value *Cond,
10361 const Instruction *ContextI,
10362 const DataLayout &DL) {
10363 assert(Cond->getType()->isIntOrIntVectorTy(1) && "Condition must be bool");
10364 auto PredCond = getDomPredecessorCondition(ContextI);
10365 if (PredCond.first)
10366 return isImpliedCondition(PredCond.first, Cond, DL, PredCond.second);
10367 return std::nullopt;
10368}
10369
10371 const Value *LHS,
10372 const Value *RHS,
10373 const Instruction *ContextI,
10374 const DataLayout &DL) {
10375 auto PredCond = getDomPredecessorCondition(ContextI);
10376 if (PredCond.first)
10377 return isImpliedCondition(PredCond.first, Pred, LHS, RHS, DL,
10378 PredCond.second);
10379 return std::nullopt;
10380}
10381
10383 APInt &Upper, const InstrInfoQuery &IIQ,
10384 bool PreferSignedRange) {
10385 unsigned Width = Lower.getBitWidth();
10386 const APInt *C;
10387 switch (BO.getOpcode()) {
10388 case Instruction::Sub:
10389 if (match(BO.getOperand(0), m_APInt(C))) {
10390 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10391 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10392
10393 // If the caller expects a signed compare, then try to use a signed range.
10394 // Otherwise if both no-wraps are set, use the unsigned range because it
10395 // is never larger than the signed range. Example:
10396 // "sub nuw nsw i8 -2, x" is unsigned [0, 254] vs. signed [-128, 126].
10397 // "sub nuw nsw i8 2, x" is unsigned [0, 2] vs. signed [-125, 127].
10398 if (PreferSignedRange && HasNSW && HasNUW)
10399 HasNUW = false;
10400
10401 if (HasNUW) {
10402 // 'sub nuw c, x' produces [0, C].
10403 Upper = *C + 1;
10404 } else if (HasNSW) {
10405 if (C->isNegative()) {
10406 // 'sub nsw -C, x' produces [SINT_MIN, -C - SINT_MIN].
10408 Upper = *C - APInt::getSignedMaxValue(Width);
10409 } else {
10410 // Note that sub 0, INT_MIN is not NSW. It techically is a signed wrap
10411 // 'sub nsw C, x' produces [C - SINT_MAX, SINT_MAX].
10412 Lower = *C - APInt::getSignedMaxValue(Width);
10414 }
10415 }
10416 }
10417 break;
10418 case Instruction::Add:
10419 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10420 bool HasNSW = IIQ.hasNoSignedWrap(&BO);
10421 bool HasNUW = IIQ.hasNoUnsignedWrap(&BO);
10422
10423 // If the caller expects a signed compare, then try to use a signed
10424 // range. Otherwise if both no-wraps are set, use the unsigned range
10425 // because it is never larger than the signed range. Example: "add nuw
10426 // nsw i8 X, -2" is unsigned [254,255] vs. signed [-128, 125].
10427 if (PreferSignedRange && HasNSW && HasNUW)
10428 HasNUW = false;
10429
10430 if (HasNUW) {
10431 // 'add nuw x, C' produces [C, UINT_MAX].
10432 Lower = *C;
10433 } else if (HasNSW) {
10434 if (C->isNegative()) {
10435 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
10437 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
10438 } else {
10439 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
10440 Lower = APInt::getSignedMinValue(Width) + *C;
10441 Upper = APInt::getSignedMaxValue(Width) + 1;
10442 }
10443 }
10444 }
10445 break;
10446
10447 case Instruction::And:
10448 if (match(BO.getOperand(1), m_APInt(C)))
10449 // 'and x, C' produces [0, C].
10450 Upper = *C + 1;
10451 // X & -X is a power of two or zero. So we can cap the value at max power of
10452 // two.
10453 if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
10454 match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
10455 Upper = APInt::getSignedMinValue(Width) + 1;
10456 break;
10457
10458 case Instruction::Or:
10459 if (match(BO.getOperand(1), m_APInt(C)))
10460 // 'or x, C' produces [C, UINT_MAX].
10461 Lower = *C;
10462 break;
10463
10464 case Instruction::AShr:
10465 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10466 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
10468 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
10469 } else if (match(BO.getOperand(0), m_APInt(C))) {
10470 unsigned ShiftAmount = Width - 1;
10471 if (!C->isZero() && IIQ.isExact(&BO))
10472 ShiftAmount = C->countr_zero();
10473 if (C->isNegative()) {
10474 // 'ashr C, x' produces [C, C >> (Width-1)]
10475 Lower = *C;
10476 Upper = C->ashr(ShiftAmount) + 1;
10477 } else {
10478 // 'ashr C, x' produces [C >> (Width-1), C]
10479 Lower = C->ashr(ShiftAmount);
10480 Upper = *C + 1;
10481 }
10482 }
10483 break;
10484
10485 case Instruction::LShr:
10486 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10487 // 'lshr x, C' produces [0, UINT_MAX >> C].
10488 Upper = APInt::getAllOnes(Width).lshr(*C) + 1;
10489 } else if (match(BO.getOperand(0), m_APInt(C))) {
10490 // 'lshr C, x' produces [C >> (Width-1), C].
10491 unsigned ShiftAmount = Width - 1;
10492 if (!C->isZero() && IIQ.isExact(&BO))
10493 ShiftAmount = C->countr_zero();
10494 Lower = C->lshr(ShiftAmount);
10495 Upper = *C + 1;
10496 }
10497 break;
10498
10499 case Instruction::Shl:
10500 if (match(BO.getOperand(0), m_APInt(C))) {
10501 if (IIQ.hasNoUnsignedWrap(&BO)) {
10502 // 'shl nuw C, x' produces [C, C << CLZ(C)]
10503 Lower = *C;
10504 Upper = Lower.shl(Lower.countl_zero()) + 1;
10505 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
10506 if (C->isNegative()) {
10507 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
10508 unsigned ShiftAmount = C->countl_one() - 1;
10509 Lower = C->shl(ShiftAmount);
10510 Upper = *C + 1;
10511 } else {
10512 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
10513 unsigned ShiftAmount = C->countl_zero() - 1;
10514 Lower = *C;
10515 Upper = C->shl(ShiftAmount) + 1;
10516 }
10517 } else {
10518 // If lowbit is set, value can never be zero.
10519 if ((*C)[0])
10520 Lower = APInt::getOneBitSet(Width, 0);
10521 // If we are shifting a constant the largest it can be is if the longest
10522 // sequence of consecutive ones is shifted to the highbits (breaking
10523 // ties for which sequence is higher). At the moment we take a liberal
10524 // upper bound on this by just popcounting the constant.
10525 // TODO: There may be a bitwise trick for it longest/highest
10526 // consecutative sequence of ones (naive method is O(Width) loop).
10527 Upper = APInt::getHighBitsSet(Width, C->popcount()) + 1;
10528 }
10529 } else if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
10530 Upper = APInt::getBitsSetFrom(Width, C->getZExtValue()) + 1;
10531 }
10532 break;
10533
10534 case Instruction::SDiv:
10535 if (match(BO.getOperand(1), m_APInt(C))) {
10536 APInt IntMin = APInt::getSignedMinValue(Width);
10537 APInt IntMax = APInt::getSignedMaxValue(Width);
10538 if (C->isAllOnes()) {
10539 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
10540 // where C != -1 and C != 0 and C != 1
10541 Lower = IntMin + 1;
10542 Upper = IntMax + 1;
10543 } else if (C->countl_zero() < Width - 1) {
10544 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
10545 // where C != -1 and C != 0 and C != 1
10546 Lower = IntMin.sdiv(*C);
10547 Upper = IntMax.sdiv(*C);
10548 if (Lower.sgt(Upper))
10550 Upper = Upper + 1;
10551 assert(Upper != Lower && "Upper part of range has wrapped!");
10552 }
10553 } else if (match(BO.getOperand(0), m_APInt(C))) {
10554 if (C->isMinSignedValue()) {
10555 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
10556 Lower = *C;
10557 Upper = Lower.lshr(1) + 1;
10558 } else {
10559 // 'sdiv C, x' produces [-|C|, |C|].
10560 Upper = C->abs() + 1;
10561 Lower = (-Upper) + 1;
10562 }
10563 }
10564 break;
10565
10566 case Instruction::UDiv:
10567 if (match(BO.getOperand(1), m_APInt(C)) && !C->isZero()) {
10568 // 'udiv x, C' produces [0, UINT_MAX / C].
10569 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
10570 } else if (match(BO.getOperand(0), m_APInt(C))) {
10571 // 'udiv C, x' produces [0, C].
10572 Upper = *C + 1;
10573 }
10574 break;
10575
10576 case Instruction::SRem:
10577 if (match(BO.getOperand(1), m_APInt(C))) {
10578 // 'srem x, C' produces (-|C|, |C|).
10579 Upper = C->abs();
10580 Lower = (-Upper) + 1;
10581 } else if (match(BO.getOperand(0), m_APInt(C))) {
10582 if (C->isNegative()) {
10583 // 'srem -|C|, x' produces [-|C|, 0].
10584 Upper = 1;
10585 Lower = *C;
10586 } else {
10587 // 'srem |C|, x' produces [0, |C|].
10588 Upper = *C + 1;
10589 }
10590 }
10591 break;
10592
10593 case Instruction::URem:
10594 if (match(BO.getOperand(1), m_APInt(C)))
10595 // 'urem x, C' produces [0, C).
10596 Upper = *C;
10597 else if (match(BO.getOperand(0), m_APInt(C)))
10598 // 'urem C, x' produces [0, C].
10599 Upper = *C + 1;
10600 break;
10601
10602 default:
10603 break;
10604 }
10605}
10606
10608 bool UseInstrInfo) {
10609 unsigned Width = II.getType()->getScalarSizeInBits();
10610 const APInt *C;
10611 switch (II.getIntrinsicID()) {
10612 case Intrinsic::ctlz:
10613 case Intrinsic::cttz: {
10614 APInt Upper(Width, Width);
10615 if (!UseInstrInfo || !match(II.getArgOperand(1), m_One()))
10616 Upper += 1;
10617 // Maximum of set/clear bits is the bit width.
10619 }
10620 case Intrinsic::ctpop:
10621 // Maximum of set/clear bits is the bit width.
10623 APInt(Width, Width) + 1);
10624 case Intrinsic::uadd_sat:
10625 // uadd.sat(x, C) produces [C, UINT_MAX].
10626 if (match(II.getOperand(0), m_APInt(C)) ||
10627 match(II.getOperand(1), m_APInt(C)))
10629 break;
10630 case Intrinsic::sadd_sat:
10631 if (match(II.getOperand(0), m_APInt(C)) ||
10632 match(II.getOperand(1), m_APInt(C))) {
10633 if (C->isNegative())
10634 // sadd.sat(x, -C) produces [SINT_MIN, SINT_MAX + (-C)].
10636 APInt::getSignedMaxValue(Width) + *C +
10637 1);
10638
10639 // sadd.sat(x, +C) produces [SINT_MIN + C, SINT_MAX].
10641 APInt::getSignedMaxValue(Width) + 1);
10642 }
10643 break;
10644 case Intrinsic::usub_sat:
10645 // usub.sat(C, x) produces [0, C].
10646 if (match(II.getOperand(0), m_APInt(C)))
10647 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10648
10649 // usub.sat(x, C) produces [0, UINT_MAX - C].
10650 if (match(II.getOperand(1), m_APInt(C)))
10652 APInt::getMaxValue(Width) - *C + 1);
10653 break;
10654 case Intrinsic::ssub_sat:
10655 if (match(II.getOperand(0), m_APInt(C))) {
10656 if (C->isNegative())
10657 // ssub.sat(-C, x) produces [SINT_MIN, -SINT_MIN + (-C)].
10659 *C - APInt::getSignedMinValue(Width) +
10660 1);
10661
10662 // ssub.sat(+C, x) produces [-SINT_MAX + C, SINT_MAX].
10664 APInt::getSignedMaxValue(Width) + 1);
10665 } else if (match(II.getOperand(1), m_APInt(C))) {
10666 if (C->isNegative())
10667 // ssub.sat(x, -C) produces [SINT_MIN - (-C), SINT_MAX]:
10669 APInt::getSignedMaxValue(Width) + 1);
10670
10671 // ssub.sat(x, +C) produces [SINT_MIN, SINT_MAX - C].
10673 APInt::getSignedMaxValue(Width) - *C +
10674 1);
10675 }
10676 break;
10677 case Intrinsic::umin:
10678 case Intrinsic::umax:
10679 case Intrinsic::smin:
10680 case Intrinsic::smax:
10681 if (!match(II.getOperand(0), m_APInt(C)) &&
10682 !match(II.getOperand(1), m_APInt(C)))
10683 break;
10684
10685 switch (II.getIntrinsicID()) {
10686 case Intrinsic::umin:
10687 return ConstantRange::getNonEmpty(APInt::getZero(Width), *C + 1);
10688 case Intrinsic::umax:
10690 case Intrinsic::smin:
10692 *C + 1);
10693 case Intrinsic::smax:
10695 APInt::getSignedMaxValue(Width) + 1);
10696 default:
10697 llvm_unreachable("Must be min/max intrinsic");
10698 }
10699 break;
10700 case Intrinsic::abs:
10701 // If abs of SIGNED_MIN is poison, then the result is [0..SIGNED_MAX],
10702 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10703 if (match(II.getOperand(1), m_One()))
10705 APInt::getSignedMaxValue(Width) + 1);
10706
10708 APInt::getSignedMinValue(Width) + 1);
10709 case Intrinsic::vscale:
10710 if (!II.getParent() || !II.getFunction())
10711 break;
10712 return getVScaleRange(II.getFunction(), Width);
10713 case Intrinsic::read_register:
10714 case Intrinsic::read_volatile_register: {
10715 const Module *M = II.getModule();
10716 if (!M || !M->getTargetTriple().isRISCV())
10717 break;
10718 if (II.getFunction() && isReadVLENB(II))
10719 return getRISCVVLENBRange(II, Width);
10720 break;
10721 }
10722 default:
10723 break;
10724 }
10725
10726 return ConstantRange::getFull(Width);
10727}
10728
10730 const InstrInfoQuery &IIQ) {
10731 unsigned BitWidth = SI.getType()->getScalarSizeInBits();
10732 const Value *LHS = nullptr, *RHS = nullptr;
10734 if (R.Flavor == SPF_UNKNOWN)
10735 return ConstantRange::getFull(BitWidth);
10736
10737 if (R.Flavor == SelectPatternFlavor::SPF_ABS) {
10738 // If the negation part of the abs (in RHS) has the NSW flag,
10739 // then the result of abs(X) is [0..SIGNED_MAX],
10740 // otherwise it is [0..SIGNED_MIN], as -SIGNED_MIN == SIGNED_MIN.
10741 if (match(RHS, m_Neg(m_Specific(LHS))) &&
10745
10748 }
10749
10750 if (R.Flavor == SelectPatternFlavor::SPF_NABS) {
10751 // The result of -abs(X) is <= 0.
10753 APInt(BitWidth, 1));
10754 }
10755
10756 const APInt *C;
10757 if (!match(LHS, m_APInt(C)) && !match(RHS, m_APInt(C)))
10758 return ConstantRange::getFull(BitWidth);
10759
10760 switch (R.Flavor) {
10761 case SPF_UMIN:
10763 case SPF_UMAX:
10765 case SPF_SMIN:
10767 *C + 1);
10768 case SPF_SMAX:
10771 default:
10772 return ConstantRange::getFull(BitWidth);
10773 }
10774}
10775
10777 // The maximum representable value of a half is 65504. For floats the maximum
10778 // value is 3.4e38 which requires roughly 129 bits.
10779 unsigned BitWidth = I->getType()->getScalarSizeInBits();
10780 if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
10781 return;
10782 if (isa<FPToSIInst>(I) && BitWidth >= 17) {
10783 Lower = APInt(BitWidth, -65504, true);
10784 Upper = APInt(BitWidth, 65505);
10785 }
10786
10787 if (isa<FPToUIInst>(I) && BitWidth >= 16) {
10788 // For a fptoui the lower limit is left as 0.
10789 Upper = APInt(BitWidth, 65505);
10790 }
10791}
10792
10794 const SimplifyQuery &SQ,
10795 unsigned Depth) {
10796 assert(V->getType()->isIntOrIntVectorTy() && "Expected integer instruction");
10797
10799 return ConstantRange::getFull(V->getType()->getScalarSizeInBits());
10800
10801 if (auto *C = dyn_cast<Constant>(V))
10802 return C->toConstantRange();
10803
10804 unsigned BitWidth = V->getType()->getScalarSizeInBits();
10805 ConstantRange CR = ConstantRange::getFull(BitWidth);
10806 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
10807 APInt Lower = APInt(BitWidth, 0);
10808 APInt Upper = APInt(BitWidth, 0);
10809 // TODO: Return ConstantRange.
10810 setLimitsForBinOp(*BO, Lower, Upper, SQ.IIQ, ForSigned);
10812 } else if (auto *II = dyn_cast<IntrinsicInst>(V))
10814 else if (auto *SI = dyn_cast<SelectInst>(V)) {
10815 ConstantRange CRTrue =
10816 computeConstantRange(SI->getTrueValue(), ForSigned, SQ, Depth + 1);
10817 ConstantRange CRFalse =
10818 computeConstantRange(SI->getFalseValue(), ForSigned, SQ, Depth + 1);
10819 CR = CRTrue.unionWith(CRFalse);
10821 } else if (auto *TI = dyn_cast<TruncInst>(V)) {
10822 ConstantRange SrcCR =
10823 computeConstantRange(TI->getOperand(0), ForSigned, SQ, Depth + 1);
10824 CR = SrcCR.truncate(BitWidth);
10825 } else if (auto *ZExt = dyn_cast<ZExtInst>(V)) {
10826 ConstantRange SrcCR =
10827 computeConstantRange(ZExt->getOperand(0), ForSigned, SQ, Depth + 1);
10828 CR = SrcCR.zeroExtend(BitWidth);
10829 } else if (auto *SExt = dyn_cast<SExtInst>(V)) {
10830 ConstantRange SrcCR =
10831 computeConstantRange(SExt->getOperand(0), ForSigned, SQ, Depth + 1);
10832 CR = SrcCR.signExtend(BitWidth);
10833 } else if (isa<FPToUIInst>(V) || isa<FPToSIInst>(V)) {
10834 APInt Lower = APInt(BitWidth, 0);
10835 APInt Upper = APInt(BitWidth, 0);
10836 // TODO: Return ConstantRange.
10839 } else if (const auto *A = dyn_cast<Argument>(V))
10840 if (std::optional<ConstantRange> Range = A->getRange())
10841 CR = *Range;
10842
10843 if (auto *I = dyn_cast<Instruction>(V)) {
10844 if (auto *Range = SQ.IIQ.getMetadata(I, LLVMContext::MD_range))
10846
10847 Value *FrexpSrc;
10848 if (const auto *CB = dyn_cast<CallBase>(V)) {
10849 if (std::optional<ConstantRange> Range = CB->getRange())
10850 CR = CR.intersectWith(*Range);
10852 m_Value(FrexpSrc))))) {
10853 const fltSemantics &FltSem =
10854 FrexpSrc->getType()->getScalarType()->getFltSemantics();
10855 // It should be possible to implement this for any type, but this logic
10856 // only computes the range assuming standard subnormal handling.
10857 if (APFloat::isIEEELikeFP(FltSem)) {
10859 FrexpSrc, fcSubnormal | fcZero | fcNan | fcInf, SQ, Depth + 1);
10860
10861 // The exponent of frexp(NaN) and frexp(Inf) is unspecified. Only
10862 // constrain its range when the source can be neither.
10863 if (KnownSrc.isKnownNeverInfOrNaN()) {
10864 int MinExp = APFloat::semanticsMinExponent(FltSem) + 1;
10865
10866 // Offset to find the true minimum exponent value for a denormal.
10867 if (!KnownSrc.isKnownNeverSubnormal())
10868 MinExp -= (APFloat::semanticsPrecision(FltSem) - 1);
10869
10870 int MaxExp = APFloat::semanticsMaxExponent(FltSem) + 1;
10871
10872 auto [AdjustedMin, AdjustedMax, AdjustedMaxNonZero] =
10874
10875 DenormalMode Mode = I->getFunction()->getDenormalMode(FltSem);
10876 bool NeverLogicalZero = KnownSrc.isKnownNeverLogicalZero(Mode);
10877
10878 MinExp = std::max(AdjustedMin, MinExp);
10879 MaxExp = std::min(NeverLogicalZero ? AdjustedMaxNonZero : AdjustedMax,
10880 MaxExp);
10881
10883 APInt(BitWidth, static_cast<int64_t>(MinExp), /*isSigned=*/true),
10884 APInt(BitWidth, static_cast<int64_t>(MaxExp) + 1,
10885 /*isSigned=*/true));
10886 }
10887 }
10888 }
10889 }
10890
10891 if (SQ.CtxI && SQ.AC) {
10892 // Try to restrict the range based on information from assumptions.
10893 for (auto &AssumeVH : SQ.AC->assumptionsFor(V)) {
10894 if (!AssumeVH)
10895 continue;
10896 CallInst *I = cast<CallInst>(AssumeVH);
10897 assert(I->getParent()->getParent() == SQ.CtxI->getParent()->getParent() &&
10898 "Got assumption for the wrong function!");
10899 assert(I->getIntrinsicID() == Intrinsic::assume &&
10900 "must be an assume intrinsic");
10901
10902 if (!isValidAssumeForContext(I, SQ))
10903 continue;
10904 Value *Arg = I->getArgOperand(0);
10905 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
10906 // Currently we just use information from comparisons.
10907 if (!Cmp || Cmp->getOperand(0) != V)
10908 continue;
10909 // TODO: Set "ForSigned" parameter via Cmp->isSigned()?
10910 ConstantRange RHS =
10911 computeConstantRange(Cmp->getOperand(1), /*ForSigned=*/false,
10912 SQ.getWithInstruction(I), Depth + 1);
10913 CR = CR.intersectWith(
10914 ConstantRange::makeAllowedICmpRegion(Cmp->getCmpPredicate(), RHS));
10915 }
10916 }
10917
10918 return CR;
10919}
10920
10921static void
10923 function_ref<void(Value *)> InsertAffected) {
10924 assert(V != nullptr);
10925 if (isa<Argument>(V) || isa<GlobalValue>(V)) {
10926 InsertAffected(V);
10927 } else if (auto *I = dyn_cast<Instruction>(V)) {
10928 InsertAffected(V);
10929
10930 // Peek through unary operators to find the source of the condition.
10931 Value *Op;
10933 m_Trunc(m_Value(Op))))) {
10935 InsertAffected(Op);
10936 }
10937 }
10938}
10939
10941 Value *Cond, bool IsAssume, function_ref<void(Value *)> InsertAffected) {
10942 auto AddAffected = [&InsertAffected](Value *V) {
10943 addValueAffectedByCondition(V, InsertAffected);
10944 };
10945
10946 auto AddCmpOperands = [&AddAffected, IsAssume](Value *LHS, Value *RHS) {
10947 if (IsAssume) {
10948 AddAffected(LHS);
10949 AddAffected(RHS);
10950 } else if (match(RHS, m_Constant()))
10951 AddAffected(LHS);
10952 };
10953
10954 SmallVector<Value *, 8> Worklist;
10956 Worklist.push_back(Cond);
10957 while (!Worklist.empty()) {
10958 Value *V = Worklist.pop_back_val();
10959 if (!Visited.insert(V).second)
10960 continue;
10961
10962 CmpPredicate Pred;
10963 Value *A, *B, *X;
10964
10965 if (IsAssume) {
10966 AddAffected(V);
10967 if (match(V, m_Not(m_Value(X))))
10968 AddAffected(X);
10969 }
10970
10971 if (match(V, m_LogicalOp(m_Value(A), m_Value(B)))) {
10972 // assume(A && B) is split to -> assume(A); assume(B);
10973 // assume(!(A || B)) is split to -> assume(!A); assume(!B);
10974 // Finally, assume(A || B) / assume(!(A && B)) generally don't provide
10975 // enough information to be worth handling (intersection of information as
10976 // opposed to union).
10977 if (!IsAssume) {
10978 Worklist.push_back(A);
10979 Worklist.push_back(B);
10980 }
10981 } else if (match(V, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
10982 bool HasRHSC = match(B, m_ConstantInt());
10983 if (ICmpInst::isEquality(Pred)) {
10984 AddAffected(A);
10985 if (IsAssume)
10986 AddAffected(B);
10987 if (HasRHSC) {
10988 Value *Y;
10989 // (X << C) or (X >>_s C) or (X >>_u C).
10990 if (match(A, m_Shift(m_Value(X), m_ConstantInt())))
10991 AddAffected(X);
10992 // (X & C) or (X | C).
10993 else if (match(A, m_And(m_Value(X), m_Value(Y))) ||
10994 match(A, m_Or(m_Value(X), m_Value(Y)))) {
10995 AddAffected(X);
10996 AddAffected(Y);
10997 }
10998 // X - Y
10999 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11000 AddAffected(X);
11001 AddAffected(Y);
11002 }
11003 }
11004 } else {
11005 AddCmpOperands(A, B);
11006 if (HasRHSC) {
11007 Value *Y;
11008 // Handle (A + C1) u< C2, which is the canonical form of
11009 // A > C3 && A < C4.
11011 AddAffected(X);
11012 // X - Y pred C, which implies X != Y if 0 pred C is false.
11013 else if (match(A, m_Sub(m_Value(X), m_Value(Y)))) {
11014 AddAffected(X);
11015 AddAffected(Y);
11016 }
11017
11018 if (ICmpInst::isUnsigned(Pred)) {
11019 // X & Y u> C -> X >u C && Y >u C
11020 // X | Y u< C -> X u< C && Y u< C
11021 // X nuw+ Y u< C -> X u< C && Y u< C
11022 if (match(A, m_And(m_Value(X), m_Value(Y))) ||
11023 match(A, m_Or(m_Value(X), m_Value(Y))) ||
11024 match(A, m_NUWAdd(m_Value(X), m_Value(Y)))) {
11025 AddAffected(X);
11026 AddAffected(Y);
11027 }
11028 }
11029 }
11030
11031 // Handle icmp slt/sgt (bitcast X to int), 0/-1, which is supported
11032 // by computeKnownFPClass().
11034 if (Pred == ICmpInst::ICMP_SLT && match(B, m_Zero()))
11035 InsertAffected(X);
11036 else if (Pred == ICmpInst::ICMP_SGT && match(B, m_AllOnes()))
11037 InsertAffected(X);
11038 }
11039 }
11040
11041 auto AddNuwSquareOperand = [&AddAffected](Value *Op) {
11042 Value *SquareOp = nullptr;
11043 if (match(Op, m_NUWMul(m_Value(SquareOp), m_Deferred(SquareOp))))
11044 AddAffected(SquareOp);
11045 };
11046 AddNuwSquareOperand(A);
11047 AddNuwSquareOperand(B);
11048
11049 if (HasRHSC && match(A, m_Ctpop(m_Value(X))))
11050 AddAffected(X);
11051 } else if (match(V, m_FCmp(Pred, m_Value(A), m_Value(B)))) {
11052 AddCmpOperands(A, B);
11053
11054 // fcmp fneg(x), y
11055 // fcmp fabs(x), y
11056 // fcmp fneg(fabs(x)), y
11057 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
11059 AddAffected(A);
11060 if (match(A, m_FAbs(m_Value(A))))
11061 AddAffected(A);
11062
11064 m_Value()))) {
11065 // Handle patterns that computeKnownFPClass() support.
11066 AddAffected(A);
11067 } else if (!IsAssume && match(V, m_Trunc(m_Value(X)))) {
11068 // Assume is checked here as X is already added above for assumes in
11069 // addValueAffectedByCondition
11070 AddAffected(X);
11071 } else if (!IsAssume && match(V, m_Not(m_Value(X)))) {
11072 // Assume is checked here to avoid issues with ephemeral values
11073 Worklist.push_back(X);
11074 }
11075 }
11076}
11077
11079 // (X >> C) or/add (X & mask(C) != 0)
11080 if (const auto *BO = dyn_cast<BinaryOperator>(V)) {
11081 if (BO->getOpcode() == Instruction::Add ||
11082 BO->getOpcode() == Instruction::Or) {
11083 const Value *X;
11084 const APInt *C1, *C2;
11085 if (match(BO, m_c_BinOp(m_LShr(m_Value(X), m_APInt(C1)),
11089 m_Zero())))) &&
11090 C2->popcount() == C1->getZExtValue())
11091 return X;
11092 }
11093 }
11094
11095 // select(cond, X, -X)
11096 {
11097 const Value *X;
11098 if (match(V, m_c_Select(m_Value(X), m_Neg(m_Deferred(X)))))
11099 return X;
11100 }
11101
11102 return nullptr;
11103}
11104
11106 return const_cast<Value *>(stripNullTest(const_cast<const Value *>(V)));
11107}
11108
11111 unsigned MaxCount, bool AllowUndefOrPoison) {
11114 auto Push = [&](const Value *V) -> bool {
11115 Constant *C;
11116 if (match(const_cast<Value *>(V), m_ImmConstant(C))) {
11117 if (!AllowUndefOrPoison && !isGuaranteedNotToBeUndefOrPoison(C))
11118 return false;
11119 // Check existence first to avoid unnecessary allocations.
11120 if (Constants.contains(C))
11121 return true;
11122 if (Constants.size() == MaxCount)
11123 return false;
11124 Constants.insert(C);
11125 return true;
11126 }
11127
11128 if (auto *Inst = dyn_cast<Instruction>(V)) {
11129 if (Visited.insert(Inst).second)
11130 Worklist.push_back(Inst);
11131 return true;
11132 }
11133 return false;
11134 };
11135 if (!Push(V))
11136 return false;
11137 while (!Worklist.empty()) {
11138 const Instruction *CurInst = Worklist.pop_back_val();
11139 switch (CurInst->getOpcode()) {
11140 case Instruction::Select:
11141 if (!Push(CurInst->getOperand(1)))
11142 return false;
11143 if (!Push(CurInst->getOperand(2)))
11144 return false;
11145 break;
11146 case Instruction::PHI:
11147 for (Value *IncomingValue : cast<PHINode>(CurInst)->incoming_values()) {
11148 // Fast path for recurrence PHI.
11149 if (IncomingValue == CurInst)
11150 continue;
11151 if (!Push(IncomingValue))
11152 return false;
11153 }
11154 break;
11155 default:
11156 return false;
11157 }
11158 }
11159 return true;
11160}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Function Alias Analysis Results
This file contains the simple types necessary to represent the attributes associated with functions a...
static const Function * getParent(const Value *V)
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Utilities for dealing with flags related to floating point properties and mode controls.
static Value * getCondition(Instruction *I)
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
Module.h This file contains the declarations for the Module class.
static bool hasNoUnsignedWrap(BinaryOperator &I)
#define RegName(no)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
uint64_t IntrinsicInst * II
#define P(N)
PowerPC Reduce CR logical Operation
R600 Clause Merge
SmallVector< MachineOperand, 4 > Cond
int64_t C1
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
std::pair< BasicBlock *, BasicBlock * > Edge
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file contains the UndefPoisonKind enum and helper functions.
static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero, SimplifyQuery &Q, unsigned Depth)
Try to detect a recurrence that the value of the induction variable is always a power of two (or zero...
static cl::opt< unsigned > DomConditionsMaxUses("dom-conditions-max-uses", cl::Hidden, cl::init(20))
static unsigned computeNumSignBitsVectorConstant(const Value *V, const APInt &DemandedElts, unsigned TyBits)
For vector constants, loop over the elements and find the constant with the minimum number of sign bi...
static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS, const Value *RHS)
Return true if "icmp Pred LHS RHS" is always true.
static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V1 == (binop V2, X), where X is known non-zero.
static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q, unsigned Depth)
Test whether a GEP's result is known to be non-null.
static bool isNonEqualShl(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and the shift is nuw or nsw.
static bool isKnownNonNullFromDominatingCondition(const Value *V, const Instruction *CtxI, const DominatorTree *DT)
static const Value * getUnderlyingObjectFromInt(const Value *V)
This is the function that does the work of looking through basic ptrtoint+arithmetic+inttoptr sequenc...
static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool rangeMetadataExcludesValue(const MDNode *Ranges, const APInt &Value)
Does the 'Range' metadata (which must be a valid MD_range operand list) ensure that the value it's at...
static KnownBits getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &Q, unsigned Depth)
static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI, Value *&ValOut, Instruction *&CtxIOut, const PHINode **PhiOut=nullptr)
static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, unsigned Depth)
static const Instruction * safeCtxI(const Value *V, const Instruction *CtxI)
static OverflowResult mapOverflowResult(ConstantRange::OverflowResult OR)
Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
static void addValueAffectedByCondition(Value *V, function_ref< void(Value *)> InsertAffected)
static bool isNonZeroAddrPlusOffset(const SimplifyQuery &Q, Value *X, Value *Y)
Return true if "addr(P) + Off" cannot be zero.
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower, APInt &Upper, const InstrInfoQuery &IIQ, bool PreferSignedRange)
static Value * lookThroughCast(CmpInst *CmpI, Value *V1, Value *V2, Instruction::CastOps *CastOp)
Helps to match a select pattern in case of a type mismatch.
static std::pair< Value *, bool > getDomPredecessorCondition(const Instruction *ContextI)
static constexpr unsigned MaxInstrsToCheckForFree
Maximum number of instructions to check between assume and context instruction.
static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, const KnownBits &KnownVal, unsigned Depth)
static bool hasNoFreeInRange(BasicBlock::const_iterator Begin, BasicBlock::const_iterator End, unsigned &NumChecked)
static std::optional< bool > isImpliedCondFCmps(FCmpInst::Predicate LPred, const Value *L0, const Value *L1, FCmpInst::Predicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static ConstantRange getRISCVVLENBRange(const IntrinsicInst &II, unsigned Width)
Return the value range of a RISC-V vlenb CSR read.
static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2, const SimplifyQuery &Q, unsigned Depth)
static SelectPatternResult matchFastFloatClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match clamp pattern for float types without care about NaNs or signed zeros.
static std::optional< bool > isImpliedCondICmps(CmpPredicate LPred, const Value *L0, const Value *L1, CmpPredicate RPred, const Value *R0, const Value *R1, const DataLayout &DL, bool LHSIsTrue)
Return true if LHS implies RHS (expanded to its components as "R0 RPred R1") is true.
static std::optional< bool > isImpliedCondCommonOperandWithCR(CmpPredicate LPred, const ConstantRange &LCR, CmpPredicate RPred, const ConstantRange &RCR)
Return true if "icmp LPred X, LCR" implies "icmp RPred X, RCR" is true.
static SelectPatternResult matchMinMax(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS)
Match non-obvious integer minimum and maximum sequences.
static ConstantRange getRangeForSelectPattern(const SelectInst &SI, const InstrInfoQuery &IIQ)
static void computeKnownBitsFromOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth)
static uint64_t GetStringLengthH(const Value *V, SmallPtrSetImpl< const PHINode * > &PHIs, unsigned CharSize)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
static void computeKnownBitsFromShiftOperator(const Operator *I, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth, function_ref< KnownBits(const KnownBits &, const KnownBits &, bool)> KF)
Compute known bits from a shift operator, including those with a non-constant shift amount.
static void computeKnownFPClassFromCond(const Value *V, Value *Cond, bool CondIsTrue, const Instruction *CtxI, KnownFPClass &KnownFromContext, unsigned Depth=0)
static std::optional< bool > isImpliedCondAndOr(const Instruction *LHS, CmpPredicate RHSPred, const Value *RHSOp0, const Value *RHSOp1, const DataLayout &DL, bool LHSIsTrue, unsigned Depth)
Return true if LHS implies RHS is true.
static std::tuple< int, int, int > computeKnownExponentRangeFromContext(const Value *V, const SimplifyQuery &Q)
Compute the minimum and maximum values (inclusive) for the exponent of V, assuming it is not nan.
static bool isSignedMinMaxClamp(const Value *Select, const Value *&In, const APInt *&CLow, const APInt *&CHigh)
static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q, unsigned BitWidth, Value *X, Value *Y, bool NSW, bool NUW, unsigned Depth)
static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V, unsigned Depth)
static bool isNonEqualSelect(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchTwoInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp)
static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static void computeKnownBitsFromCmp(const Value *V, CmpInst::Predicate Pred, Value *LHS, Value *RHS, KnownBits &Known, const SimplifyQuery &Q)
static void unionWithMinMaxIntrinsicClamp(const IntrinsicInst *II, KnownBits &Known)
static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper)
static bool isSameUnderlyingObjectInLoop(const PHINode *PN, const LoopInfo *LI)
PN defines a loop-variant pointer to an object.
static bool isNonEqualPointersWithRecursiveGEP(const Value *A, const Value *B, const SimplifyQuery &Q)
static bool isSignedMinMaxIntrinsicClamp(const IntrinsicInst *II, const APInt *&CLow, const APInt *&CHigh)
static Value * lookThroughCastConst(CmpInst *CmpI, Type *SrcTy, Constant *C, Instruction::CastOps *CastOp)
static bool handleGuaranteedWellDefinedOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be undef or poison.
static bool isAbsoluteValueULEOne(const Value *V)
static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1, const APInt &DemandedElts, KnownBits &KnownOut, const SimplifyQuery &Q, unsigned Depth)
Try to detect the lerp pattern: a * (b - c) + c * d where a >= 0, b >= 0, c >= 0, d >= 0,...
static KnownFPClass computeKnownFPClassFromContext(const Value *V, const SimplifyQuery &Q)
static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &KnownOut, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static Value * getNotValue(Value *V)
If the input value is the result of a 'not' op, constant integer, or vector splat of a constant integ...
static constexpr KnownFPClass::MinMaxKind getMinMaxKind(Intrinsic::ID IID)
static bool isReadVLENB(const IntrinsicInst &II)
Return true if II reads a register named "vlenb".
static unsigned ComputeNumSignBitsImpl(const Value *V, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return the number of times the sign bit of the register is replicated into the other bits.
static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp, KnownBits &Known, const SimplifyQuery &SQ, bool Invert)
static bool isKnownNonZeroFromOperator(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
static bool matchOpWithOpEqZero(Value *Op0, Value *Op1)
static bool isNonZeroRecurrence(const PHINode *PN)
Try to detect a recurrence that monotonically increases/decreases from a non-zero starting value.
static SelectPatternResult matchClamp(CmpInst::Predicate Pred, Value *CmpLHS, Value *CmpRHS, Value *TrueVal, Value *FalseVal)
Recognize variations of: CLAMP(v,l,h) ==> ((v) < (l) ?
static bool shiftAmountKnownInRange(const Value *ShiftAmount)
Shifts return poison if shiftwidth is larger than the bitwidth.
static bool isEphemeralValueOf(const Instruction *I, const Value *E)
static void computeKnownBitsForRecurrenceOperands(const PHINode *P, Value *Start, Value *Step, const APInt &DemandedElts, KnownBits &KnownStart, KnownBits &KnownStep, const SimplifyQuery &Q, unsigned Depth)
static KnownBits computeKnownBitsForHorizontalOperation(const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth, const function_ref< KnownBits(const KnownBits &, const KnownBits &)> KnownBitsFunc)
static bool handleGuaranteedNonPoisonOps(const Instruction *I, const CallableT &Handle)
Enumerates all operands of I that are guaranteed to not be poison.
static std::optional< std::pair< Value *, Value * > > getInvertibleOperands(const Operator *Op1, const Operator *Op2)
If the pair of operators are the same invertible function, return the the operands of the function co...
static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS)
static void computeKnownBitsFromCond(const Value *V, Value *Cond, KnownBits &Known, const SimplifyQuery &SQ, bool Invert, unsigned Depth)
static NoCommonBitsSetResult haveNoCommonBitsSetSpecialCases(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q)
static std::optional< bool > isImpliedCondOperands(CmpInst::Predicate Pred, const Value *ALHS, const Value *ARHS, const Value *BLHS, const Value *BRHS)
Return true if "icmp Pred BLHS BRHS" is true whenever "icmp PredALHS ARHS" is true.
static bool isNonEqualMul(const Value *V1, const Value *V2, const APInt &DemandedElts, const SimplifyQuery &Q, unsigned Depth)
Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and the multiplication is nuw o...
static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero, const Value *Cond, bool CondIsTrue)
Return true if we can infer that V is known to be a power of 2 from dominating condition Cond (e....
static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW, bool NUW, const APInt &DemandedElts, KnownBits &Known, KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth)
static bool matchThreeInputRecurrence(const PHINode *PN, InstTy *&Inst, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
static bool isKnownNonNaN(const Value *V, FastMathFlags FMF)
static bool isNonEqualURem(const Value *X, const Value *Rem, const SimplifyQuery &Q)
static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II, bool UseInstrInfo)
static void computeKnownFPClassForFPTrunc(const Operator *Op, const APInt &DemandedElts, FPClassTest InterestedClasses, KnownFPClass &Known, const SimplifyQuery &Q, unsigned Depth)
static Value * BuildSubAggregate(Value *From, Value *To, Type *IndexedType, SmallVectorImpl< unsigned > &Idxs, unsigned IdxSkip, BasicBlock::iterator InsertBefore)
Value * RHS
Value * LHS
static LLVM_ABI bool semanticsHasInf(const fltSemantics &)
Definition APFloat.cpp:367
static LLVM_ABI ExponentType semanticsMinExponent(const fltSemantics &)
Definition APFloat.cpp:342
static LLVM_ABI bool semanticsHasSignedRepr(const fltSemantics &)
Definition APFloat.cpp:363
static LLVM_ABI ExponentType semanticsMaxExponent(const fltSemantics &)
Definition APFloat.cpp:338
static LLVM_ABI unsigned int semanticsPrecision(const fltSemantics &)
Definition APFloat.cpp:334
static LLVM_ABI bool semanticsHasNaN(const fltSemantics &)
Definition APFloat.cpp:371
static LLVM_ABI bool semanticsHasZero(const fltSemantics &)
Definition APFloat.cpp:359
static LLVM_ABI bool isRepresentableAsNormalIn(const fltSemantics &Src, const fltSemantics &Dst)
Definition APFloat.cpp:384
static LLVM_ABI bool isIEEELikeFP(const fltSemantics &)
Definition APFloat.cpp:375
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:6165
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 isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
static APInt getMinValue(unsigned numBits)
Gets minimum unsigned value of APInt for a specific bit width.
Definition APInt.h:212
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool intersects(const APInt &RHS) const
This operation tests if there are any pairs of corresponding bits between this APInt and RHS that are...
Definition APInt.h:1253
LLVM_ABI APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Definition APInt.cpp:1673
LLVM_ABI APInt reverseBits() const
Definition APInt.cpp:786
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition APInt.h:1170
unsigned getNumSignBits() const
Computes the number of leading bits of this APInt that are equal to its sign bit.
Definition APInt.h:1648
unsigned countl_zero() const
The APInt version of std::countl_zero.
Definition APInt.h:1618
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition APInt.h:215
LLVM_ABI APInt sextOrTrunc(unsigned width) const
Sign extend or truncate to width.
Definition APInt.cpp:1086
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
Definition APInt.h:352
unsigned logBase2() const
Definition APInt.h:1781
APInt ashr(unsigned ShiftAmt) const
Arithmetic right-shift function.
Definition APInt.h:829
bool getBoolValue() const
Convert APInt to a boolean value.
Definition APInt.h:467
bool isMaxSignedValue() const
Determine if this is the largest signed value.
Definition APInt.h:401
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
Definition APInt.h:330
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition APInt.h:1154
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition APInt.h:1261
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
void setLowBits(unsigned loBits)
Set the bottom loBits bits.
Definition APInt.h:1408
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition APInt.h:1241
static APInt getBitsSetFrom(unsigned numBits, unsigned loBit)
Constructs an APInt value that has a contiguous range of bits set.
Definition APInt.h:282
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
an instruction to allocate memory on the stack
This class represents an incoming formal argument to a Function.
Definition Argument.h:32
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
Class to represent array types.
This represents the llvm.assume intrinsic.
A cache of @llvm.assume calls within a function.
MutableArrayRef< ResultElem > assumptionsFor(const Value *V)
Access the list of assumptions which affect this value.
Functions, function parameters, and return types can have attributes to indicate how they should be t...
Definition Attributes.h:106
LLVM_ABI std::optional< unsigned > getVScaleRangeMax() const
Returns the maximum value for the vscale_range attribute or std::nullopt when unknown.
LLVM_ABI unsigned getVScaleRangeMin() const
Returns the minimum value for the vscale_range attribute.
bool isValid() const
Return true if the attribute is any kind of attribute.
Definition Attributes.h:262
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI InstListType::const_iterator getFirstNonPHIIt() const
Returns an iterator to the first instruction in this block that is not a PHINode instruction.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Function * getCalledFunction() const
Returns the function called, or null if this is an indirect function invocation or the function signa...
LLVM_ABI bool paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const
Determine whether the argument or parameter has the given attribute.
LLVM_ABI bool isIndirectCall() const
Return true if the callsite is an indirect call.
bool onlyReadsMemory(unsigned OpNo) const
Value * getCalledOperand() const
Value * getArgOperand(unsigned i) const
LLVM_ABI Intrinsic::ID getIntrinsicID() const
Returns the intrinsic ID of the intrinsic called or Intrinsic::not_intrinsic if the called function i...
unsigned arg_size() const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI Predicate getFlippedStrictnessPredicate(Predicate pred)
This is a static version that you can use without an instruction available.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ FCMP_OEQ
0 0 0 1 True if ordered and equal
Definition InstrTypes.h:743
@ FCMP_TRUE
1 1 1 1 Always true (always folded)
Definition InstrTypes.h:757
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ FCMP_OLT
0 1 0 0 True if ordered and less than
Definition InstrTypes.h:746
@ FCMP_ULE
1 1 0 1 True if unordered, less than, or equal
Definition InstrTypes.h:755
@ FCMP_OGT
0 0 1 0 True if ordered and greater than
Definition InstrTypes.h:744
@ FCMP_OGE
0 0 1 1 True if ordered and greater than or equal
Definition InstrTypes.h:745
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ FCMP_ULT
1 1 0 0 True if unordered or less than
Definition InstrTypes.h:754
@ FCMP_UEQ
1 0 0 1 True if unordered or equal
Definition InstrTypes.h:751
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ FCMP_UGT
1 0 1 0 True if unordered or greater than
Definition InstrTypes.h:752
@ FCMP_OLE
0 1 0 1 True if ordered and less than or equal
Definition InstrTypes.h:747
@ FCMP_ORD
0 1 1 1 True if ordered (no nans)
Definition InstrTypes.h:749
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
@ FCMP_UGE
1 0 1 1 True if unordered, greater than, or equal
Definition InstrTypes.h:753
@ FCMP_FALSE
0 0 0 0 Always false (always folded)
Definition InstrTypes.h:742
@ FCMP_UNO
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
Definition InstrTypes.h:750
bool isSigned() const
Definition InstrTypes.h:993
static LLVM_ABI bool isEquality(Predicate pred)
Determine if this is an equals/not equals predicate.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
bool isTrueWhenEqual() const
This is just a convenience.
static bool isFPPredicate(Predicate P)
Definition InstrTypes.h:833
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
static bool isIntPredicate(Predicate P)
Definition InstrTypes.h:839
static LLVM_ABI bool isOrdered(Predicate predicate)
Determine if the predicate is an ordered operation.
bool isUnsigned() const
Definition InstrTypes.h:999
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
LLVM_ABI CmpInst::Predicate getPreferredSignedPredicate() const
Attempts to return a signed CmpInst::Predicate from the CmpPredicate.
CmpInst::Predicate dropSameSign() const
Drops samesign information.
bool hasSameSign() const
Query samesign information, for optimizations.
Conditional Branch instruction.
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
ConstantDataSequential - A vector or array constant whose element type is a simple 1/2/4/8-byte integ...
Definition Constants.h:755
StringRef getAsString() const
If this array is isString(), then this method returns the array as a StringRef.
Definition Constants.h:831
A vector constant whose element type is a simple 1/2/4/8-byte integer or float/double,...
Definition Constants.h:951
static LLVM_ABI Constant * getAdd(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI std::optional< ConstantFPRange > makeExactFCmpRegion(FCmpInst::Predicate Pred, const APFloat &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
ConstantFP - Floating Point Values [float, double].
Definition Constants.h:420
This is the shared class of boolean and integer constants.
Definition Constants.h:87
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
This class represents a range of values.
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
static LLVM_ABI ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned)
Initialize a range based on a known bits constraint.
LLVM_ABI OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const
Return whether unsigned sub of the two ranges always/never overflows.
LLVM_ABI bool isAllNegative() const
Return true if all values in this range are negative.
LLVM_ABI OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const
Return whether unsigned add of the two ranges always/never overflows.
LLVM_ABI KnownBits toKnownBits() const
Return known bits for values in this range.
LLVM_ABI bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const
Does the predicate Pred hold between ranges this and Other?
LLVM_ABI ConstantRange zeroExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
LLVM_ABI APInt getSignedMin() const
Return the smallest signed value contained in the ConstantRange.
LLVM_ABI OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const
Return whether unsigned mul of the two ranges always/never overflows.
LLVM_ABI ConstantRange truncate(uint32_t BitWidth, unsigned NoWrapKind=0) const
Return a new range in the specified integer type, which must be strictly smaller than the current typ...
LLVM_ABI bool isAllNonNegative() const
Return true if all values in this range are non-negative.
LLVM_ABI ConstantRange signExtend(uint32_t BitWidth) const
Return a new range in the specified integer type, which must be strictly larger than the current type...
static LLVM_ABI ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
LLVM_ABI ConstantRange multiply(const ConstantRange &Other, unsigned NoWrapKind=0) const
Return a new range representing the possible values resulting from a multiplication of a value in thi...
LLVM_ABI ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
LLVM_ABI OverflowResult signedAddMayOverflow(const ConstantRange &Other) const
Return whether signed add of the two ranges always/never overflows.
LLVM_ABI APInt getUnsignedMax() const
Return the largest unsigned value contained in the ConstantRange.
LLVM_ABI ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
LLVM_ABI APInt getSignedMax() const
Return the largest signed value contained in the ConstantRange.
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
static ConstantRange getNonEmpty(APInt Lower, APInt Upper)
Create non-empty constant range with the given bounds.
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
LLVM_ABI OverflowResult signedSubMayOverflow(const ConstantRange &Other) const
Return whether signed sub of the two ranges always/never overflows.
LLVM_ABI ConstantRange sub(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a subtraction of a value in this r...
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * replaceUndefsWith(Constant *C, Constant *Replacement)
Try to replace undefined constant C or undefined elements in C with Replacement.
LLVM_ABI Constant * getSplatValue(bool AllowPoison=false) const
If all elements of the vector constant have the same value, return that value.
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition Constant.h:65
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:217
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:518
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:791
ArrayRef< CondBrInst * > conditionsFor(const Value *V) const
Access the list of branches which affect this value.
DomTreeNodeBase * getIDom() const
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction extracts a struct member or array element value from an aggregate value.
ArrayRef< unsigned > getIndices() const
unsigned getNumIndices() const
static LLVM_ABI Type * getIndexedType(Type *Agg, ArrayRef< unsigned > Idxs)
Returns the type of the element that would be extracted with an extractvalue instruction with the spe...
This instruction compares its operands according to the predicate given to the constructor.
Utility class for floating point operations which can have information about relaxed accuracy require...
Definition Operator.h:202
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
bool noInfs() const
Definition FMF.h:66
void setNoSignedZeros(bool B=true)
Definition FMF.h:84
void setNoNaNs(bool B=true)
Definition FMF.h:78
bool noNaNs() const
Definition FMF.h:65
const BasicBlock & getEntryBlock() const
Definition Function.h:794
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
Type * getValueType() const
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
This instruction compares its operands according to the predicate given to the constructor.
CmpPredicate getSwappedCmpPredicate() const
CmpPredicate getInverseCmpPredicate() const
Predicate getFlippedSignednessPredicate() const
For example, SLT->ULT, ULT->SLT, SLE->ULE, ULE->SLE, EQ->EQ.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
static LLVM_ABI std::optional< bool > isImpliedByMatchingCmp(CmpPredicate Pred1, CmpPredicate Pred2)
Determine if Pred1 implies Pred2 is true, false, or if nothing can be inferred about the implication,...
bool isRelational() const
Return true if the predicate is relational (not EQ or NE).
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
This instruction inserts a struct field of array element value into an aggregate value.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI bool hasNoNaNs() const LLVM_READONLY
Determine whether the no-NaNs flag is set.
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
bool isBinaryOp() const
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI const Function * getFunction() const
Return the function this instruction belongs to.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isUnaryOp() const
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
A wrapper class for inspecting calls to intrinsic functions.
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
static LLVM_ABI KnownFPClass fmul(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmul.
static LLVM_ABI KnownFPClass ceil(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ceil.
static LLVM_ABI KnownFPClass fadd_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd x, x.
static LLVM_ABI KnownFPClass fmuladd(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmuladd.
static KnownFPClass square(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fsub(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fsub.
bool isKnownNeverSubnormal() const
Return true if it's known this can never be a subnormal.
KnownFPClass unionWith(const KnownFPClass &RHS) const
static LLVM_ABI KnownFPClass canonicalize(const KnownFPClass &Src, DenormalMode DenormMode=DenormalMode::getDynamic())
Apply the canonicalize intrinsic to this value.
LLVM_ABI bool isKnownNeverLogicalZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a zero.
static LLVM_ABI KnownFPClass atan2(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for atan2.
static LLVM_ABI KnownFPClass atan(const KnownFPClass &Src)
Report known values for atan.
static LLVM_ABI KnownFPClass fdiv(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fdiv.
static LLVM_ABI KnownFPClass fpext(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy, DenormalMode DstMode, DenormalMode SrcMode)
Propagate known class for fpext.
static LLVM_ABI KnownFPClass cos(const KnownFPClass &Src)
Report known values for cos.
static LLVM_ABI KnownFPClass fptrunc(const KnownFPClass &KnownSrc, const fltSemantics &DstTy, const fltSemantics &SrcTy, DenormalMode DstMode, DenormalMode SrcMode)
Propagate known class for fptrunc and fptrunc_round.
static LLVM_ABI KnownFPClass cosh(const KnownFPClass &Src)
Report known values for cosh.
static LLVM_ABI KnownFPClass minMaxLike(const KnownFPClass &LHS, const KnownFPClass &RHS, MinMaxKind Kind, DenormalMode DenormMode=DenormalMode::getDynamic())
static LLVM_ABI KnownFPClass fmuladd_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fmuladd squared, squared, addend.
bool isUnknown() const
static LLVM_ABI KnownFPClass exp(const KnownFPClass &Src)
Report known values for exp, exp2 and exp10.
static LLVM_ABI KnownFPClass frexp_mant(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for mantissa component of frexp.
static LLVM_ABI KnownFPClass asin(const KnownFPClass &Src)
Report known values for asin.
bool isKnownNeverNaN() const
Return true if it's known this can never be a nan.
void knownNot(FPClassMask RuleOut)
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 ...
FPClassTest getKnownFPClasses() const
Floating-point classes the value could be one of.
static KnownFPClass getEmpty()
static LLVM_ABI KnownFPClass roundToIntegral(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for rounding intrinsics (rint, nearbyint, round, roundeven).
static LLVM_ABI KnownFPClass fma(const KnownFPClass &LHS, const KnownFPClass &RHS, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma.
static LLVM_ABI KnownFPClass tan(const KnownFPClass &Src)
Report known values for tan.
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 isKnownNever(FPClassMask Mask) const
Return true if it's known this can never be one of the mask entries.
bool isKnownNeverPosInfinity() const
Return true if it's known this can never be +infinity.
static LLVM_ABI KnownFPClass fadd(const KnownFPClass &LHS, const KnownFPClass &RHS, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fadd.
static LLVM_ABI KnownFPClass trunc(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for trunc.
LLVM_ABI bool isKnownNeverLogicalNegZero(DenormalMode Mode) const
Return true if it's known this can never be interpreted as a negative zero.
static LLVM_ABI KnownFPClass bitcast(const fltSemantics &FltSemantics, const KnownBits &Bits)
Report known values for a bitcast into a float with provided semantics.
static LLVM_ABI KnownFPClass fma_square(const KnownFPClass &Squared, const KnownFPClass &Addend, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for fma squared, squared, addend.
static LLVM_ABI KnownFPClass acos(const KnownFPClass &Src)
Report known values for acos.
static LLVM_ABI KnownFPClass log(const KnownFPClass &Src, DenormalMode Mode, bool IsMultiUnitFPType)
Propagate known class for log/log2/log10.
static LLVM_ABI KnownFPClass frem_self(const KnownFPClass &Src, DenormalMode Mode=DenormalMode::getDynamic())
Report known values for frem x, x.
static LLVM_ABI KnownFPClass powi(const KnownFPClass &Src, const KnownBits &N)
Propagate known class for powi.
static LLVM_ABI KnownFPClass floor(const KnownFPClass &Src, bool IsMultiUnitFPType, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for floor.
static LLVM_ABI KnownFPClass pow(const KnownFPClass &LHS, const KnownFPClass &RHS)
Propagate known class for pow.
static LLVM_ABI KnownFPClass ldexp(const KnownFPClass &Src, const APInt &ConstantRangeMin, const APInt &ConstantRangeMax, const fltSemantics &Flt, DenormalMode Mode=DenormalMode::getDynamic())
Propagate known class for ldexp, assuming the exponent is known to be within [ConstantRangeMin,...
static LLVM_ABI KnownFPClass sinh(const KnownFPClass &Src)
Report known values for sinh.
static LLVM_ABI KnownFPClass tanh(const KnownFPClass &Src)
Report known values for tanh.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
An instruction for reading from memory.
Value * getPointerOperand()
Align getAlign() const
Return the alignment of the access that is being performed.
bool isLoopHeader(const BlockT *BB) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
unsigned getOpcode() const
Return the opcode for this Instruction or ConstantExpr.
Definition Operator.h:43
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl.
Definition Operator.h:78
iterator_range< const_block_iterator > blocks() const
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
unsigned getAddressSpace() const
Return the address space of the Pointer type.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A udiv, sdiv, lshr, or ashr instruction, which can be marked as "exact", indicating that no bits are ...
Definition Operator.h:156
bool isExact() const
Test whether this division is known to be exact, with zero remainder.
Definition Operator.h:175
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getCondition() const
const Value * getTrueValue() const
This instruction constructs a fixed permutation of two input vectors.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:743
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:774
Class to represent struct types.
unsigned getNumElements() const
Random access to the elements.
Type * getElementType(unsigned N) const
Provides information about what library functions are available for the current target.
LibFunc getLibFunc(StringRef funcName) const
Searches for a particular function name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
bool isFloatTy() const
Return true if this is 'float', a 32-bit IEEE fp type.
Definition Type.h:155
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
LLVM_ABI uint64_t getArrayNumElements() const
bool isSized() const
Return true if it makes sense to take the size of this type.
Definition Type.h:321
static LLVM_ABI IntegerType * getInt8Ty(LLVMContext &C)
Definition Type.cpp:297
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:363
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
bool isHalfTy() const
Return true if this is 'half', a 16-bit IEEE fp type.
Definition Type.h:144
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:222
bool isDoubleTy() const
Return true if this is 'double', a 64-bit IEEE fp type.
Definition Type.h:158
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition Type.h:280
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition Type.h:265
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:303
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
LLVM_ABI const fltSemantics & getFltSemantics() const
Definition Type.cpp:96
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
LLVM_ABI unsigned getOperandNo() const
Return the operand # of this use in its User.
Definition Use.cpp:35
User * getUser() const
Returns the User that contains this Use.
Definition Use.h:61
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition Value.h:729
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
const KnownBits & getKnownBits(const SimplifyQuery &Q) const
Definition WithCache.h:59
PointerType getValue() const
Definition WithCache.h:57
Represents an op.with.overflow intrinsic.
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
TypeSize getSequentialElementStride(const DataLayout &DL) const
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A range adaptor for a pair of iterators.
CallInst * Call
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
LLVM_ABI APInt ScaleBitMask(const APInt &A, unsigned NewBitWidth, bool MatchAllBits=false)
Splat/Merge neighboring bits to widen/narrow the bitmask represented by.
Definition APInt.cpp:3043
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
cst_pred_ty< is_lowbit_mask > m_LowBitMask()
Match an integer or vector with only the low bit(s) set.
match_bind< PHINode > m_Phi(PHINode *&PN)
Match a PHI node, capturing it if we match.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
PtrToIntSameSize_match< OpTy > m_PtrToIntSameSize(const DataLayout &DL, const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, FCmpInst > m_FCmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_c_UMax(const LHS &L, const RHS &R)
Matches a UMax with LHS and RHS in either order.
cst_pred_ty< is_sign_mask > m_SignMask()
Match an integer or vector with only the sign bit(s) set.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWAdd(const LHS &L, const RHS &R)
auto m_PtrToIntOrAddr(const OpTy &Op)
Matches PtrToInt or PtrToAddr.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_LogicalOp()
Matches either L && R or L || R where L and R are arbitrary values.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
cst_pred_ty< is_power2_or_zero > m_Power2OrZero()
Match an integer or vector of 0 or power-of-2 values.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
CastOperator_match< OpTy, Instruction::PtrToAddr > m_PtrToAddr(const OpTy &Op)
Matches PtrToAddr.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoSignedWrap > m_NSWSub(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_idiv_op > m_IDiv(const LHS &L, const RHS &R)
Matches integer division operations.
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
auto m_UMin(const Opnd0 &Op0, const Opnd1 &Op1)
match_deferred< Value > m_Deferred(Value *const &V)
Like m_Specific(), but works if the specific value to match is determined as part of the same match()...
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ap_match< APFloat > m_APFloat(const APFloat *&Res)
Match a ConstantFP or splatted ConstantVector, binding the specified pointer to the contained APFloat...
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
auto match_fn(const Pattern &P)
A match functor that can be used as a UnaryPredicate in functional algorithms like all_of.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap, true > m_c_NUWAdd(const LHS &L, const RHS &R)
cstfp_pred_ty< is_finite > m_Finite()
Match a finite FP constant, i.e.
cst_pred_ty< is_nonnegative > m_NonNegative()
Match an integer or vector of non-negative values.
auto m_SMax(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_UMax(const Opnd0 &Op0, const Opnd1 &Op1)
auto m_BasicBlock()
Match an arbitrary basic block value and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
ICmpLike_match< LHS, RHS > m_ICmpLike(CmpPredicate &Pred, const LHS &L, const RHS &R)
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Xor, true > m_c_Xor(const LHS &L, const RHS &R)
Matches an Xor with LHS and RHS in either order.
auto m_Ctpop(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
cst_pred_ty< is_strictlypositive > m_StrictlyPositive()
Match an integer or vector of strictly positive values.
auto m_VScale()
Matches a call to llvm.vscale().
ThreeOps_match< decltype(m_Value()), LHS, RHS, Instruction::Select, true > m_c_Select(const LHS &L, const RHS &R)
Match Select(C, LHS, RHS) or Select(C, RHS, LHS)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoSignedWrap > m_NSWShl(const LHS &L, const RHS &R)
match_bind< WithOverflowInst > m_WithOverflowInst(WithOverflowInst *&I)
Match a with overflow intrinsic, capturing it if we match.
SpecificCmpClass_match< LHS, RHS, ICmpInst > m_SpecificICmp(CmpPredicate MatchPred, const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
auto m_Ctlz(const Opnd0 &Op0, const Opnd1 &Op1)
match_combine_or< FMaxMin_match< LHS, RHS, ofmin_pred_ty >, FMaxMin_match< LHS, RHS, ufmin_pred_ty > > m_OrdOrUnordFMin(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point minimum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::UDiv > m_UDiv(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
match_combine_or< BinaryOp_match< LHS, RHS, Instruction::Add >, DisjointOr_match< LHS, RHS > > m_AddLike(const LHS &L, const RHS &R)
Match either "add" or "or disjoint".
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_c_MaxOrMin(const LHS &L, const RHS &R)
cstfp_pred_ty< custom_checkfn< APFloat > > m_CheckedFp(function_ref< bool(const APFloat &)> CheckFn)
Match a float or vector where CheckFn(ele) for each element is true.
auto m_FMinNum(const Opnd0 &Op0, const Opnd1 &Op1)
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
auto m_SMin(const Opnd0 &Op0, const Opnd1 &Op1)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
auto m_FAbs(const Opnd0 &Op0)
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap >, DisjointOr_match< LHS, RHS > > m_NSWAddLike(const LHS &L, const RHS &R)
Match either "add nsw" or "or disjoint".
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< FMaxMin_match< LHS, RHS, ofmax_pred_ty >, FMaxMin_match< LHS, RHS, ufmax_pred_ty > > m_OrdOrUnordFMax(const LHS &L, const RHS &R)
Match an 'ordered' or 'unordered' floating point maximum function.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinOpPred_match< LHS, RHS, is_shift_op > m_Shift(const LHS &L, const RHS &R)
Matches shift operations.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_irem_op > m_IRem(const LHS &L, const RHS &R)
Matches integer remainder operations.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
brc_match< Cond_t, match_bind< BasicBlock >, match_bind< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
auto m_c_UMin(const LHS &L, const RHS &R)
Matches a UMin with LHS and RHS in either order.
auto m_c_SMax(const LHS &L, const RHS &R)
Matches an SMax with LHS and RHS in either order.
BinaryOp_match< LHS, RHS, Instruction::SRem > m_SRem(const LHS &L, const RHS &R)
auto m_FMaxNum(const Opnd0 &Op0, const Opnd1 &Op1)
cst_pred_ty< is_nonpositive > m_NonPositive()
Match an integer or vector of non-positive values.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
match_combine_or< OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoUnsignedWrap >, DisjointOr_match< LHS, RHS > > m_NUWAddLike(const LHS &L, const RHS &R)
Match either "add nuw" or "or disjoint".
auto m_c_SMin(const LHS &L, const RHS &R)
Matches an SMin with LHS and RHS in either order.
ElementWiseBitCast_match< OpTy > m_ElementWiseBitCast(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Mul, true > m_c_Mul(const LHS &L, const RHS &R)
Matches a Mul with LHS and RHS in either order.
CastOperator_match< OpTy, Instruction::PtrToInt > m_PtrToInt(const OpTy &Op)
Matches PtrToInt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoSignedWrap > m_NSWMul(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static unsigned decodeVSEW(unsigned VSEW)
LLVM_ABI unsigned getSEWLMULRatio(unsigned SEW, VLMUL VLMul)
static constexpr unsigned RVVBitsPerBlock
static constexpr unsigned RVVBytesPerBlock
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h: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 Constant * ReadByteArrayFromGlobal(const GlobalVariable *GV, uint64_t Offset)
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
int bit_width(T Value)
Returns the number of bits needed to represent Value if Value is nonzero.
Definition bit.h:325
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool assumeBundleImpliesNonNull(const Value *Val, const Function *Context, OperandBundleUse OBU)
LLVM_ABI bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition Loads.cpp:450
@ O1
Optimize quickly without destroying debuggability.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
gep_type_iterator gep_type_end(const User *GEP)
int ilogb(const APFloat &Arg)
Returns the exponent of the internal representation of the APFloat.
Definition APFloat.h:1692
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI bool isKnownNegative(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
std::tuple< Value *, FPClassTest, FPClassTest > fcmpImpliesClass(CmpInst::Predicate Pred, const Function &F, Value *LHS, FPClassTest RHSClass, bool LookThroughSrc=true)
const Value * getPointerOperand(const Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CtxI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI bool getShuffleDemandedElts(int SrcWidth, ArrayRef< int > Mask, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS, bool AllowUndefElts=false)
Transform a shuffle mask's output demanded element mask into demanded element masks for the 2 operand...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
LLVM_ABI bool isKnownPositive(const WithCache< const Value * > &V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI void getHorizDemandedEltsForFirstOperand(unsigned VectorBitWidth, const APInt &DemandedElts, APInt &DemandedLHS, APInt &DemandedRHS)
Compute the demanded elements mask of horizontal binary operations.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
FPClassTest
Floating-point class tests, supported by 'is_fpclass' intrinsic.
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
generic_gep_type_iterator<> gep_type_iterator
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V, bool MustPreserveProvenance=false)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth, bool MustPreserveProvenance=false)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
bool includesPoison(UndefPoisonKind Kind)
Returns true if Kind includes the Poison bit.
Definition UndefPoison.h:27
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
LLVM_ABI RetainedKnowledge getKnowledgeValidInContext(const Value *V, ArrayRef< Attribute::AttrKind > AttrKinds, AssumptionCache &AC, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Return a valid Knowledge associated to the Value V if its Attribute kind is in AttrKinds and the know...
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
bool includesUndef(UndefPoisonKind Kind)
Returns true if Kind includes the Undef bit.
Definition UndefPoison.h:33
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CtxI)
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CtxI)
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset, bool MustPreserveProvenance=false)
launder.invariant.group and similar intrinsics return a pointer that aliases their argument,...
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
LLVM_ABI bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const SimplifyQuery &Q, bool IgnoreFree=false)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition Loads.cpp:246
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:320
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI Constant * ConstantFoldIntegerCast(Constant *C, Type *DestTy, bool IsSigned, const DataLayout &DL)
Constant fold a zext, sext or trunc, depending on IsSigned and whether the DestTy is wider or narrowe...
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI bool isIdentifiedObject(const Value *V)
Return true if this pointer refers to a distinct and identifiable object.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h: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
SelectPatternFlavor Flavor
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
const DataLayout & DL
SimplifyQuery getWithoutCondContext() const
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const DomConditionCache * DC
const Instruction * CtxI
const Function * getFunction() const
const InstrInfoQuery IIQ
const CondContext * CC
fltNanEncoding nanEncoding
Definition APFloat.h:1041