LLVM 24.0.0git
ValueTracking.cpp
Go to the documentation of this file.
1//===- ValueTracking.cpp - Walk computations to compute properties --------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/StringRef.h"
32#include "llvm/Analysis/Loads.h"
37#include "llvm/IR/Argument.h"
38#include "llvm/IR/Attributes.h"
39#include "llvm/IR/BasicBlock.h"
41#include "llvm/IR/Constant.h"
44#include "llvm/IR/Constants.h"
47#include "llvm/IR/Dominators.h"
49#include "llvm/IR/Function.h"
51#include "llvm/IR/GlobalAlias.h"
52#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/InstrTypes.h"
55#include "llvm/IR/Instruction.h"
58#include "llvm/IR/Intrinsics.h"
59#include "llvm/IR/IntrinsicsAArch64.h"
60#include "llvm/IR/IntrinsicsAMDGPU.h"
61#include "llvm/IR/IntrinsicsRISCV.h"
62#include "llvm/IR/IntrinsicsX86.h"
63#include "llvm/IR/LLVMContext.h"
64#include "llvm/IR/Metadata.h"
65#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
68#include "llvm/IR/Type.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
80#include <algorithm>
81#include <cassert>
82#include <cstdint>
83#include <optional>
84#include <utility>
85
86using namespace llvm;
87using namespace llvm::PatternMatch;
88
89// Controls the number of uses of the value searched for possible
90// dominating comparisons.
91static cl::opt<unsigned> DomConditionsMaxUses("dom-conditions-max-uses",
92 cl::Hidden, cl::init(20));
93
94/// Maximum number of instructions to check between assume and context
95/// instruction.
96static constexpr unsigned MaxInstrsToCheckForFree = 32;
97
98/// Returns the bitwidth of the given scalar or pointer type. For vector types,
99/// returns the element type's bitwidth.
100static unsigned getBitWidth(Type *Ty, const DataLayout &DL) {
101 if (unsigned BitWidth = Ty->getScalarSizeInBits())
102 return BitWidth;
103
104 return DL.getPointerTypeSizeInBits(Ty);
105}
106
107// Given the provided Value and, potentially, a context instruction, return
108// the preferred context instruction (if any).
109static const Instruction *safeCxtI(const Value *V, const Instruction *CxtI) {
110 // If we've been provided with a context instruction, then use that (provided
111 // it has been inserted).
112 if (CxtI && CxtI->getParent())
113 return CxtI;
114
115 // If the value is really an already-inserted instruction, then use that.
116 CxtI = dyn_cast<Instruction>(V);
117 if (CxtI && CxtI->getParent())
118 return CxtI;
119
120 return nullptr;
121}
122
124 const APInt &DemandedElts,
125 APInt &DemandedLHS, APInt &DemandedRHS) {
126 if (isa<ScalableVectorType>(Shuf->getType())) {
127 assert(DemandedElts == APInt(1,1));
128 DemandedLHS = DemandedRHS = DemandedElts;
129 return true;
130 }
131
132 int NumElts =
133 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
134 return llvm::getShuffleDemandedElts(NumElts, Shuf->getShuffleMask(),
135 DemandedElts, DemandedLHS, DemandedRHS);
136}
137
138static void computeKnownBits(const Value *V, const APInt &DemandedElts,
139 KnownBits &Known, const SimplifyQuery &Q,
140 unsigned Depth);
141
143 const SimplifyQuery &Q, unsigned Depth) {
144 // Since the number of lanes in a scalable vector is unknown at compile time,
145 // we track one bit which is implicitly broadcast to all lanes. This means
146 // that all lanes in a scalable vector are considered demanded.
147 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
148 APInt DemandedElts =
149 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
150 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
151}
152
154 const DataLayout &DL, AssumptionCache *AC,
155 const Instruction *CxtI, const DominatorTree *DT,
156 bool UseInstrInfo, unsigned Depth) {
158 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
159 Depth);
160}
161
163 AssumptionCache *AC, const Instruction *CxtI,
164 const DominatorTree *DT, bool UseInstrInfo,
165 unsigned Depth) {
166 return computeKnownBits(
167 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
168}
169
170KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
171 const DataLayout &DL, AssumptionCache *AC,
172 const Instruction *CxtI,
173 const DominatorTree *DT, bool UseInstrInfo,
174 unsigned Depth) {
175 return computeKnownBits(
176 V, DemandedElts,
177 SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
178}
179
182 const SimplifyQuery &SQ) {
183 // Look for an inverted mask: (X & ~M) op (Y & M).
184 {
185 Value *M;
186 if (match(LHS, m_c_And(m_Not(m_Value(M)), m_Value())) &&
188 return isGuaranteedNotToBeUndef(M, SQ.AC, SQ.CxtI, SQ.DT)
191 }
192
193 // X op (Y & ~X)
195 return isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT)
198
199 // X op ((X & Y) ^ Y) -- this is the canonical form of the previous pattern
200 // for constant Y.
201 Value *Y;
202 if (match(RHS,
204 bool IsNoUndef = isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT) &&
205 isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT);
206 return IsNoUndef ? NoCommonBitsSetResult::Known
208 }
209
210 // Peek through extends to find a 'not' of the other side:
211 // (ext Y) op ext(~Y)
212 if (match(LHS, m_ZExtOrSExt(m_Value(Y))) &&
214 return isGuaranteedNotToBeUndef(Y, SQ.AC, SQ.CxtI, SQ.DT)
217
218 // Look for: (A & B) op ~(A | B)
219 {
220 Value *A, *B;
221 if (match(LHS, m_And(m_Value(A), m_Value(B))) &&
223 bool IsNoUndef = isGuaranteedNotToBeUndef(A, SQ.AC, SQ.CxtI, SQ.DT) &&
224 isGuaranteedNotToBeUndef(B, SQ.AC, SQ.CxtI, SQ.DT);
225 return IsNoUndef ? NoCommonBitsSetResult::Known
227 }
228 }
229
230 // Look for: (X << V) op (Y >> (BitWidth - V))
231 // or (X >> V) op (Y << (BitWidth - V))
232 {
233 const Value *V;
234 const APInt *R;
235 if (((match(RHS, m_Shl(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
236 match(LHS, m_LShr(m_Value(), m_Specific(V)))) ||
237 (match(RHS, m_LShr(m_Value(), m_Sub(m_APInt(R), m_Value(V)))) &&
238 match(LHS, m_Shl(m_Value(), m_Specific(V))))) &&
239 R->uge(LHS->getType()->getScalarSizeInBits()))
241 }
242
244}
245
248 const WithCache<const Value *> &RHSCache,
249 const SimplifyQuery &SQ) {
250 const Value *LHS = LHSCache.getValue();
251 const Value *RHS = RHSCache.getValue();
252
253 assert(LHS->getType() == RHS->getType() &&
254 "LHS and RHS should have the same type");
255 assert(LHS->getType()->isIntOrIntVectorTy() &&
256 "LHS and RHS should be integers");
257
259 if (Result == NoCommonBitsSetResult::Known)
261
262 NoCommonBitsSetResult CommuteResult =
264 if (CommuteResult == NoCommonBitsSetResult::Known)
266
268 RHSCache.getKnownBits(SQ)))
270
274
276}
277
279 const WithCache<const Value *> &RHSCache,
280 const SimplifyQuery &SQ) {
281 NoCommonBitsSetResult Result =
282 getNoCommonBitsSetResult(LHSCache, RHSCache, SQ);
283 return Result == NoCommonBitsSetResult::Known;
284}
285
287 return !I->user_empty() &&
288 all_of(I->users(), match_fn(m_ICmp(m_Value(), m_Zero())));
289}
290
292 return !I->user_empty() && all_of(I->users(), [](const User *U) {
293 CmpPredicate P;
294 return match(U, m_ICmp(P, m_Value(), m_Zero())) && ICmpInst::isEquality(P);
295 });
296}
297
299 bool OrZero, AssumptionCache *AC,
300 const Instruction *CxtI,
301 const DominatorTree *DT, bool UseInstrInfo,
302 unsigned Depth) {
303 return ::isKnownToBeAPowerOfTwo(
304 V, OrZero, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo),
305 Depth);
306}
307
308static bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
309 const SimplifyQuery &Q, unsigned Depth);
310
312 unsigned Depth) {
313 return computeKnownBits(V, SQ, Depth).isNonNegative();
314}
315
317 unsigned Depth) {
318 if (auto *CI = dyn_cast<ConstantInt>(V))
319 return CI->getValue().isStrictlyPositive();
320
321 // If `isKnownNonNegative` ever becomes more sophisticated, make sure to keep
322 // this updated.
324 return Known.isNonNegative() &&
325 (Known.isNonZero() || isKnownNonZero(V, SQ, Depth));
326}
327
329 unsigned Depth) {
330 return computeKnownBits(V, SQ, Depth).isNegative();
331}
332
333static bool isKnownNonEqual(const Value *V1, const Value *V2,
334 const APInt &DemandedElts, const SimplifyQuery &Q,
335 unsigned Depth);
336
337static bool isTruePredicate(CmpInst::Predicate Pred, const Value *LHS,
338 const Value *RHS);
339
340bool llvm::isKnownNonEqual(const Value *V1, const Value *V2,
341 const SimplifyQuery &Q, unsigned Depth) {
342 // We don't support looking through casts.
343 if (V1 == V2 || V1->getType() != V2->getType())
344 return false;
345 auto *FVTy = dyn_cast<FixedVectorType>(V1->getType());
346 APInt DemandedElts =
347 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
348 return ::isKnownNonEqual(V1, V2, DemandedElts, Q, Depth);
349}
350
351bool llvm::MaskedValueIsZero(const Value *V, const APInt &Mask,
352 const SimplifyQuery &SQ, unsigned Depth) {
353 KnownBits Known(Mask.getBitWidth());
355 return Mask.isSubsetOf(Known.Zero);
356}
357
358static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
359 const SimplifyQuery &Q, unsigned Depth);
360
361static unsigned ComputeNumSignBits(const Value *V, const SimplifyQuery &Q,
362 unsigned Depth = 0) {
363 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
364 APInt DemandedElts =
365 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
366 return ComputeNumSignBits(V, DemandedElts, Q, Depth);
367}
368
369unsigned llvm::ComputeNumSignBits(const Value *V, const DataLayout &DL,
370 AssumptionCache *AC, const Instruction *CxtI,
371 const DominatorTree *DT, bool UseInstrInfo,
372 unsigned Depth) {
373 return ::ComputeNumSignBits(
374 V, SimplifyQuery(DL, DT, AC, safeCxtI(V, CxtI), UseInstrInfo), Depth);
375}
376
378 AssumptionCache *AC,
379 const Instruction *CxtI,
380 const DominatorTree *DT,
381 unsigned Depth) {
382 unsigned SignBits = ComputeNumSignBits(V, DL, AC, CxtI, DT, Depth);
383 return V->getType()->getScalarSizeInBits() - SignBits + 1;
384}
385
386/// Try to detect the lerp pattern: a * (b - c) + c * d
387/// where a >= 0, b >= 0, c >= 0, d >= 0, and b >= c.
388///
389/// In that particular case, we can use the following chain of reasoning:
390///
391/// a * (b - c) + c * d <= a' * (b - c) + a' * c = a' * b where a' = max(a, d)
392///
393/// Since that is true for arbitrary a, b, c and d within our constraints, we
394/// can conclude that:
395///
396/// max(a * (b - c) + c * d) <= max(max(a), max(d)) * max(b) = U
397///
398/// Considering that any result of the lerp would be less or equal to U, it
399/// would have at least the number of leading 0s as in U.
400///
401/// While being quite a specific situation, it is fairly common in computer
402/// graphics in the shape of alpha blending.
403///
404/// Modifies given KnownOut in-place with the inferred information.
405static void computeKnownBitsFromLerpPattern(const Value *Op0, const Value *Op1,
406 const APInt &DemandedElts,
407 KnownBits &KnownOut,
408 const SimplifyQuery &Q,
409 unsigned Depth) {
410
411 Type *Ty = Op0->getType();
412 const unsigned BitWidth = Ty->getScalarSizeInBits();
413
414 // Only handle scalar types for now
415 if (Ty->isVectorTy())
416 return;
417
418 // Try to match: a * (b - c) + c * d.
419 // When a == 1 => A == nullptr, the same applies to d/D as well.
420 const Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
421 const Instruction *SubBC = nullptr;
422
423 const auto MatchSubBC = [&]() {
424 // (b - c) can have two forms that interest us:
425 //
426 // 1. sub nuw %b, %c
427 // 2. xor %c, %b
428 //
429 // For the first case, nuw flag guarantees our requirement b >= c.
430 //
431 // The second case might happen when the analysis can infer that b is a mask
432 // for c and we can transform sub operation into xor (that is usually true
433 // for constant b's). Even though xor is symmetrical, canonicalization
434 // ensures that the constant will be the RHS. We have additional checks
435 // later on to ensure that this xor operation is equivalent to subtraction.
437 m_Xor(m_Value(C), m_Value(B))));
438 };
439
440 const auto MatchASubBC = [&]() {
441 // Cases:
442 // - a * (b - c)
443 // - (b - c) * a
444 // - (b - c) <- a implicitly equals 1
445 return m_CombineOr(m_c_Mul(m_Value(A), MatchSubBC()), MatchSubBC());
446 };
447
448 const auto MatchCD = [&]() {
449 // Cases:
450 // - d * c
451 // - c * d
452 // - c <- d implicitly equals 1
454 };
455
456 const auto Match = [&](const Value *LHS, const Value *RHS) {
457 // We do use m_Specific(C) in MatchCD, so we have to make sure that
458 // it's bound to anything and match(LHS, MatchASubBC()) absolutely
459 // has to evaluate first and return true.
460 //
461 // If Match returns true, it is guaranteed that B != nullptr, C != nullptr.
462 return match(LHS, MatchASubBC()) && match(RHS, MatchCD());
463 };
464
465 if (!Match(Op0, Op1) && !Match(Op1, Op0))
466 return;
467
468 const auto ComputeKnownBitsOrOne = [&](const Value *V) {
469 // For some of the values we use the convention of leaving
470 // it nullptr to signify an implicit constant 1.
471 return V ? computeKnownBits(V, DemandedElts, Q, Depth + 1)
473 };
474
475 // Check that all operands are non-negative
476 const KnownBits KnownA = ComputeKnownBitsOrOne(A);
477 if (!KnownA.isNonNegative())
478 return;
479
480 const KnownBits KnownD = ComputeKnownBitsOrOne(D);
481 if (!KnownD.isNonNegative())
482 return;
483
484 const KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
485 if (!KnownB.isNonNegative())
486 return;
487
488 const KnownBits KnownC = computeKnownBits(C, DemandedElts, Q, Depth + 1);
489 if (!KnownC.isNonNegative())
490 return;
491
492 // If we matched subtraction as xor, we need to actually check that xor
493 // is semantically equivalent to subtraction.
494 //
495 // For that to be true, b has to be a mask for c or that b's known
496 // ones cover all known and possible ones of c.
497 if (SubBC->getOpcode() == Instruction::Xor &&
498 !KnownC.getMaxValue().isSubsetOf(KnownB.getMinValue()))
499 return;
500
501 const APInt MaxA = KnownA.getMaxValue();
502 const APInt MaxD = KnownD.getMaxValue();
503 const APInt MaxAD = APIntOps::umax(MaxA, MaxD);
504 const APInt MaxB = KnownB.getMaxValue();
505
506 // We can't infer leading zeros info if the upper-bound estimate wraps.
507 bool Overflow;
508 const APInt UpperBound = MaxAD.umul_ov(MaxB, Overflow);
509
510 if (Overflow)
511 return;
512
513 // If we know that x <= y and both are positive than x has at least the same
514 // number of leading zeros as y.
515 const unsigned MinimumNumberOfLeadingZeros = UpperBound.countl_zero();
516 KnownOut.Zero.setHighBits(MinimumNumberOfLeadingZeros);
517}
518
519static void computeKnownBitsAddSub(bool Add, const Value *Op0, const Value *Op1,
520 bool NSW, bool NUW,
521 const APInt &DemandedElts,
522 KnownBits &KnownOut, KnownBits &Known2,
523 const SimplifyQuery &Q, unsigned Depth) {
524 computeKnownBits(Op1, DemandedElts, KnownOut, Q, Depth + 1);
525
526 // If one operand is unknown and we have no nowrap information,
527 // the result will be unknown independently of the second operand.
528 if (KnownOut.isUnknown() && !NSW && !NUW)
529 return;
530
531 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
532 KnownOut = KnownBits::computeForAddSub(Add, NSW, NUW, Known2, KnownOut);
533
534 if (!Add && NSW && !KnownOut.isNonNegative() &&
536 .value_or(false) ||
537 match(Op1, m_c_SMin(m_Specific(Op0), m_Value()))))
538 KnownOut.makeNonNegative();
539
540 if (Add)
541 // Try to match lerp pattern and combine results
542 computeKnownBitsFromLerpPattern(Op0, Op1, DemandedElts, KnownOut, Q, Depth);
543}
544
545static void computeKnownBitsMul(const Value *Op0, const Value *Op1, bool NSW,
546 bool NUW, const APInt &DemandedElts,
547 KnownBits &Known, KnownBits &Known2,
548 const SimplifyQuery &Q, unsigned Depth) {
549 computeKnownBits(Op1, DemandedElts, Known, Q, Depth + 1);
550 computeKnownBits(Op0, DemandedElts, Known2, Q, Depth + 1);
551
552 bool isKnownNegative = false;
553 bool isKnownNonNegative = false;
554 // If the multiplication is known not to overflow, compute the sign bit.
555 if (NSW) {
556 if (Op0 == Op1) {
557 // The product of a number with itself is non-negative.
558 isKnownNonNegative = true;
559 } else {
560 bool isKnownNonNegativeOp1 = Known.isNonNegative();
561 bool isKnownNonNegativeOp0 = Known2.isNonNegative();
562 bool isKnownNegativeOp1 = Known.isNegative();
563 bool isKnownNegativeOp0 = Known2.isNegative();
564 // The product of two numbers with the same sign is non-negative.
565 isKnownNonNegative = (isKnownNegativeOp1 && isKnownNegativeOp0) ||
566 (isKnownNonNegativeOp1 && isKnownNonNegativeOp0);
567 if (!isKnownNonNegative && NUW) {
568 // mul nuw nsw with a factor > 1 is non-negative.
569 KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1));
570 isKnownNonNegative = KnownBits::sgt(Known, One).value_or(false) ||
571 KnownBits::sgt(Known2, One).value_or(false);
572 }
573
574 // The product of a negative number and a non-negative number is either
575 // negative or zero.
578 (isKnownNegativeOp1 && isKnownNonNegativeOp0 &&
579 Known2.isNonZero()) ||
580 (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero());
581 }
582 }
583
584 bool SelfMultiply = Op0 == Op1;
585 if (SelfMultiply)
586 SelfMultiply &=
587 isGuaranteedNotToBeUndef(Op0, Q.AC, Q.CxtI, Q.DT, Depth + 1);
588 Known = KnownBits::mul(Known, Known2, SelfMultiply);
589
590 if (SelfMultiply) {
591 unsigned SignBits = ComputeNumSignBits(Op0, DemandedElts, Q, Depth + 1);
592 unsigned TyBits = Op0->getType()->getScalarSizeInBits();
593 unsigned OutValidBits = 2 * (TyBits - SignBits + 1);
594
595 if (OutValidBits < TyBits) {
596 APInt KnownZeroMask =
597 APInt::getHighBitsSet(TyBits, TyBits - OutValidBits + 1);
598 Known.Zero |= KnownZeroMask;
599 }
600 }
601
602 // Only make use of no-wrap flags if we failed to compute the sign bit
603 // directly. This matters if the multiplication always overflows, in
604 // which case we prefer to follow the result of the direct computation,
605 // though as the program is invoking undefined behaviour we can choose
606 // whatever we like here.
607 if (isKnownNonNegative && !Known.isNegative())
608 Known.makeNonNegative();
609 else if (isKnownNegative && !Known.isNonNegative())
610 Known.makeNegative();
611}
612
614 KnownBits &Known) {
615 unsigned BitWidth = Known.getBitWidth();
616 unsigned NumRanges = Ranges.getNumOperands() / 2;
617 assert(NumRanges >= 1);
618
619 Known.setAllConflict();
620
621 for (unsigned i = 0; i < NumRanges; ++i) {
623 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 0));
625 mdconst::extract<ConstantInt>(Ranges.getOperand(2 * i + 1));
626 ConstantRange Range(Lower->getValue(), Upper->getValue());
627 // BitWidth must equal the Ranges BitWidth for the correct number of high
628 // bits to be set.
629 assert(BitWidth == Range.getBitWidth() &&
630 "Known bit width must match range bit width!");
631
632 // The first CommonPrefixBits of all values in Range are equal.
633 unsigned CommonPrefixBits =
634 (Range.getUnsignedMax() ^ Range.getUnsignedMin()).countl_zero();
635 APInt Mask = APInt::getHighBitsSet(BitWidth, CommonPrefixBits);
636 APInt UnsignedMax = Range.getUnsignedMax().zextOrTrunc(BitWidth);
637 Known.One &= UnsignedMax & Mask;
638 Known.Zero &= ~UnsignedMax & Mask;
639 }
640}
641
642static bool isEphemeralValueOf(const Instruction *I, const Value *E) {
643 // The instruction defining an assumption's condition itself is always
644 // considered ephemeral to that assumption (even if it has other
645 // non-ephemeral users). See r246696's test case for an example.
646 if (is_contained(I->operands(), E))
647 return true;
648
649 const auto *EI = dyn_cast<Instruction>(E);
650 if (!EI)
651 return false;
652
653 if (EI == I)
654 return true;
655
658 Visited.insert(EI);
659 WorkList.push_back(EI);
660 bool ReachesI = false;
661 while (!WorkList.empty()) {
662 const Instruction *V = WorkList.pop_back_val();
663 for (const User *U : V->users()) {
664 const auto *UI = cast<Instruction>(U);
665 if (UI == I) {
666 ReachesI = true;
667 continue;
668 }
669 if (UI->mayHaveSideEffects() || UI->isTerminator())
670 return false;
671 if (Visited.insert(UI).second)
672 WorkList.push_back(UI);
673 }
674 }
675 return ReachesI;
676}
677
678// Is this an intrinsic that cannot be speculated but also cannot trap?
680 if (const IntrinsicInst *CI = dyn_cast<IntrinsicInst>(I))
681 return CI->isAssumeLikeIntrinsic();
682
683 return false;
684}
685
687 const Instruction *CxtI,
688 const DominatorTree *DT,
689 bool AllowEphemerals) {
690 // There are two restrictions on the use of an assume:
691 // 1. The assume must dominate the context (or the control flow must
692 // reach the assume whenever it reaches the context).
693 // 2. The context must not be in the assume's set of ephemeral values
694 // (otherwise we will use the assume to prove that the condition
695 // feeding the assume is trivially true, thus causing the removal of
696 // the assume).
697
698 if (Inv->getParent() == CxtI->getParent()) {
699 // If Inv and CtxI are in the same block, check if the assume (Inv) is first
700 // in the BB.
701 if (Inv->comesBefore(CxtI))
702 return true;
703
704 // Don't let an assume affect itself - this would cause the problems
705 // `isEphemeralValueOf` is trying to prevent, and it would also make
706 // the loop below go out of bounds.
707 if (!AllowEphemerals && Inv == CxtI)
708 return false;
709
710 // The context comes first, but they're both in the same block.
711 // Make sure there is nothing in between that might interrupt
712 // the control flow, not even CxtI itself.
713 // We limit the scan distance between the assume and its context instruction
714 // to avoid a compile-time explosion. This limit is chosen arbitrarily, so
715 // it can be adjusted if needed (could be turned into a cl::opt).
716 auto Range = make_range(CxtI->getIterator(), Inv->getIterator());
718 return false;
719
720 return AllowEphemerals || !isEphemeralValueOf(Inv, CxtI);
721 }
722
723 // Inv and CxtI are in different blocks.
724 if (DT) {
725 if (DT->dominates(Inv, CxtI))
726 return true;
727 } else if (Inv->getParent() == CxtI->getParent()->getSinglePredecessor() ||
728 Inv->getParent()->isEntryBlock()) {
729 // We don't have a DT, but this trivially dominates.
730 return true;
731 }
732
733 return false;
734}
735
737 const Instruction *CtxI) {
738 // Helper to check if there are any calls in the range that may free memory.
739 unsigned NumChecked = 0;
740 auto hasNoFreeInRange = [&NumChecked](auto Range) {
741 for (const Instruction &I : Range) {
742 if (NumChecked++ > MaxInstrsToCheckForFree)
743 return false;
744
745 if (auto *CB = dyn_cast<CallBase>(&I)) {
746 if (!CB->hasFnAttr(Attribute::NoFree))
747 return false;
748 } else if (I.maySynchronize())
749 return false;
750 }
751 return true;
752 };
753
754 const BasicBlock *CtxBB = CtxI->getParent();
755 const BasicBlock *AssumeBB = Assume->getParent();
756 BasicBlock::const_iterator CtxIter = CtxI->getIterator();
757 if (CtxBB == AssumeBB) {
758 // Same block case: check that Assume comes before CtxI.
759 if (Assume != CtxI && !Assume->comesBefore(CtxI))
760 return false;
761 return hasNoFreeInRange(make_range(Assume->getIterator(), CtxIter));
762 }
763
764 // Handle chain of single-predecessor blocks.
765 const BasicBlock *CurBB = CtxBB;
766 while (true) {
767 if (CurBB == AssumeBB)
768 return hasNoFreeInRange(
769 make_range(Assume->getIterator(), AssumeBB->end()));
770
771 const BasicBlock *PredBB = CurBB->getSinglePredecessor();
772 if (!PredBB)
773 return false;
774
775 if (!hasNoFreeInRange(make_range(CurBB->begin(),
776 CurBB == CtxBB ? CtxIter : CurBB->end())))
777 return false;
778 CurBB = PredBB;
779 }
780}
781
782// TODO: cmpExcludesZero misses many cases where `RHS` is non-constant but
783// we still have enough information about `RHS` to conclude non-zero. For
784// example Pred=EQ, RHS=isKnownNonZero. cmpExcludesZero is called in loops
785// so the extra compile time may not be worth it, but possibly a second API
786// should be created for use outside of loops.
787static bool cmpExcludesZero(CmpInst::Predicate Pred, const Value *RHS) {
788 // v u> y implies v != 0.
789 if (Pred == ICmpInst::ICMP_UGT)
790 return true;
791
792 // Special-case v != 0 to also handle v != null.
793 if (Pred == ICmpInst::ICMP_NE)
794 return match(RHS, m_Zero());
795
796 // All other predicates - rely on generic ConstantRange handling.
797 const APInt *C;
798 auto Zero = APInt::getZero(RHS->getType()->getScalarSizeInBits());
799 if (match(RHS, m_APInt(C))) {
801 return !TrueValues.contains(Zero);
802 }
803
805 if (VC == nullptr)
806 return false;
807
808 for (unsigned ElemIdx = 0, NElem = VC->getNumElements(); ElemIdx < NElem;
809 ++ElemIdx) {
811 Pred, VC->getElementAsAPInt(ElemIdx));
812 if (TrueValues.contains(Zero))
813 return false;
814 }
815 return true;
816}
817
818static void breakSelfRecursivePHI(const Use *U, const PHINode *PHI,
819 Value *&ValOut, Instruction *&CtxIOut,
820 const PHINode **PhiOut = nullptr) {
821 ValOut = U->get();
822 if (ValOut == PHI)
823 return;
824 CtxIOut = PHI->getIncomingBlock(*U)->getTerminator();
825 if (PhiOut)
826 *PhiOut = PHI;
827 Value *V;
828 // If the Use is a select of this phi, compute analysis on other arm to break
829 // recursion.
830 // TODO: Min/Max
831 if (match(ValOut, m_Select(m_Value(), m_Specific(PHI), m_Value(V))) ||
832 match(ValOut, m_Select(m_Value(), m_Value(V), m_Specific(PHI))))
833 ValOut = V;
834
835 // Same for select, if this phi is 2-operand phi, compute analysis on other
836 // incoming value to break recursion.
837 // TODO: We could handle any number of incoming edges as long as we only have
838 // two unique values.
839 if (auto *IncPhi = dyn_cast<PHINode>(ValOut);
840 IncPhi && IncPhi->getNumIncomingValues() == 2) {
841 for (int Idx = 0; Idx < 2; ++Idx) {
842 if (IncPhi->getIncomingValue(Idx) == PHI) {
843 ValOut = IncPhi->getIncomingValue(1 - Idx);
844 if (PhiOut)
845 *PhiOut = IncPhi;
846 CtxIOut = IncPhi->getIncomingBlock(1 - Idx)->getTerminator();
847 break;
848 }
849 }
850 }
851}
852
853static bool isKnownNonZeroFromAssume(const Value *V, const SimplifyQuery &Q) {
854 // Use of assumptions is context-sensitive. If we don't have a context, we
855 // cannot use them!
856 if (!Q.AC || !Q.CxtI)
857 return false;
858
859 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
860 if (!Elem.Assume)
861 continue;
862
863 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
864 assert(I->getFunction() == Q.CxtI->getFunction() &&
865 "Got assumption for the wrong function!");
866
867 if (Elem.Index != AssumptionCache::ExprResultIdx) {
869 I->getOperandBundleAt(Elem.Index)) &&
871 return true;
872 continue;
873 }
874
875 // Warning: This loop can end up being somewhat performance sensitive.
876 // We're running this loop for once for each value queried resulting in a
877 // runtime of ~O(#assumes * #values).
878
879 Value *RHS;
880 CmpPredicate Pred;
881 auto m_V = m_CombineOr(m_Specific(V), m_PtrToInt(m_Specific(V)));
882 if (!match(I->getArgOperand(0), m_c_ICmp(Pred, m_V, m_Value(RHS))))
883 continue;
884
886 return true;
887 }
888
889 return false;
890}
891
894 const SimplifyQuery &Q) {
895 if (RHS->getType()->isPointerTy()) {
896 // Handle comparison of pointer to null explicitly, as it will not be
897 // covered by the m_APInt() logic below.
898 if (LHS == V && match(RHS, m_Zero())) {
899 switch (Pred) {
901 Known.setAllZero();
902 break;
905 Known.makeNonNegative();
906 break;
908 Known.makeNegative();
909 break;
910 default:
911 break;
912 }
913 }
914 return;
915 }
916
917 unsigned BitWidth = Known.getBitWidth();
918 auto m_V =
920
921 Value *Y;
922 const APInt *Mask, *C;
923 if (!match(RHS, m_APInt(C)))
924 return;
925
926 uint64_t ShAmt;
927 switch (Pred) {
929 // assume(V = C)
930 if (match(LHS, m_V)) {
931 Known = Known.unionWith(KnownBits::makeConstant(*C));
932 // assume(V & Mask = C)
933 } else if (match(LHS, m_c_And(m_V, m_Value(Y)))) {
934 // For one bits in Mask, we can propagate bits from C to V.
935 Known.One |= *C;
936 if (match(Y, m_APInt(Mask)))
937 Known.Zero |= ~*C & *Mask;
938 // assume(V | Mask = C)
939 } else if (match(LHS, m_c_Or(m_V, m_Value(Y)))) {
940 // For zero bits in Mask, we can propagate bits from C to V.
941 Known.Zero |= ~*C;
942 if (match(Y, m_APInt(Mask)))
943 Known.One |= *C & ~*Mask;
944 // assume(V << ShAmt = C)
945 } else if (match(LHS, m_Shl(m_V, m_ConstantInt(ShAmt))) &&
946 ShAmt < BitWidth) {
947 // For those bits in C that are known, we can propagate them to known
948 // bits in V shifted to the right by ShAmt.
950 RHSKnown >>= ShAmt;
951 Known = Known.unionWith(RHSKnown);
952 // assume(V >> ShAmt = C)
953 } else if (match(LHS, m_Shr(m_V, m_ConstantInt(ShAmt))) &&
954 ShAmt < BitWidth) {
955 // For those bits in RHS that are known, we can propagate them to known
956 // bits in V shifted to the right by C.
958 RHSKnown <<= ShAmt;
959 Known = Known.unionWith(RHSKnown);
960 }
961 break;
962 case ICmpInst::ICMP_NE: {
963 // assume (V & B != 0) where B is a power of 2
964 const APInt *BPow2;
965 if (C->isZero() && match(LHS, m_And(m_V, m_Power2(BPow2))))
966 Known.One |= *BPow2;
967 break;
968 }
969 default: {
970 const APInt *Offset = nullptr;
971 if (match(LHS, m_CombineOr(m_V, m_AddLike(m_V, m_APInt(Offset))))) {
973 if (Offset)
974 LHSRange = LHSRange.sub(*Offset);
975 Known = Known.unionWith(LHSRange.toKnownBits());
976 }
977 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
978 // X & Y u> C -> X u> C && Y u> C
979 // X nuw- Y u> C -> X u> C
980 if (match(LHS, m_c_And(m_V, m_Value())) ||
981 match(LHS, m_NUWSub(m_V, m_Value())))
982 Known.One.setHighBits(
983 (*C + (Pred == ICmpInst::ICMP_UGT)).countLeadingOnes());
984 }
985 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
986 // X | Y u< C -> X u< C && Y u< C
987 // X nuw+ Y u< C -> X u< C && Y u< C
988 if (match(LHS, m_c_Or(m_V, m_Value())) ||
989 match(LHS, m_c_NUWAdd(m_V, m_Value()))) {
990 Known.Zero.setHighBits(
991 (*C - (Pred == ICmpInst::ICMP_ULT)).countLeadingZeros());
992 }
993 }
994 } break;
995 }
996}
997
998static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
1000 const SimplifyQuery &SQ, bool Invert) {
1001 ICmpInst::Predicate Pred =
1002 Invert ? Cmp->getInversePredicate() : Cmp->getPredicate();
1003 Value *LHS = Cmp->getOperand(0);
1004 Value *RHS = Cmp->getOperand(1);
1005
1006 // Handle icmp pred (trunc V), C
1007 if (match(LHS, m_Trunc(m_Specific(V)))) {
1008 KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
1009 computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
1011 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1012 else
1013 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1014 return;
1015 }
1016
1017 computeKnownBitsFromCmp(V, Pred, LHS, RHS, Known, SQ);
1018}
1019
1021 KnownBits &Known, const SimplifyQuery &SQ,
1022 bool Invert, unsigned Depth) {
1023 Value *A, *B;
1026 KnownBits Known2(Known.getBitWidth());
1027 KnownBits Known3(Known.getBitWidth());
1028 computeKnownBitsFromCond(V, A, Known2, SQ, Invert, Depth + 1);
1029 computeKnownBitsFromCond(V, B, Known3, SQ, Invert, Depth + 1);
1030 if (Invert ? match(Cond, m_LogicalOr(m_Value(), m_Value()))
1032 Known2 = Known2.unionWith(Known3);
1033 else
1034 Known2 = Known2.intersectWith(Known3);
1035 Known = Known.unionWith(Known2);
1036 return;
1037 }
1038
1039 if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
1040 computeKnownBitsFromICmpCond(V, Cmp, Known, SQ, Invert);
1041 return;
1042 }
1043
1044 if (match(Cond, m_Trunc(m_Specific(V)))) {
1045 KnownBits DstKnown(1);
1046 if (Invert) {
1047 DstKnown.setAllZero();
1048 } else {
1049 DstKnown.setAllOnes();
1050 }
1052 Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
1053 return;
1054 }
1055 Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
1056 return;
1057 }
1058
1060 computeKnownBitsFromCond(V, A, Known, SQ, !Invert, Depth + 1);
1061}
1062
1064 const SimplifyQuery &Q, unsigned Depth) {
1065 // Handle injected condition.
1066 if (Q.CC && Q.CC->AffectedValues.contains(V))
1068
1069 if (!Q.CxtI)
1070 return;
1071
1072 if (Q.DC && Q.DT) {
1073 // Handle dominating conditions.
1074 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
1075 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
1076 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
1077 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1078 /*Invert*/ false, Depth);
1079
1080 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
1081 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
1082 computeKnownBitsFromCond(V, BI->getCondition(), Known, Q,
1083 /*Invert*/ true, Depth);
1084 }
1085
1086 if (Known.hasConflict())
1087 Known.resetAll();
1088 }
1089
1090 if (!Q.AC)
1091 return;
1092
1093 unsigned BitWidth = Known.getBitWidth();
1094
1095 // Note that the patterns below need to be kept in sync with the code
1096 // in AssumptionCache::updateAffectedValues.
1097
1098 for (AssumptionCache::ResultElem &Elem : Q.AC->assumptionsFor(V)) {
1099 if (!Elem.Assume)
1100 continue;
1101
1102 AssumeInst *I = cast<AssumeInst>(Elem.Assume);
1103 assert(I->getParent()->getParent() == Q.CxtI->getParent()->getParent() &&
1104 "Got assumption for the wrong function!");
1105
1106 if (Elem.Index != AssumptionCache::ExprResultIdx) {
1107 if (auto OBU = I->getOperandBundleAt(Elem.Index);
1108 getBundleAttrFromOBU(OBU) == BundleAttr::Align) {
1109 auto [Ptr, _, _2, Alignment, Offset] = getAssumeAlignInfo(OBU);
1110 if (Ptr == V && Alignment && Offset && isPowerOf2_64(*Alignment) &&
1112 Known.Zero |= (*Alignment - 1) & ~*Offset;
1113 Known.One |= (*Alignment - 1) & *Offset;
1114 }
1115 }
1116 continue;
1117 }
1118
1119 // Warning: This loop can end up being somewhat performance sensitive.
1120 // We're running this loop for once for each value queried resulting in a
1121 // runtime of ~O(#assumes * #values).
1122
1123 Value *Arg = I->getArgOperand(0);
1124
1125 if (Arg == V && isValidAssumeForContext(I, Q)) {
1126 assert(BitWidth == 1 && "assume operand is not i1?");
1127 (void)BitWidth;
1128 Known.setAllOnes();
1129 return;
1130 }
1131 if (match(Arg, m_Not(m_Specific(V))) &&
1133 assert(BitWidth == 1 && "assume operand is not i1?");
1134 (void)BitWidth;
1135 Known.setAllZero();
1136 return;
1137 }
1138 auto *Trunc = dyn_cast<TruncInst>(Arg);
1139 if (Trunc && Trunc->getOperand(0) == V &&
1141 if (Trunc->hasNoUnsignedWrap()) {
1143 return;
1144 }
1145 Known.One.setBit(0);
1146 return;
1147 }
1148
1149 // The remaining tests are all recursive, so bail out if we hit the limit.
1151 continue;
1152
1153 ICmpInst *Cmp = dyn_cast<ICmpInst>(Arg);
1154 if (!Cmp)
1155 continue;
1156
1157 if (!isValidAssumeForContext(I, Q))
1158 continue;
1159
1160 computeKnownBitsFromICmpCond(V, Cmp, Known, Q, /*Invert=*/false);
1161 }
1162
1163 // Conflicting assumption: Undefined behavior will occur on this execution
1164 // path.
1165 if (Known.hasConflict())
1166 Known.resetAll();
1167}
1168
1169/// Compute known bits from a shift operator, including those with a
1170/// non-constant shift amount. Known is the output of this function. Known2 is a
1171/// pre-allocated temporary with the same bit width as Known and on return
1172/// contains the known bit of the shift value source. KF is an
1173/// operator-specific function that, given the known-bits and a shift amount,
1174/// compute the implied known-bits of the shift operator's result respectively
1175/// for that shift amount. The results from calling KF are conservatively
1176/// combined for all permitted shift amounts.
1178 const Operator *I, const APInt &DemandedElts, KnownBits &Known,
1179 KnownBits &Known2, const SimplifyQuery &Q, unsigned Depth,
1180 function_ref<KnownBits(const KnownBits &, const KnownBits &, bool)> KF) {
1181 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1182 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1183 // To limit compile-time impact, only query isKnownNonZero() if we know at
1184 // least something about the shift amount.
1185 bool ShAmtNonZero =
1186 Known.isNonZero() ||
1187 (Known.getMaxValue().ult(Known.getBitWidth()) &&
1188 isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth + 1));
1189 Known = KF(Known2, Known, ShAmtNonZero);
1190}
1191
1192static KnownBits
1193getKnownBitsFromAndXorOr(const Operator *I, const APInt &DemandedElts,
1194 const KnownBits &KnownLHS, const KnownBits &KnownRHS,
1195 const SimplifyQuery &Q, unsigned Depth) {
1196 unsigned BitWidth = KnownLHS.getBitWidth();
1197 KnownBits KnownOut(BitWidth);
1198 bool IsAnd = false;
1199 bool HasKnownOne = !KnownLHS.One.isZero() || !KnownRHS.One.isZero();
1200 Value *X = nullptr, *Y = nullptr;
1201
1202 switch (I->getOpcode()) {
1203 case Instruction::And:
1204 KnownOut = KnownLHS & KnownRHS;
1205 IsAnd = true;
1206 // and(x, -x) is common idioms that will clear all but lowest set
1207 // bit. If we have a single known bit in x, we can clear all bits
1208 // above it.
1209 // TODO: instcombine often reassociates independent `and` which can hide
1210 // this pattern. Try to match and(x, and(-x, y)) / and(and(x, y), -x).
1211 if (HasKnownOne && match(I, m_c_And(m_Value(X), m_Neg(m_Deferred(X))))) {
1212 // -(-x) == x so using whichever (LHS/RHS) gets us a better result.
1213 if (KnownLHS.countMaxTrailingZeros() <= KnownRHS.countMaxTrailingZeros())
1214 KnownOut = KnownLHS.blsi();
1215 else
1216 KnownOut = KnownRHS.blsi();
1217 }
1218 break;
1219 case Instruction::Or:
1220 KnownOut = KnownLHS | KnownRHS;
1221 break;
1222 case Instruction::Xor:
1223 KnownOut = KnownLHS ^ KnownRHS;
1224 // xor(x, x-1) is common idioms that will clear all but lowest set
1225 // bit. If we have a single known bit in x, we can clear all bits
1226 // above it.
1227 // TODO: xor(x, x-1) is often rewritting as xor(x, x-C) where C !=
1228 // -1 but for the purpose of demanded bits (xor(x, x-C) &
1229 // Demanded) == (xor(x, x-1) & Demanded). Extend the xor pattern
1230 // to use arbitrary C if xor(x, x-C) as the same as xor(x, x-1).
1231 if (HasKnownOne &&
1233 const KnownBits &XBits = I->getOperand(0) == X ? KnownLHS : KnownRHS;
1234 KnownOut = XBits.blsmsk();
1235 }
1236 break;
1237 default:
1238 llvm_unreachable("Invalid Op used in 'analyzeKnownBitsFromAndXorOr'");
1239 }
1240
1241 // and(x, add (x, -1)) is a common idiom that always clears the low bit;
1242 // xor/or(x, add (x, -1)) is an idiom that will always set the low bit.
1243 // here we handle the more general case of adding any odd number by
1244 // matching the form and/xor/or(x, add(x, y)) where y is odd.
1245 // TODO: This could be generalized to clearing any bit set in y where the
1246 // following bit is known to be unset in y.
1247 if (!KnownOut.Zero[0] && !KnownOut.One[0] &&
1251 KnownBits KnownY(BitWidth);
1252 computeKnownBits(Y, DemandedElts, KnownY, Q, Depth + 1);
1253 if (KnownY.countMinTrailingOnes() > 0) {
1254 if (IsAnd)
1255 KnownOut.Zero.setBit(0);
1256 else
1257 KnownOut.One.setBit(0);
1258 }
1259 }
1260 return KnownOut;
1261}
1262
1264 const Operator *I, const APInt &DemandedElts, const SimplifyQuery &Q,
1265 unsigned Depth,
1266 const function_ref<KnownBits(const KnownBits &, const KnownBits &)>
1267 KnownBitsFunc) {
1268 APInt DemandedEltsLHS, DemandedEltsRHS;
1270 DemandedElts, DemandedEltsLHS,
1271 DemandedEltsRHS);
1272
1273 const auto ComputeForSingleOpFunc =
1274 [Depth, &Q, KnownBitsFunc](const Value *Op, APInt &DemandedEltsOp) {
1275 return KnownBitsFunc(
1276 computeKnownBits(Op, DemandedEltsOp, Q, Depth + 1),
1277 computeKnownBits(Op, DemandedEltsOp << 1, Q, Depth + 1));
1278 };
1279
1280 if (DemandedEltsRHS.isZero())
1281 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS);
1282 if (DemandedEltsLHS.isZero())
1283 return ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS);
1284
1285 return ComputeForSingleOpFunc(I->getOperand(0), DemandedEltsLHS)
1286 .intersectWith(ComputeForSingleOpFunc(I->getOperand(1), DemandedEltsRHS));
1287}
1288
1289// Public so this can be used in `SimplifyDemandedUseBits`.
1291 const KnownBits &KnownLHS,
1292 const KnownBits &KnownRHS,
1293 const SimplifyQuery &SQ,
1294 unsigned Depth) {
1295 auto *FVTy = dyn_cast<FixedVectorType>(I->getType());
1296 APInt DemandedElts =
1297 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
1298
1299 return getKnownBitsFromAndXorOr(I, DemandedElts, KnownLHS, KnownRHS, SQ,
1300 Depth);
1301}
1302
1304 Attribute Attr = F->getFnAttribute(Attribute::VScaleRange);
1305 // Without vscale_range, we only know that vscale is non-zero.
1306 if (!Attr.isValid())
1308
1309 unsigned AttrMin = Attr.getVScaleRangeMin();
1310 // Minimum is larger than vscale width, result is always poison.
1311 if ((unsigned)llvm::bit_width(AttrMin) > BitWidth)
1312 return ConstantRange::getEmpty(BitWidth);
1313
1314 APInt Min(BitWidth, AttrMin);
1315 std::optional<unsigned> AttrMax = Attr.getVScaleRangeMax();
1316 if (!AttrMax || (unsigned)llvm::bit_width(*AttrMax) > BitWidth)
1318
1319 return ConstantRange(Min, APInt(BitWidth, *AttrMax) + 1);
1320}
1321
1323 Value *Arm, bool Invert,
1324 const SimplifyQuery &Q, unsigned Depth) {
1325 // If we have a constant arm, we are done.
1326 if (Known.isConstant())
1327 return;
1328
1329 // See what condition implies about the bits of the select arm.
1330 KnownBits CondRes(Known.getBitWidth());
1331 computeKnownBitsFromCond(Arm, Cond, CondRes, Q, Invert, Depth + 1);
1332 // If we don't get any information from the condition, no reason to
1333 // proceed.
1334 if (CondRes.isUnknown())
1335 return;
1336
1337 // We can have conflict if the condition is dead. I.e if we have
1338 // (x | 64) < 32 ? (x | 64) : y
1339 // we will have conflict at bit 6 from the condition/the `or`.
1340 // In that case just return. Its not particularly important
1341 // what we do, as this select is going to be simplified soon.
1342 CondRes = CondRes.unionWith(Known);
1343 if (CondRes.hasConflict())
1344 return;
1345
1346 // Finally make sure the information we found is valid. This is relatively
1347 // expensive so it's left for the very end.
1348 if (!isGuaranteedNotToBeUndef(Arm, Q.AC, Q.CxtI, Q.DT, Depth + 1))
1349 return;
1350
1351 // Finally, we know we get information from the condition and its valid,
1352 // so return it.
1353 Known = std::move(CondRes);
1354}
1355
1356// Match a signed min+max clamp pattern like smax(smin(In, CHigh), CLow).
1357// Returns the input and lower/upper bounds.
1358static bool isSignedMinMaxClamp(const Value *Select, const Value *&In,
1359 const APInt *&CLow, const APInt *&CHigh) {
1361 cast<Operator>(Select)->getOpcode() == Instruction::Select &&
1362 "Input should be a Select!");
1363
1364 const Value *LHS = nullptr, *RHS = nullptr;
1366 if (SPF != SPF_SMAX && SPF != SPF_SMIN)
1367 return false;
1368
1369 if (!match(RHS, m_APInt(CLow)))
1370 return false;
1371
1372 const Value *LHS2 = nullptr, *RHS2 = nullptr;
1374 if (getInverseMinMaxFlavor(SPF) != SPF2)
1375 return false;
1376
1377 if (!match(RHS2, m_APInt(CHigh)))
1378 return false;
1379
1380 if (SPF == SPF_SMIN)
1381 std::swap(CLow, CHigh);
1382
1383 In = LHS2;
1384 return CLow->sle(*CHigh);
1385}
1386
1388 const APInt *&CLow,
1389 const APInt *&CHigh) {
1390 assert((II->getIntrinsicID() == Intrinsic::smin ||
1391 II->getIntrinsicID() == Intrinsic::smax) &&
1392 "Must be smin/smax");
1393
1394 Intrinsic::ID InverseID = getInverseMinMaxIntrinsic(II->getIntrinsicID());
1395 auto *InnerII = dyn_cast<IntrinsicInst>(II->getArgOperand(0));
1396 if (!InnerII || InnerII->getIntrinsicID() != InverseID ||
1397 !match(II->getArgOperand(1), m_APInt(CLow)) ||
1398 !match(InnerII->getArgOperand(1), m_APInt(CHigh)))
1399 return false;
1400
1401 if (II->getIntrinsicID() == Intrinsic::smin)
1402 std::swap(CLow, CHigh);
1403 return CLow->sle(*CHigh);
1404}
1405
1407 KnownBits &Known) {
1408 const APInt *CLow, *CHigh;
1409 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
1410 Known = Known.unionWith(
1411 ConstantRange::getNonEmpty(*CLow, *CHigh + 1).toKnownBits());
1412}
1413
1415 const APInt &DemandedElts,
1417 const SimplifyQuery &Q,
1418 unsigned Depth) {
1419 unsigned BitWidth = Known.getBitWidth();
1420
1421 KnownBits Known2(BitWidth);
1422 switch (I->getOpcode()) {
1423 default: break;
1424 case Instruction::Load:
1425 if (MDNode *MD =
1426 Q.IIQ.getMetadata(cast<LoadInst>(I), LLVMContext::MD_range))
1428 break;
1429 case Instruction::And:
1430 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1431 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1432
1433 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1434 break;
1435 case Instruction::Or:
1436 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1437 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1438
1439 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1440 break;
1441 case Instruction::Xor:
1442 computeKnownBits(I->getOperand(1), DemandedElts, Known, Q, Depth + 1);
1443 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
1444
1445 Known = getKnownBitsFromAndXorOr(I, DemandedElts, Known2, Known, Q, Depth);
1446 break;
1447 case Instruction::Mul: {
1450 computeKnownBitsMul(I->getOperand(0), I->getOperand(1), NSW, NUW,
1451 DemandedElts, Known, Known2, Q, Depth);
1452 break;
1453 }
1454 case Instruction::UDiv: {
1455 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1456 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1457 Known =
1459 break;
1460 }
1461 case Instruction::SDiv: {
1462 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1463 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1464 Known =
1466 break;
1467 }
1468 case Instruction::Select: {
1469 auto ComputeForArm = [&](Value *Arm, bool Invert) {
1470 KnownBits Res(Known.getBitWidth());
1471 computeKnownBits(Arm, DemandedElts, Res, Q, Depth + 1);
1472 adjustKnownBitsForSelectArm(Res, I->getOperand(0), Arm, Invert, Q, Depth);
1473 return Res;
1474 };
1475 // Only known if known in both the LHS and RHS.
1476 Known =
1477 ComputeForArm(I->getOperand(1), /*Invert=*/false)
1478 .intersectWith(ComputeForArm(I->getOperand(2), /*Invert=*/true));
1479 break;
1480 }
1481 case Instruction::FPTrunc:
1482 case Instruction::FPExt:
1483 case Instruction::FPToUI:
1484 case Instruction::FPToSI:
1485 case Instruction::SIToFP:
1486 case Instruction::UIToFP:
1487 break; // Can't work with floating point.
1488 case Instruction::PtrToInt:
1489 case Instruction::PtrToAddr:
1490 case Instruction::IntToPtr:
1491 // Fall through and handle them the same as zext/trunc.
1492 [[fallthrough]];
1493 case Instruction::ZExt:
1494 case Instruction::Trunc: {
1495 Type *SrcTy = I->getOperand(0)->getType();
1496
1497 unsigned SrcBitWidth;
1498 // Note that we handle pointer operands here because of inttoptr/ptrtoint
1499 // which fall through here.
1500 Type *ScalarTy = SrcTy->getScalarType();
1501 SrcBitWidth = ScalarTy->isPointerTy() ?
1502 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
1503 Q.DL.getTypeSizeInBits(ScalarTy);
1504
1505 assert(SrcBitWidth && "SrcBitWidth can't be zero");
1506 Known = Known.anyextOrTrunc(SrcBitWidth);
1507 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1508 if (auto *Inst = dyn_cast<PossiblyNonNegInst>(I);
1509 Inst && Inst->hasNonNeg() && !Known.isNegative())
1510 Known.makeNonNegative();
1511 Known = Known.zextOrTrunc(BitWidth);
1512 break;
1513 }
1514 case Instruction::BitCast: {
1515 Type *SrcTy = I->getOperand(0)->getType();
1516 if (SrcTy->isIntOrPtrTy() &&
1517 // TODO: For now, not handling conversions like:
1518 // (bitcast i64 %x to <2 x i32>)
1519 !I->getType()->isVectorTy()) {
1520 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1521 break;
1522 }
1523
1524 const Value *V;
1525 // Handle bitcast from floating point to integer.
1526 if (match(I, m_ElementWiseBitCast(m_Value(V))) &&
1527 V->getType()->isFPOrFPVectorTy()) {
1528 Type *FPType = V->getType()->getScalarType();
1529 KnownFPClass Result =
1530 computeKnownFPClass(V, DemandedElts, fcAllFlags, Q, Depth + 1);
1531
1532 Known = Result.toKnownBits(FPType->getFltSemantics());
1533
1534 break;
1535 }
1536
1537 // Handle cast from vector integer type to scalar or vector integer.
1538 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcTy);
1539 if (!SrcVecTy || !SrcVecTy->getElementType()->isIntegerTy() ||
1540 !I->getType()->isIntOrIntVectorTy() ||
1541 isa<ScalableVectorType>(I->getType()))
1542 break;
1543
1544 unsigned NumElts = DemandedElts.getBitWidth();
1545 bool IsLE = Q.DL.isLittleEndian();
1546 // Look through a cast from narrow vector elements to wider type.
1547 // Examples: v4i32 -> v2i64, v3i8 -> v24
1548 unsigned SubBitWidth = SrcVecTy->getScalarSizeInBits();
1549 if (BitWidth % SubBitWidth == 0) {
1550 // Known bits are automatically intersected across demanded elements of a
1551 // vector. So for example, if a bit is computed as known zero, it must be
1552 // zero across all demanded elements of the vector.
1553 //
1554 // For this bitcast, each demanded element of the output is sub-divided
1555 // across a set of smaller vector elements in the source vector. To get
1556 // the known bits for an entire element of the output, compute the known
1557 // bits for each sub-element sequentially. This is done by shifting the
1558 // one-set-bit demanded elements parameter across the sub-elements for
1559 // consecutive calls to computeKnownBits. We are using the demanded
1560 // elements parameter as a mask operator.
1561 //
1562 // The known bits of each sub-element are then inserted into place
1563 // (dependent on endian) to form the full result of known bits.
1564 unsigned SubScale = BitWidth / SubBitWidth;
1565 APInt SubDemandedElts = APInt::getZero(NumElts * SubScale);
1566 for (unsigned i = 0; i != NumElts; ++i) {
1567 if (DemandedElts[i])
1568 SubDemandedElts.setBit(i * SubScale);
1569 }
1570
1571 KnownBits KnownSrc(SubBitWidth);
1572 for (unsigned i = 0; i != SubScale; ++i) {
1573 computeKnownBits(I->getOperand(0), SubDemandedElts.shl(i), KnownSrc, Q,
1574 Depth + 1);
1575 unsigned ShiftElt = IsLE ? i : SubScale - 1 - i;
1576 Known.insertBits(KnownSrc, ShiftElt * SubBitWidth);
1577 }
1578 }
1579 // Look through a cast from wider vector elements to narrow type.
1580 // Examples: v2i64 -> v4i32
1581 if (SubBitWidth % BitWidth == 0) {
1582 unsigned SubScale = SubBitWidth / BitWidth;
1583 KnownBits KnownSrc(SubBitWidth);
1584 APInt SubDemandedElts =
1585 APIntOps::ScaleBitMask(DemandedElts, NumElts / SubScale);
1586 computeKnownBits(I->getOperand(0), SubDemandedElts, KnownSrc, Q,
1587 Depth + 1);
1588
1589 Known.setAllConflict();
1590 for (unsigned i = 0; i != NumElts; ++i) {
1591 if (DemandedElts[i]) {
1592 unsigned Shifts = IsLE ? i : NumElts - 1 - i;
1593 unsigned Offset = (Shifts % SubScale) * BitWidth;
1594 Known = Known.intersectWith(KnownSrc.extractBits(BitWidth, Offset));
1595 if (Known.isUnknown())
1596 break;
1597 }
1598 }
1599 }
1600 break;
1601 }
1602 case Instruction::SExt: {
1603 // Compute the bits in the result that are not present in the input.
1604 unsigned SrcBitWidth = I->getOperand(0)->getType()->getScalarSizeInBits();
1605
1606 Known = Known.trunc(SrcBitWidth);
1607 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1608 // If the sign bit of the input is known set or clear, then we know the
1609 // top bits of the result.
1610 Known = Known.sext(BitWidth);
1611 break;
1612 }
1613 case Instruction::Shl: {
1616 auto KF = [NUW, NSW](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1617 bool ShAmtNonZero) {
1618 return KnownBits::shl(KnownVal, KnownAmt, NUW, NSW, ShAmtNonZero);
1619 };
1620 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1621 KF);
1622 // Trailing zeros of a right-shifted constant never decrease.
1623 const APInt *C;
1624 if (match(I->getOperand(0), m_APInt(C)))
1625 Known.Zero.setLowBits(C->countr_zero());
1626
1627 // shl X, sub(Y, xor(ctlz(X, true), BitWidth-1)) shifts X so that its MSB
1628 // lands at bit Y, when BitWidth is a power of 2.
1629 const APInt *YC;
1630 Value *X = I->getOperand(0);
1631 if (isPowerOf2_32(BitWidth) &&
1632 match(I->getOperand(1),
1634 m_SpecificInt(BitWidth - 1)))) &&
1635 YC->ult(BitWidth - 1)) {
1636 unsigned Y = YC->getZExtValue();
1637 Known.One.setBit(Y);
1638 Known.Zero.setBitsFrom(Y + 1);
1639 }
1640 break;
1641 }
1642 case Instruction::LShr: {
1643 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1644 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1645 bool ShAmtNonZero) {
1646 return KnownBits::lshr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1647 };
1648 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1649 KF);
1650 // Leading zeros of a left-shifted constant never decrease.
1651 const APInt *C;
1652 if (match(I->getOperand(0), m_APInt(C)))
1653 Known.Zero.setHighBits(C->countl_zero());
1654 break;
1655 }
1656 case Instruction::AShr: {
1657 bool Exact = Q.IIQ.isExact(cast<BinaryOperator>(I));
1658 auto KF = [Exact](const KnownBits &KnownVal, const KnownBits &KnownAmt,
1659 bool ShAmtNonZero) {
1660 return KnownBits::ashr(KnownVal, KnownAmt, ShAmtNonZero, Exact);
1661 };
1662 computeKnownBitsFromShiftOperator(I, DemandedElts, Known, Known2, Q, Depth,
1663 KF);
1664 break;
1665 }
1666 case Instruction::Sub: {
1669 computeKnownBitsAddSub(false, I->getOperand(0), I->getOperand(1), NSW, NUW,
1670 DemandedElts, Known, Known2, Q, Depth);
1671 break;
1672 }
1673 case Instruction::Add: {
1676 computeKnownBitsAddSub(true, I->getOperand(0), I->getOperand(1), NSW, NUW,
1677 DemandedElts, Known, Known2, Q, Depth);
1678 break;
1679 }
1680 case Instruction::SRem:
1681 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1682 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1683 Known = KnownBits::srem(Known, Known2);
1684 break;
1685
1686 case Instruction::URem:
1687 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
1688 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
1689 Known = KnownBits::urem(Known, Known2);
1690 break;
1691 case Instruction::Alloca:
1692 Known.Zero.setLowBits(Log2(cast<AllocaInst>(I)->getAlign()));
1693 break;
1694 case Instruction::GetElementPtr: {
1695 // Analyze all of the subscripts of this getelementptr instruction
1696 // to determine if we can prove known low zero bits.
1697 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
1698 // Accumulate the constant indices in a separate variable
1699 // to minimize the number of calls to computeForAddSub.
1700 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(I->getType());
1701 APInt AccConstIndices(IndexWidth, 0);
1702
1703 auto AddIndexToKnown = [&](KnownBits IndexBits) {
1704 if (IndexWidth == BitWidth) {
1705 // Note that inbounds does *not* guarantee nsw for the addition, as only
1706 // the offset is signed, while the base address is unsigned.
1707 Known = KnownBits::add(Known, IndexBits);
1708 } else {
1709 // If the index width is smaller than the pointer width, only add the
1710 // value to the low bits.
1711 assert(IndexWidth < BitWidth &&
1712 "Index width can't be larger than pointer width");
1713 Known.insertBits(KnownBits::add(Known.trunc(IndexWidth), IndexBits), 0);
1714 }
1715 };
1716
1718 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1719 // TrailZ can only become smaller, short-circuit if we hit zero.
1720 if (Known.isUnknown())
1721 break;
1722
1723 Value *Index = I->getOperand(i);
1724
1725 // Handle case when index is zero.
1726 Constant *CIndex = dyn_cast<Constant>(Index);
1727 if (CIndex && CIndex->isNullValue())
1728 continue;
1729
1730 if (StructType *STy = GTI.getStructTypeOrNull()) {
1731 // Handle struct member offset arithmetic.
1732
1733 assert(CIndex &&
1734 "Access to structure field must be known at compile time");
1735
1736 if (CIndex->getType()->isVectorTy())
1737 Index = CIndex->getSplatValue();
1738
1739 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1740 const StructLayout *SL = Q.DL.getStructLayout(STy);
1741 uint64_t Offset = SL->getElementOffset(Idx);
1742 AccConstIndices += Offset;
1743 continue;
1744 }
1745
1746 // Handle array index arithmetic.
1747 Type *IndexedTy = GTI.getIndexedType();
1748 if (!IndexedTy->isSized()) {
1749 Known.resetAll();
1750 break;
1751 }
1752
1753 TypeSize Stride = GTI.getSequentialElementStride(Q.DL);
1754 uint64_t StrideInBytes = Stride.getKnownMinValue();
1755 if (!Stride.isScalable()) {
1756 // Fast path for constant offset.
1757 if (auto *CI = dyn_cast<ConstantInt>(Index)) {
1758 AccConstIndices +=
1759 CI->getValue().sextOrTrunc(IndexWidth) * StrideInBytes;
1760 continue;
1761 }
1762 }
1763
1764 KnownBits IndexBits =
1765 computeKnownBits(Index, Q, Depth + 1).sextOrTrunc(IndexWidth);
1766 KnownBits ScalingFactor(IndexWidth);
1767 // Multiply by current sizeof type.
1768 // &A[i] == A + i * sizeof(*A[i]).
1769 if (Stride.isScalable()) {
1770 // For scalable types the only thing we know about sizeof is
1771 // that this is a multiple of the minimum size.
1772 ScalingFactor.Zero.setLowBits(llvm::countr_zero(StrideInBytes));
1773 } else {
1774 ScalingFactor =
1775 KnownBits::makeConstant(APInt(IndexWidth, StrideInBytes));
1776 }
1777 AddIndexToKnown(KnownBits::mul(IndexBits, ScalingFactor));
1778 }
1779 if (!Known.isUnknown() && !AccConstIndices.isZero())
1780 AddIndexToKnown(KnownBits::makeConstant(AccConstIndices));
1781 break;
1782 }
1783 case Instruction::PHI: {
1784 const PHINode *P = cast<PHINode>(I);
1785 BinaryOperator *BO = nullptr;
1786 Value *R = nullptr, *L = nullptr;
1787 if (matchSimpleRecurrence(P, BO, R, L)) {
1788 // Handle the case of a simple two-predecessor recurrence PHI.
1789 // There's a lot more that could theoretically be done here, but
1790 // this is sufficient to catch some interesting cases.
1791 unsigned Opcode = BO->getOpcode();
1792
1793 switch (Opcode) {
1794 // If this is a shift recurrence, we know the bits being shifted in. We
1795 // can combine that with information about the start value of the
1796 // recurrence to conclude facts about the result. If this is a udiv
1797 // recurrence, we know that the result can never exceed either the
1798 // numerator or the start value, whichever is greater.
1799 case Instruction::LShr:
1800 case Instruction::AShr:
1801 case Instruction::Shl:
1802 case Instruction::UDiv:
1803 if (BO->getOperand(0) != I)
1804 break;
1805 [[fallthrough]];
1806
1807 // For a urem recurrence, the result can never exceed the start value. The
1808 // phi could either be the numerator or the denominator.
1809 case Instruction::URem: {
1810 // We have matched a recurrence of the form:
1811 // %iv = [R, %entry], [%iv.next, %backedge]
1812 // %iv.next = shift_op %iv, L
1813
1814 // Recurse with the phi context to avoid concern about whether facts
1815 // inferred hold at original context instruction. TODO: It may be
1816 // correct to use the original context. IF warranted, explore and
1817 // add sufficient tests to cover.
1819 RecQ.CxtI = P;
1820 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1821 switch (Opcode) {
1822 case Instruction::Shl:
1823 // A shl recurrence will only increase the tailing zeros
1824 Known.Zero.setLowBits(Known2.countMinTrailingZeros());
1825 break;
1826 case Instruction::LShr:
1827 case Instruction::UDiv:
1828 case Instruction::URem:
1829 // lshr, udiv, and urem recurrences will preserve the leading zeros of
1830 // the start value.
1831 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1832 break;
1833 case Instruction::AShr:
1834 // An ashr recurrence will extend the initial sign bit
1835 Known.Zero.setHighBits(Known2.countMinLeadingZeros());
1836 Known.One.setHighBits(Known2.countMinLeadingOnes());
1837 break;
1838 }
1839 break;
1840 }
1841
1842 // Check for operations that have the property that if
1843 // both their operands have low zero bits, the result
1844 // will have low zero bits.
1845 case Instruction::Add:
1846 case Instruction::Sub:
1847 case Instruction::And:
1848 case Instruction::Or:
1849 case Instruction::Mul: {
1850 // Change the context instruction to the "edge" that flows into the
1851 // phi. This is important because that is where the value is actually
1852 // "evaluated" even though it is used later somewhere else. (see also
1853 // D69571).
1855
1856 unsigned OpNum = P->getOperand(0) == R ? 0 : 1;
1857 Instruction *RInst = P->getIncomingBlock(OpNum)->getTerminator();
1858 Instruction *LInst = P->getIncomingBlock(1 - OpNum)->getTerminator();
1859
1860 // Ok, we have a PHI of the form L op= R. Check for low
1861 // zero bits.
1862 RecQ.CxtI = RInst;
1863 computeKnownBits(R, DemandedElts, Known2, RecQ, Depth + 1);
1864
1865 // We need to take the minimum number of known bits
1866 KnownBits Known3(BitWidth);
1867 RecQ.CxtI = LInst;
1868 computeKnownBits(L, DemandedElts, Known3, RecQ, Depth + 1);
1869
1870 Known.Zero.setLowBits(std::min(Known2.countMinTrailingZeros(),
1871 Known3.countMinTrailingZeros()));
1872
1873 auto *OverflowOp = dyn_cast<OverflowingBinaryOperator>(BO);
1874 if (!OverflowOp || !Q.IIQ.hasNoSignedWrap(OverflowOp))
1875 break;
1876
1877 switch (Opcode) {
1878 // If initial value of recurrence is nonnegative, and we are adding
1879 // a nonnegative number with nsw, the result can only be nonnegative
1880 // or poison value regardless of the number of times we execute the
1881 // add in phi recurrence. If initial value is negative and we are
1882 // adding a negative number with nsw, the result can only be
1883 // negative or poison value. Similar arguments apply to sub and mul.
1884 //
1885 // (add non-negative, non-negative) --> non-negative
1886 // (add negative, negative) --> negative
1887 case Instruction::Add: {
1888 if (Known2.isNonNegative() && Known3.isNonNegative())
1889 Known.makeNonNegative();
1890 else if (Known2.isNegative() && Known3.isNegative())
1891 Known.makeNegative();
1892 break;
1893 }
1894
1895 // (sub nsw non-negative, negative) --> non-negative
1896 // (sub nsw negative, non-negative) --> negative
1897 case Instruction::Sub: {
1898 if (BO->getOperand(0) != I)
1899 break;
1900 if (Known2.isNonNegative() && Known3.isNegative())
1901 Known.makeNonNegative();
1902 else if (Known2.isNegative() && Known3.isNonNegative())
1903 Known.makeNegative();
1904 break;
1905 }
1906
1907 // (mul nsw non-negative, non-negative) --> non-negative
1908 case Instruction::Mul:
1909 if (Known2.isNonNegative() && Known3.isNonNegative())
1910 Known.makeNonNegative();
1911 break;
1912
1913 default:
1914 break;
1915 }
1916 break;
1917 }
1918
1919 default:
1920 break;
1921 }
1922 }
1923
1924 // Unreachable blocks may have zero-operand PHI nodes.
1925 if (P->getNumIncomingValues() == 0)
1926 break;
1927
1928 // Otherwise take the unions of the known bit sets of the operands,
1929 // taking conservative care to avoid excessive recursion.
1930 if (Depth < MaxAnalysisRecursionDepth - 1 && Known.isUnknown()) {
1931 // Skip if every incoming value references to ourself.
1932 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
1933 break;
1934
1935 Known.setAllConflict();
1936 for (const Use &U : P->operands()) {
1937 Value *IncValue;
1938 const PHINode *CxtPhi;
1939 Instruction *CxtI;
1940 breakSelfRecursivePHI(&U, P, IncValue, CxtI, &CxtPhi);
1941 // Skip direct self references.
1942 if (IncValue == P)
1943 continue;
1944
1945 // Change the context instruction to the "edge" that flows into the
1946 // phi. This is important because that is where the value is actually
1947 // "evaluated" even though it is used later somewhere else. (see also
1948 // D69571).
1950
1951 Known2 = KnownBits(BitWidth);
1952
1953 // Recurse, but cap the recursion to one level, because we don't
1954 // want to waste time spinning around in loops.
1955 // TODO: See if we can base recursion limiter on number of incoming phi
1956 // edges so we don't overly clamp analysis.
1957 computeKnownBits(IncValue, DemandedElts, Known2, RecQ,
1959
1960 // See if we can further use a conditional branch into the phi
1961 // to help us determine the range of the value.
1962 if (!Known2.isConstant()) {
1963 CmpPredicate Pred;
1964 const APInt *RHSC;
1965 BasicBlock *TrueSucc, *FalseSucc;
1966 // TODO: Use RHS Value and compute range from its known bits.
1967 if (match(RecQ.CxtI,
1968 m_Br(m_c_ICmp(Pred, m_Specific(IncValue), m_APInt(RHSC)),
1969 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
1970 // Check for cases of duplicate successors.
1971 if ((TrueSucc == CxtPhi->getParent()) !=
1972 (FalseSucc == CxtPhi->getParent())) {
1973 // If we're using the false successor, invert the predicate.
1974 if (FalseSucc == CxtPhi->getParent())
1975 Pred = CmpInst::getInversePredicate(Pred);
1976 // Get the knownbits implied by the incoming phi condition.
1977 auto CR = ConstantRange::makeExactICmpRegion(Pred, *RHSC);
1978 KnownBits KnownUnion = Known2.unionWith(CR.toKnownBits());
1979 // We can have conflicts here if we are analyzing deadcode (its
1980 // impossible for us reach this BB based the icmp).
1981 if (KnownUnion.hasConflict()) {
1982 // No reason to continue analyzing in a known dead region, so
1983 // just resetAll and break. This will cause us to also exit the
1984 // outer loop.
1985 Known.resetAll();
1986 break;
1987 }
1988 Known2 = KnownUnion;
1989 }
1990 }
1991 }
1992
1993 Known = Known.intersectWith(Known2);
1994 // If all bits have been ruled out, there's no need to check
1995 // more operands.
1996 if (Known.isUnknown())
1997 break;
1998 }
1999 }
2000 break;
2001 }
2002 case Instruction::Call:
2003 case Instruction::Invoke: {
2004 // If range metadata is attached to this call, set known bits from that,
2005 // and then intersect with known bits based on other properties of the
2006 // function.
2007 if (MDNode *MD =
2008 Q.IIQ.getMetadata(cast<Instruction>(I), LLVMContext::MD_range))
2010
2011 const auto *CB = cast<CallBase>(I);
2012
2013 if (std::optional<ConstantRange> Range = CB->getRange())
2014 Known = Known.unionWith(Range->toKnownBits());
2015
2016 if (const Value *RV = CB->getReturnedArgOperand()) {
2017 if (RV->getType() == I->getType()) {
2018 computeKnownBits(RV, Known2, Q, Depth + 1);
2019 Known = Known.unionWith(Known2);
2020 // If the function doesn't return properly for all input values
2021 // (e.g. unreachable exits) then there might be conflicts between the
2022 // argument value and the range metadata. Simply discard the known bits
2023 // in case of conflicts.
2024 if (Known.hasConflict())
2025 Known.resetAll();
2026 }
2027 }
2028 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
2029 switch (II->getIntrinsicID()) {
2030 default:
2031 break;
2032 case Intrinsic::abs: {
2033 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2034 bool IntMinIsPoison = match(II->getArgOperand(1), m_One());
2035 Known = Known.unionWith(Known2.abs(IntMinIsPoison));
2036 break;
2037 }
2038 case Intrinsic::bitreverse:
2039 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2040 Known = Known.unionWith(Known2.reverseBits());
2041 break;
2042 case Intrinsic::bswap:
2043 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2044 Known = Known.unionWith(Known2.byteSwap());
2045 break;
2046 case Intrinsic::ctlz: {
2047 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2048 // If we have a known 1, its position is our upper bound.
2049 unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2050 // If this call is poison for 0 input, the result will be less than 2^n.
2051 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2052 PossibleLZ = std::min(PossibleLZ, BitWidth - 1);
2053 unsigned LowBits = llvm::bit_width(PossibleLZ);
2054 Known.Zero.setBitsFrom(LowBits);
2055 break;
2056 }
2057 case Intrinsic::cttz: {
2058 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2059 // If we have a known 1, its position is our upper bound.
2060 unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2061 // If this call is poison for 0 input, the result will be less than 2^n.
2062 if (II->getArgOperand(1) == ConstantInt::getTrue(II->getContext()))
2063 PossibleTZ = std::min(PossibleTZ, BitWidth - 1);
2064 unsigned LowBits = llvm::bit_width(PossibleTZ);
2065 Known.Zero.setBitsFrom(LowBits);
2066 break;
2067 }
2068 case Intrinsic::ctpop: {
2069 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2070 // We can bound the space the count needs. Also, bits known to be zero
2071 // can't contribute to the population.
2072 unsigned BitsPossiblySet = Known2.countMaxPopulation();
2073 unsigned LowBits = llvm::bit_width(BitsPossiblySet);
2074 Known.Zero.setBitsFrom(LowBits);
2075 // TODO: we could bound KnownOne using the lower bound on the number
2076 // of bits which might be set provided by popcnt KnownOne2.
2077 break;
2078 }
2079 case Intrinsic::fshr:
2080 case Intrinsic::fshl: {
2081 const APInt *SA;
2082 if (!match(I->getOperand(2), m_APInt(SA)))
2083 break;
2084
2085 KnownBits Known3(BitWidth);
2086 computeKnownBits(I->getOperand(0), DemandedElts, Known2, Q, Depth + 1);
2087 computeKnownBits(I->getOperand(1), DemandedElts, Known3, Q, Depth + 1);
2088 Known = II->getIntrinsicID() == Intrinsic::fshl
2089 ? KnownBits::fshl(Known2, Known3, *SA)
2090 : KnownBits::fshr(Known2, Known3, *SA);
2091 break;
2092 }
2093 case Intrinsic::clmul:
2094 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2095 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2096 Known = KnownBits::clmul(Known, Known2);
2097 break;
2098 case Intrinsic::pext:
2099 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2100 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2101 Known = KnownBits::pext(Known, Known2);
2102 break;
2103 case Intrinsic::pdep:
2104 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2105 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2106 Known = KnownBits::pdep(Known, Known2);
2107 break;
2108 case Intrinsic::uadd_sat:
2109 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2110 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2111 Known = KnownBits::uadd_sat(Known, Known2);
2112 break;
2113 case Intrinsic::usub_sat:
2114 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2115 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2116 Known = KnownBits::usub_sat(Known, Known2);
2117 break;
2118 case Intrinsic::sadd_sat:
2119 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2120 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2121 Known = KnownBits::sadd_sat(Known, Known2);
2122 break;
2123 case Intrinsic::ssub_sat:
2124 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2125 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2126 Known = KnownBits::ssub_sat(Known, Known2);
2127 break;
2128 // Vec reverse preserves bits from input vec.
2129 case Intrinsic::vector_reverse:
2130 computeKnownBits(I->getOperand(0), DemandedElts.reverseBits(), Known, Q,
2131 Depth + 1);
2132 break;
2133 // for min/max/and/or reduce, any bit common to each element in the
2134 // input vec is set in the output.
2135 case Intrinsic::vector_reduce_and:
2136 case Intrinsic::vector_reduce_or:
2137 case Intrinsic::vector_reduce_umax:
2138 case Intrinsic::vector_reduce_umin:
2139 case Intrinsic::vector_reduce_smax:
2140 case Intrinsic::vector_reduce_smin:
2141 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2142 break;
2143 case Intrinsic::vector_reduce_xor: {
2144 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2145 // The zeros common to all vecs are zero in the output.
2146 // If the number of elements is odd, then the common ones remain. If the
2147 // number of elements is even, then the common ones becomes zeros.
2148 auto *VecTy = cast<VectorType>(I->getOperand(0)->getType());
2149 // Even, so the ones become zeros.
2150 bool EvenCnt = VecTy->getElementCount().isKnownEven();
2151 if (EvenCnt)
2152 Known.Zero |= Known.One;
2153 // Maybe even element count so need to clear ones.
2154 if (VecTy->isScalableTy() || EvenCnt)
2155 Known.One.clearAllBits();
2156 break;
2157 }
2158 case Intrinsic::vector_reduce_add: {
2159 auto *VecTy = dyn_cast<FixedVectorType>(I->getOperand(0)->getType());
2160 if (!VecTy)
2161 break;
2162 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2163 Known = Known.reduceAdd(VecTy->getNumElements());
2164 break;
2165 }
2166 case Intrinsic::umin:
2167 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2168 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2169 Known = KnownBits::umin(Known, Known2);
2170 break;
2171 case Intrinsic::umax:
2172 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2173 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2174 Known = KnownBits::umax(Known, Known2);
2175 break;
2176 case Intrinsic::smin:
2177 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2178 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2179 Known = KnownBits::smin(Known, Known2);
2181 break;
2182 case Intrinsic::smax:
2183 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2184 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2185 Known = KnownBits::smax(Known, Known2);
2187 break;
2188 case Intrinsic::ptrmask: {
2189 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2190
2191 const Value *Mask = I->getOperand(1);
2192 Known2 = KnownBits(Mask->getType()->getScalarSizeInBits());
2193 computeKnownBits(Mask, DemandedElts, Known2, Q, Depth + 1);
2194 // TODO: 1-extend would be more precise.
2195 Known &= Known2.anyextOrTrunc(BitWidth);
2196 break;
2197 }
2198 case Intrinsic::x86_sse2_pmulh_w:
2199 case Intrinsic::x86_avx2_pmulh_w:
2200 case Intrinsic::x86_avx512_pmulh_w_512:
2201 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2202 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2203 Known = KnownBits::mulhs(Known, Known2);
2204 break;
2205 case Intrinsic::x86_sse2_pmulhu_w:
2206 case Intrinsic::x86_avx2_pmulhu_w:
2207 case Intrinsic::x86_avx512_pmulhu_w_512:
2208 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth + 1);
2209 computeKnownBits(I->getOperand(1), DemandedElts, Known2, Q, Depth + 1);
2210 Known = KnownBits::mulhu(Known, Known2);
2211 break;
2212 case Intrinsic::x86_sse42_crc32_64_64:
2213 Known.Zero.setBitsFrom(32);
2214 break;
2215 case Intrinsic::x86_ssse3_phadd_d_128:
2216 case Intrinsic::x86_ssse3_phadd_w_128:
2217 case Intrinsic::x86_avx2_phadd_d:
2218 case Intrinsic::x86_avx2_phadd_w: {
2220 I, DemandedElts, Q, Depth,
2221 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2222 return KnownBits::add(KnownLHS, KnownRHS);
2223 });
2224 break;
2225 }
2226 case Intrinsic::x86_ssse3_phadd_sw_128:
2227 case Intrinsic::x86_avx2_phadd_sw: {
2229 I, DemandedElts, Q, Depth, KnownBits::sadd_sat);
2230 break;
2231 }
2232 case Intrinsic::x86_ssse3_phsub_d_128:
2233 case Intrinsic::x86_ssse3_phsub_w_128:
2234 case Intrinsic::x86_avx2_phsub_d:
2235 case Intrinsic::x86_avx2_phsub_w: {
2237 I, DemandedElts, Q, Depth,
2238 [](const KnownBits &KnownLHS, const KnownBits &KnownRHS) {
2239 return KnownBits::sub(KnownLHS, KnownRHS);
2240 });
2241 break;
2242 }
2243 case Intrinsic::x86_ssse3_phsub_sw_128:
2244 case Intrinsic::x86_avx2_phsub_sw: {
2246 I, DemandedElts, Q, Depth, KnownBits::ssub_sat);
2247 break;
2248 }
2249 case Intrinsic::riscv_vsetvli:
2250 case Intrinsic::riscv_vsetvlimax: {
2251 bool HasAVL = II->getIntrinsicID() == Intrinsic::riscv_vsetvli;
2252 const ConstantRange Range = getVScaleRange(II->getFunction(), BitWidth);
2254 cast<ConstantInt>(II->getArgOperand(HasAVL))->getZExtValue());
2255 RISCVVType::VLMUL VLMUL = static_cast<RISCVVType::VLMUL>(
2256 cast<ConstantInt>(II->getArgOperand(1 + HasAVL))->getZExtValue());
2257 uint64_t MaxVLEN =
2258 Range.getUnsignedMax().getZExtValue() * RISCV::RVVBitsPerBlock;
2259 uint64_t MaxVL = MaxVLEN / RISCVVType::getSEWLMULRatio(SEW, VLMUL);
2260
2261 // Result of vsetvli must be not larger than AVL.
2262 if (HasAVL)
2263 if (auto *CI = dyn_cast<ConstantInt>(II->getArgOperand(0)))
2264 MaxVL = std::min(MaxVL, CI->getZExtValue());
2265
2266 unsigned KnownZeroFirstBit = Log2_32(MaxVL) + 1;
2267 if (BitWidth > KnownZeroFirstBit)
2268 Known.Zero.setBitsFrom(KnownZeroFirstBit);
2269 break;
2270 }
2271 case Intrinsic::amdgcn_mbcnt_hi:
2272 case Intrinsic::amdgcn_mbcnt_lo: {
2273 // Wave64 mbcnt_lo returns at most 32 + src1. Otherwise these return at
2274 // most 31 + src1.
2275 Known.Zero.setBitsFrom(
2276 II->getIntrinsicID() == Intrinsic::amdgcn_mbcnt_lo ? 6 : 5);
2277 computeKnownBits(I->getOperand(1), Known2, Q, Depth + 1);
2278 Known = KnownBits::add(Known, Known2);
2279 break;
2280 }
2281 case Intrinsic::vscale: {
2282 if (!II->getParent() || !II->getFunction())
2283 break;
2284
2285 Known = getVScaleRange(II->getFunction(), BitWidth).toKnownBits();
2286 break;
2287 }
2288 }
2289 }
2290 break;
2291 }
2292 case Instruction::ShuffleVector: {
2293 if (auto *Splat = getSplatValue(I)) {
2295 break;
2296 }
2297
2298 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
2299 // FIXME: Do we need to handle ConstantExpr involving shufflevectors?
2300 if (!Shuf) {
2301 Known.resetAll();
2302 return;
2303 }
2304 // For undef elements, we don't know anything about the common state of
2305 // the shuffle result.
2306 APInt DemandedLHS, DemandedRHS;
2307 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS)) {
2308 Known.resetAll();
2309 return;
2310 }
2311 Known.setAllConflict();
2312 if (!!DemandedLHS) {
2313 const Value *LHS = Shuf->getOperand(0);
2314 computeKnownBits(LHS, DemandedLHS, Known, Q, Depth + 1);
2315 // If we don't know any bits, early out.
2316 if (Known.isUnknown())
2317 break;
2318 }
2319 if (!!DemandedRHS) {
2320 const Value *RHS = Shuf->getOperand(1);
2321 computeKnownBits(RHS, DemandedRHS, Known2, Q, Depth + 1);
2322 Known = Known.intersectWith(Known2);
2323 }
2324 break;
2325 }
2326 case Instruction::InsertElement: {
2327 if (isa<ScalableVectorType>(I->getType())) {
2328 Known.resetAll();
2329 return;
2330 }
2331 const Value *Vec = I->getOperand(0);
2332 const Value *Elt = I->getOperand(1);
2333 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
2334 unsigned NumElts = DemandedElts.getBitWidth();
2335 APInt DemandedVecElts = DemandedElts;
2336 bool NeedsElt = true;
2337 // If we know the index we are inserting too, clear it from Vec check.
2338 if (CIdx && CIdx->getValue().ult(NumElts)) {
2339 DemandedVecElts.clearBit(CIdx->getZExtValue());
2340 NeedsElt = DemandedElts[CIdx->getZExtValue()];
2341 }
2342
2343 Known.setAllConflict();
2344 if (NeedsElt) {
2345 computeKnownBits(Elt, Known, Q, Depth + 1);
2346 // If we don't know any bits, early out.
2347 if (Known.isUnknown())
2348 break;
2349 }
2350
2351 if (!DemandedVecElts.isZero()) {
2352 computeKnownBits(Vec, DemandedVecElts, Known2, Q, Depth + 1);
2353 Known = Known.intersectWith(Known2);
2354 }
2355 break;
2356 }
2357 case Instruction::ExtractElement: {
2358 // Look through extract element. If the index is non-constant or
2359 // out-of-range demand all elements, otherwise just the extracted element.
2360 const Value *Vec = I->getOperand(0);
2361 const Value *Idx = I->getOperand(1);
2362 auto *CIdx = dyn_cast<ConstantInt>(Idx);
2363 if (isa<ScalableVectorType>(Vec->getType())) {
2364 // FIXME: there's probably *something* we can do with scalable vectors
2365 Known.resetAll();
2366 break;
2367 }
2368 unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
2369 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
2370 if (CIdx && CIdx->getValue().ult(NumElts))
2371 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
2372 computeKnownBits(Vec, DemandedVecElts, Known, Q, Depth + 1);
2373 break;
2374 }
2375 case Instruction::ExtractValue:
2376 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I->getOperand(0))) {
2378 if (EVI->getNumIndices() != 1) break;
2379 if (EVI->getIndices()[0] == 0) {
2380 switch (II->getIntrinsicID()) {
2381 default: break;
2382 case Intrinsic::uadd_with_overflow:
2383 case Intrinsic::sadd_with_overflow:
2385 true, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2386 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2387 break;
2388 case Intrinsic::usub_with_overflow:
2389 case Intrinsic::ssub_with_overflow:
2391 false, II->getArgOperand(0), II->getArgOperand(1), /*NSW=*/false,
2392 /* NUW=*/false, DemandedElts, Known, Known2, Q, Depth);
2393 break;
2394 case Intrinsic::umul_with_overflow:
2395 case Intrinsic::smul_with_overflow:
2396 computeKnownBitsMul(II->getArgOperand(0), II->getArgOperand(1), false,
2397 false, DemandedElts, Known, Known2, Q, Depth);
2398 break;
2399 }
2400 }
2401 }
2402 break;
2403 case Instruction::Freeze:
2404 if (isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
2405 Depth + 1))
2406 computeKnownBits(I->getOperand(0), Known, Q, Depth + 1);
2407 break;
2408 }
2409}
2410
2411/// Determine which bits of V are known to be either zero or one and return
2412/// them.
2413KnownBits llvm::computeKnownBits(const Value *V, const APInt &DemandedElts,
2414 const SimplifyQuery &Q, unsigned Depth) {
2415 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2416 ::computeKnownBits(V, DemandedElts, Known, Q, Depth);
2417 return Known;
2418}
2419
2420/// Determine which bits of V are known to be either zero or one and return
2421/// them.
2423 unsigned Depth) {
2424 KnownBits Known(getBitWidth(V->getType(), Q.DL));
2426 return Known;
2427}
2428
2429/// Determine which bits of V are known to be either zero or one and return
2430/// them in the Known bit set.
2431///
2432/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
2433/// we cannot optimize based on the assumption that it is zero without changing
2434/// it to be an explicit zero. If we don't change it to zero, other code could
2435/// optimized based on the contradictory assumption that it is non-zero.
2436/// Because instcombine aggressively folds operations with undef args anyway,
2437/// this won't lose us code quality.
2438///
2439/// This function is defined on values with integer type, values with pointer
2440/// type, and vectors of integers. In the case
2441/// where V is a vector, known zero, and known one values are the
2442/// same width as the vector element, and the bit is set only if it is true
2443/// for all of the demanded elements in the vector specified by DemandedElts.
2444void computeKnownBits(const Value *V, const APInt &DemandedElts,
2445 KnownBits &Known, const SimplifyQuery &Q,
2446 unsigned Depth) {
2447 if (!DemandedElts) {
2448 // No demanded elts, better to assume we don't know anything.
2449 Known.resetAll();
2450 return;
2451 }
2452
2453 assert(V && "No Value?");
2454 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2455
2456#ifndef NDEBUG
2457 Type *Ty = V->getType();
2458 unsigned BitWidth = Known.getBitWidth();
2459
2460 assert((Ty->isIntOrIntVectorTy(BitWidth) || Ty->isPtrOrPtrVectorTy()) &&
2461 "Not integer or pointer type!");
2462
2463 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
2464 assert(
2465 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
2466 "DemandedElt width should equal the fixed vector number of elements");
2467 } else {
2468 assert(DemandedElts == APInt(1, 1) &&
2469 "DemandedElt width should be 1 for scalars or scalable vectors");
2470 }
2471
2472 Type *ScalarTy = Ty->getScalarType();
2473 if (ScalarTy->isPointerTy()) {
2474 assert(BitWidth == Q.DL.getPointerTypeSizeInBits(ScalarTy) &&
2475 "V and Known should have same BitWidth");
2476 } else {
2477 assert(BitWidth == Q.DL.getTypeSizeInBits(ScalarTy) &&
2478 "V and Known should have same BitWidth");
2479 }
2480#endif
2481
2482 const APInt *C;
2483 if (match(V, m_APInt(C))) {
2484 // We know all of the bits for a scalar constant or a splat vector constant!
2486 return;
2487 }
2488 // Null and aggregate-zero are all-zeros.
2490 Known.setAllZero();
2491 return;
2492 }
2493 // Handle a constant vector by taking the intersection of the known bits of
2494 // each element.
2496 assert(!isa<ScalableVectorType>(V->getType()));
2497 // We know that CDV must be a vector of integers. Take the intersection of
2498 // each element.
2499 Known.setAllConflict();
2500 for (unsigned i = 0, e = CDV->getNumElements(); i != e; ++i) {
2501 if (!DemandedElts[i])
2502 continue;
2503 APInt Elt = CDV->getElementAsAPInt(i);
2504 Known.Zero &= ~Elt;
2505 Known.One &= Elt;
2506 }
2507 if (Known.hasConflict())
2508 Known.resetAll();
2509 return;
2510 }
2511
2512 if (const auto *CV = dyn_cast<ConstantVector>(V)) {
2513 assert(!isa<ScalableVectorType>(V->getType()));
2514 // We know that CV must be a vector of integers. Take the intersection of
2515 // each element.
2516 Known.setAllConflict();
2517 for (unsigned i = 0, e = CV->getNumOperands(); i != e; ++i) {
2518 if (!DemandedElts[i])
2519 continue;
2520 Constant *Element = CV->getAggregateElement(i);
2521 if (isa<PoisonValue>(Element))
2522 continue;
2523 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
2524 if (!ElementCI) {
2525 Known.resetAll();
2526 return;
2527 }
2528 const APInt &Elt = ElementCI->getValue();
2529 Known.Zero &= ~Elt;
2530 Known.One &= Elt;
2531 }
2532 if (Known.hasConflict())
2533 Known.resetAll();
2534 return;
2535 }
2536
2537 // Start out not knowing anything.
2538 Known.resetAll();
2539
2540 // We can't imply anything about undefs.
2541 if (isa<UndefValue>(V))
2542 return;
2543
2544 // There's no point in looking through other users of ConstantData for
2545 // assumptions. Confirm that we've handled them all.
2546 assert(!isa<ConstantData>(V) && "Unhandled constant data!");
2547
2548 if (const auto *A = dyn_cast<Argument>(V))
2549 if (std::optional<ConstantRange> Range = A->getRange())
2550 Known = Range->toKnownBits();
2551
2552 // All recursive calls that increase depth must come after this.
2554 return;
2555
2556 // A weak GlobalAlias is totally unknown. A non-weak GlobalAlias has
2557 // the bits of its aliasee.
2558 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
2559 if (!GA->isInterposable())
2560 computeKnownBits(GA->getAliasee(), Known, Q, Depth + 1);
2561 return;
2562 }
2563
2564 if (const Operator *I = dyn_cast<Operator>(V))
2565 computeKnownBitsFromOperator(I, DemandedElts, Known, Q, Depth);
2566 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
2567 if (std::optional<ConstantRange> CR = GV->getAbsoluteSymbolRange())
2568 Known = CR->toKnownBits();
2569 }
2570
2571 // Aligned pointers have trailing zeros - refine Known.Zero set
2572 if (isa<PointerType>(V->getType())) {
2573 Align Alignment = V->getPointerAlignment(Q.DL);
2574 Known.Zero.setLowBits(Log2(Alignment));
2575 }
2576
2577 // computeKnownBitsFromContext strictly refines Known.
2578 // Therefore, we run them after computeKnownBitsFromOperator.
2579
2580 // Check whether we can determine known bits from context such as assumes.
2582}
2583
2584/// Try to detect a recurrence that the value of the induction variable is
2585/// always a power of two (or zero).
2586static bool isPowerOfTwoRecurrence(const PHINode *PN, bool OrZero,
2587 SimplifyQuery &Q, unsigned Depth) {
2588 BinaryOperator *BO = nullptr;
2589 Value *Start = nullptr, *Step = nullptr;
2590 if (!matchSimpleRecurrence(PN, BO, Start, Step))
2591 return false;
2592
2593 // Initial value must be a power of two.
2594 for (const Use &U : PN->operands()) {
2595 if (U.get() == Start) {
2596 // Initial value comes from a different BB, need to adjust context
2597 // instruction for analysis.
2598 Q.CxtI = PN->getIncomingBlock(U)->getTerminator();
2599 if (!isKnownToBeAPowerOfTwo(Start, OrZero, Q, Depth))
2600 return false;
2601 }
2602 }
2603
2604 // Except for Mul, the induction variable must be on the left side of the
2605 // increment expression, otherwise its value can be arbitrary.
2606 if (BO->getOpcode() != Instruction::Mul && BO->getOperand(1) != Step)
2607 return false;
2608
2609 Q.CxtI = BO->getParent()->getTerminator();
2610 switch (BO->getOpcode()) {
2611 case Instruction::Mul:
2612 // Power of two is closed under multiplication.
2613 return (OrZero || Q.IIQ.hasNoUnsignedWrap(BO) ||
2614 Q.IIQ.hasNoSignedWrap(BO)) &&
2615 isKnownToBeAPowerOfTwo(Step, OrZero, Q, Depth);
2616 case Instruction::SDiv:
2617 // Start value must not be signmask for signed division, so simply being a
2618 // power of two is not sufficient, and it has to be a constant.
2619 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2620 return false;
2621 [[fallthrough]];
2622 case Instruction::UDiv:
2623 // Divisor must be a power of two.
2624 // If OrZero is false, cannot guarantee induction variable is non-zero after
2625 // division, same for Shr, unless it is exact division.
2626 return (OrZero || Q.IIQ.isExact(BO)) &&
2627 isKnownToBeAPowerOfTwo(Step, false, Q, Depth);
2628 case Instruction::Shl:
2629 return OrZero || Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO);
2630 case Instruction::AShr:
2631 if (!match(Start, m_Power2()) || match(Start, m_SignMask()))
2632 return false;
2633 [[fallthrough]];
2634 case Instruction::LShr:
2635 return OrZero || Q.IIQ.isExact(BO);
2636 default:
2637 return false;
2638 }
2639}
2640
2641/// Return true if we can infer that \p V is known to be a power of 2 from
2642/// dominating condition \p Cond (e.g., ctpop(V) == 1).
2643static bool isImpliedToBeAPowerOfTwoFromCond(const Value *V, bool OrZero,
2644 const Value *Cond,
2645 bool CondIsTrue) {
2646 CmpPredicate Pred;
2647 const APInt *RHSC;
2648 if (!match(Cond, m_ICmp(Pred, m_Ctpop(m_Specific(V)), m_APInt(RHSC))))
2649 return false;
2650 if (!CondIsTrue)
2651 Pred = ICmpInst::getInversePredicate(Pred);
2652 // ctpop(V) u< 2
2653 if (OrZero && Pred == ICmpInst::ICMP_ULT && *RHSC == 2)
2654 return true;
2655 // ctpop(V) == 1
2656 return Pred == ICmpInst::ICMP_EQ && *RHSC == 1;
2657}
2658
2659/// Return true if the given value is known to have exactly one
2660/// bit set when defined. For vectors return true if every element is known to
2661/// be a power of two when defined. Supports values with integer or pointer
2662/// types and vectors of integers.
2663bool llvm::isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
2664 const SimplifyQuery &Q, unsigned Depth) {
2665 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2666
2667 if (isa<Constant>(V))
2668 return OrZero ? match(V, m_Power2OrZero()) : match(V, m_Power2());
2669
2670 // i1 is by definition a power of 2 or zero.
2671 if (OrZero && V->getType()->getScalarSizeInBits() == 1)
2672 return true;
2673
2674 // Try to infer from assumptions.
2675 if (Q.AC && Q.CxtI) {
2676 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
2677 if (!AssumeVH)
2678 continue;
2679 CallInst *I = cast<CallInst>(AssumeVH);
2680 if (isImpliedToBeAPowerOfTwoFromCond(V, OrZero, I->getArgOperand(0),
2681 /*CondIsTrue=*/true) &&
2683 return true;
2684 }
2685 }
2686
2687 // Handle dominating conditions.
2688 if (Q.DC && Q.CxtI && Q.DT) {
2689 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
2690 Value *Cond = BI->getCondition();
2691
2692 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
2694 /*CondIsTrue=*/true) &&
2695 Q.DT->dominates(Edge0, Q.CxtI->getParent()))
2696 return true;
2697
2698 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
2700 /*CondIsTrue=*/false) &&
2701 Q.DT->dominates(Edge1, Q.CxtI->getParent()))
2702 return true;
2703 }
2704 }
2705
2706 auto *I = dyn_cast<Instruction>(V);
2707 if (!I)
2708 return false;
2709
2710 if (Q.CxtI && match(V, m_VScale())) {
2711 const Function *F = Q.CxtI->getFunction();
2712 // The vscale_range indicates vscale is a power-of-two.
2713 return F->hasFnAttribute(Attribute::VScaleRange);
2714 }
2715
2716 // 1 << X is clearly a power of two if the one is not shifted off the end. If
2717 // it is shifted off the end then the result is undefined.
2718 if (match(I, m_Shl(m_One(), m_Value())))
2719 return true;
2720
2721 // (signmask) >>l X is clearly a power of two if the one is not shifted off
2722 // the bottom. If it is shifted off the bottom then the result is undefined.
2723 if (match(I, m_LShr(m_SignMask(), m_Value())))
2724 return true;
2725
2726 // The remaining tests are all recursive, so bail out if we hit the limit.
2728 return false;
2729
2730 switch (I->getOpcode()) {
2731 case Instruction::ZExt:
2732 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2733 case Instruction::Trunc:
2734 return OrZero && isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2735 case Instruction::Shl:
2736 if (OrZero || Q.IIQ.hasNoUnsignedWrap(I) || Q.IIQ.hasNoSignedWrap(I))
2737 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2738 return false;
2739 case Instruction::LShr:
2740 if (OrZero || Q.IIQ.isExact(cast<BinaryOperator>(I)))
2741 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2742 return false;
2743 case Instruction::UDiv:
2745 return isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth);
2746 return false;
2747 case Instruction::Mul:
2748 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2749 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth) &&
2750 (OrZero || isKnownNonZero(I, Q, Depth));
2751 case Instruction::And:
2752 // A power of two and'd with anything is a power of two or zero.
2753 if (OrZero &&
2754 (isKnownToBeAPowerOfTwo(I->getOperand(1), /*OrZero*/ true, Q, Depth) ||
2755 isKnownToBeAPowerOfTwo(I->getOperand(0), /*OrZero*/ true, Q, Depth)))
2756 return true;
2757 // X & (-X) is always a power of two or zero.
2758 if (match(I->getOperand(0), m_Neg(m_Specific(I->getOperand(1)))) ||
2759 match(I->getOperand(1), m_Neg(m_Specific(I->getOperand(0)))))
2760 return OrZero || isKnownNonZero(I->getOperand(0), Q, Depth);
2761 return false;
2762 case Instruction::Add: {
2763 // Adding a power-of-two or zero to the same power-of-two or zero yields
2764 // either the original power-of-two, a larger power-of-two or zero.
2766 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO) ||
2767 Q.IIQ.hasNoSignedWrap(VOBO)) {
2768 if (match(I->getOperand(0),
2769 m_c_And(m_Specific(I->getOperand(1)), m_Value())) &&
2770 isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth))
2771 return true;
2772 if (match(I->getOperand(1),
2773 m_c_And(m_Specific(I->getOperand(0)), m_Value())) &&
2774 isKnownToBeAPowerOfTwo(I->getOperand(0), OrZero, Q, Depth))
2775 return true;
2776
2777 unsigned BitWidth = V->getType()->getScalarSizeInBits();
2778 KnownBits LHSBits(BitWidth);
2779 computeKnownBits(I->getOperand(0), LHSBits, Q, Depth);
2780
2781 KnownBits RHSBits(BitWidth);
2782 computeKnownBits(I->getOperand(1), RHSBits, Q, Depth);
2783 // If i8 V is a power of two or zero:
2784 // ZeroBits: 1 1 1 0 1 1 1 1
2785 // ~ZeroBits: 0 0 0 1 0 0 0 0
2786 if ((~(LHSBits.Zero & RHSBits.Zero)).isPowerOf2())
2787 // If OrZero isn't set, we cannot give back a zero result.
2788 // Make sure either the LHS or RHS has a bit set.
2789 if (OrZero || RHSBits.One.getBoolValue() || LHSBits.One.getBoolValue())
2790 return true;
2791 }
2792
2793 // LShr(UINT_MAX, Y) + 1 is a power of two (if add is nuw) or zero.
2794 if (OrZero || Q.IIQ.hasNoUnsignedWrap(VOBO))
2795 if (match(I, m_Add(m_LShr(m_AllOnes(), m_Value()), m_One())))
2796 return true;
2797 return false;
2798 }
2799 case Instruction::Select:
2800 return isKnownToBeAPowerOfTwo(I->getOperand(1), OrZero, Q, Depth) &&
2801 isKnownToBeAPowerOfTwo(I->getOperand(2), OrZero, Q, Depth);
2802 case Instruction::PHI: {
2803 // A PHI node is power of two if all incoming values are power of two, or if
2804 // it is an induction variable where in each step its value is a power of
2805 // two.
2806 auto *PN = cast<PHINode>(I);
2808
2809 // Check if it is an induction variable and always power of two.
2810 if (isPowerOfTwoRecurrence(PN, OrZero, RecQ, Depth))
2811 return true;
2812
2813 // Recursively check all incoming values. Limit recursion to 2 levels, so
2814 // that search complexity is limited to number of operands^2.
2815 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
2816 return llvm::all_of(PN->operands(), [&](const Use &U) {
2817 // Value is power of 2 if it is coming from PHI node itself by induction.
2818 if (U.get() == PN)
2819 return true;
2820
2821 // Change the context instruction to the incoming block where it is
2822 // evaluated.
2823 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
2824 return isKnownToBeAPowerOfTwo(U.get(), OrZero, RecQ, NewDepth);
2825 });
2826 }
2827 case Instruction::Invoke:
2828 case Instruction::Call: {
2829 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
2830 switch (II->getIntrinsicID()) {
2831 case Intrinsic::umax:
2832 case Intrinsic::smax:
2833 case Intrinsic::umin:
2834 case Intrinsic::smin:
2835 return isKnownToBeAPowerOfTwo(II->getArgOperand(1), OrZero, Q, Depth) &&
2836 isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2837 // bswap/bitreverse just move around bits, but don't change any 1s/0s
2838 // thus dont change pow2/non-pow2 status.
2839 case Intrinsic::bitreverse:
2840 case Intrinsic::bswap:
2841 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2842 case Intrinsic::fshr:
2843 case Intrinsic::fshl:
2844 // If Op0 == Op1, this is a rotate. is_pow2(rotate(x, y)) == is_pow2(x)
2845 if (II->getArgOperand(0) == II->getArgOperand(1))
2846 return isKnownToBeAPowerOfTwo(II->getArgOperand(0), OrZero, Q, Depth);
2847 break;
2848 case Intrinsic::riscv_vsetvlimax:
2849 // VLMAX is VLEN * LMUL / SEW, which is always a non-zero power of two
2850 // for any valid vtype, so it is a power of two regardless of OrZero.
2851 return true;
2852 default:
2853 break;
2854 }
2855 }
2856 return false;
2857 }
2858 default:
2859 return false;
2860 }
2861}
2862
2863/// Test whether a GEP's result is known to be non-null.
2864///
2865/// Uses properties inherent in a GEP to try to determine whether it is known
2866/// to be non-null.
2867///
2868/// Currently this routine does not support vector GEPs.
2869static bool isGEPKnownNonNull(const GEPOperator *GEP, const SimplifyQuery &Q,
2870 unsigned Depth) {
2871 const Function *F = nullptr;
2872 if (const Instruction *I = dyn_cast<Instruction>(GEP))
2873 F = I->getFunction();
2874
2875 // If the gep is nuw or inbounds with invalid null pointer, then the GEP
2876 // may be null iff the base pointer is null and the offset is zero.
2877 if (!GEP->hasNoUnsignedWrap() &&
2878 !(GEP->isInBounds() &&
2879 !NullPointerIsDefined(F, GEP->getPointerAddressSpace())))
2880 return false;
2881
2882 // FIXME: Support vector-GEPs.
2883 assert(GEP->getType()->isPointerTy() && "We only support plain pointer GEP");
2884
2885 // If the base pointer is non-null, we cannot walk to a null address with an
2886 // inbounds GEP in address space zero.
2887 if (isKnownNonZero(GEP->getPointerOperand(), Q, Depth))
2888 return true;
2889
2890 // Walk the GEP operands and see if any operand introduces a non-zero offset.
2891 // If so, then the GEP cannot produce a null pointer, as doing so would
2892 // inherently violate the inbounds contract within address space zero.
2894 GTI != GTE; ++GTI) {
2895 // Struct types are easy -- they must always be indexed by a constant.
2896 if (StructType *STy = GTI.getStructTypeOrNull()) {
2897 ConstantInt *OpC = cast<ConstantInt>(GTI.getOperand());
2898 unsigned ElementIdx = OpC->getZExtValue();
2899 const StructLayout *SL = Q.DL.getStructLayout(STy);
2900 uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
2901 if (ElementOffset > 0)
2902 return true;
2903 continue;
2904 }
2905
2906 // If we have a zero-sized type, the index doesn't matter. Keep looping.
2907 if (GTI.getSequentialElementStride(Q.DL).isZero())
2908 continue;
2909
2910 // Fast path the constant operand case both for efficiency and so we don't
2911 // increment Depth when just zipping down an all-constant GEP.
2912 if (ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand())) {
2913 if (!OpC->isZero())
2914 return true;
2915 continue;
2916 }
2917
2918 // We post-increment Depth here because while isKnownNonZero increments it
2919 // as well, when we pop back up that increment won't persist. We don't want
2920 // to recurse 10k times just because we have 10k GEP operands. We don't
2921 // bail completely out because we want to handle constant GEPs regardless
2922 // of depth.
2924 continue;
2925
2926 if (isKnownNonZero(GTI.getOperand(), Q, Depth))
2927 return true;
2928 }
2929
2930 return false;
2931}
2932
2934 const Instruction *CtxI,
2935 const DominatorTree *DT) {
2936 assert(!isa<Constant>(V) && "Called for constant?");
2937
2938 if (!CtxI || !DT)
2939 return false;
2940
2941 unsigned NumUsesExplored = 0;
2942 for (auto &U : V->uses()) {
2943 // Avoid massive lists
2944 if (NumUsesExplored >= DomConditionsMaxUses)
2945 break;
2946 NumUsesExplored++;
2947
2948 const Instruction *UI = cast<Instruction>(U.getUser());
2949 // If the value is used as an argument to a call or invoke, then argument
2950 // attributes may provide an answer about null-ness.
2951 if (V->getType()->isPointerTy()) {
2952 if (const auto *CB = dyn_cast<CallBase>(UI)) {
2953 if (CB->isArgOperand(&U) &&
2954 CB->paramHasNonNullAttr(CB->getArgOperandNo(&U),
2955 /*AllowUndefOrPoison=*/false) &&
2956 DT->dominates(CB, CtxI))
2957 return true;
2958 }
2959 }
2960
2961 // If the value is used as a load/store, then the pointer must be non null.
2962 if (V == getLoadStorePointerOperand(UI)) {
2965 DT->dominates(UI, CtxI))
2966 return true;
2967 }
2968
2969 if ((match(UI, m_IDiv(m_Value(), m_Specific(V))) ||
2970 match(UI, m_IRem(m_Value(), m_Specific(V)))) &&
2971 isValidAssumeForContext(UI, CtxI, DT))
2972 return true;
2973
2974 // Consider only compare instructions uniquely controlling a branch
2975 Value *RHS;
2976 CmpPredicate Pred;
2977 if (!match(UI, m_c_ICmp(Pred, m_Specific(V), m_Value(RHS))))
2978 continue;
2979
2980 bool NonNullIfTrue;
2981 if (cmpExcludesZero(Pred, RHS))
2982 NonNullIfTrue = true;
2984 NonNullIfTrue = false;
2985 else
2986 continue;
2987
2990 for (const auto *CmpU : UI->users()) {
2991 assert(WorkList.empty() && "Should be!");
2992 if (Visited.insert(CmpU).second)
2993 WorkList.push_back(CmpU);
2994
2995 while (!WorkList.empty()) {
2996 auto *Curr = WorkList.pop_back_val();
2997
2998 // If a user is an AND, add all its users to the work list. We only
2999 // propagate "pred != null" condition through AND because it is only
3000 // correct to assume that all conditions of AND are met in true branch.
3001 // TODO: Support similar logic of OR and EQ predicate?
3002 if (NonNullIfTrue)
3003 if (match(Curr, m_LogicalAnd(m_Value(), m_Value()))) {
3004 for (const auto *CurrU : Curr->users())
3005 if (Visited.insert(CurrU).second)
3006 WorkList.push_back(CurrU);
3007 continue;
3008 }
3009
3010 if (const CondBrInst *BI = dyn_cast<CondBrInst>(Curr)) {
3011 BasicBlock *NonNullSuccessor =
3012 BI->getSuccessor(NonNullIfTrue ? 0 : 1);
3013 BasicBlockEdge Edge(BI->getParent(), NonNullSuccessor);
3014 if (DT->dominates(Edge, CtxI->getParent()))
3015 return true;
3016 } else if (NonNullIfTrue && isGuard(Curr) &&
3017 DT->dominates(cast<Instruction>(Curr), CtxI)) {
3018 return true;
3019 }
3020 }
3021 }
3022 }
3023
3024 return false;
3025}
3026
3027/// Does the 'Range' metadata (which must be a valid MD_range operand list)
3028/// ensure that the value it's attached to is never Value? 'RangeType' is
3029/// is the type of the value described by the range.
3030static bool rangeMetadataExcludesValue(const MDNode* Ranges, const APInt& Value) {
3031 const unsigned NumRanges = Ranges->getNumOperands() / 2;
3032 assert(NumRanges >= 1);
3033 for (unsigned i = 0; i < NumRanges; ++i) {
3035 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 0));
3037 mdconst::extract<ConstantInt>(Ranges->getOperand(2 * i + 1));
3038 ConstantRange Range(Lower->getValue(), Upper->getValue());
3039 if (Range.contains(Value))
3040 return false;
3041 }
3042 return true;
3043}
3044
3045/// Try to detect a recurrence that monotonically increases/decreases from a
3046/// non-zero starting value. These are common as induction variables.
3047static bool isNonZeroRecurrence(const PHINode *PN) {
3048 BinaryOperator *BO = nullptr;
3049 Value *Start = nullptr, *Step = nullptr;
3050 const APInt *StartC, *StepC;
3051 if (!matchSimpleRecurrence(PN, BO, Start, Step) ||
3052 !match(Start, m_APInt(StartC)) || StartC->isZero())
3053 return false;
3054
3055 switch (BO->getOpcode()) {
3056 case Instruction::Add:
3057 // Starting from non-zero and stepping away from zero can never wrap back
3058 // to zero.
3059 return BO->hasNoUnsignedWrap() ||
3060 (BO->hasNoSignedWrap() && match(Step, m_APInt(StepC)) &&
3061 StartC->isNegative() == StepC->isNegative());
3062 case Instruction::Mul:
3063 return (BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap()) &&
3064 match(Step, m_APInt(StepC)) && !StepC->isZero();
3065 case Instruction::Shl:
3066 return BO->hasNoUnsignedWrap() || BO->hasNoSignedWrap();
3067 case Instruction::AShr:
3068 case Instruction::LShr:
3069 return BO->isExact();
3070 default:
3071 return false;
3072 }
3073}
3074
3075static bool matchOpWithOpEqZero(Value *Op0, Value *Op1) {
3077 m_Specific(Op1), m_Zero()))) ||
3079 m_Specific(Op0), m_Zero())));
3080}
3081
3082static bool isNonZeroAdd(const APInt &DemandedElts, const SimplifyQuery &Q,
3083 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3084 bool NUW, unsigned Depth) {
3085 // (X + (X != 0)) is non zero
3086 if (matchOpWithOpEqZero(X, Y))
3087 return true;
3088
3089 if (NUW)
3090 return isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3091 isKnownNonZero(X, DemandedElts, Q, Depth);
3092
3093 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3094 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3095
3096 // If X and Y are both non-negative (as signed values) then their sum is not
3097 // zero unless both X and Y are zero.
3098 if (XKnown.isNonNegative() && YKnown.isNonNegative())
3099 if (isKnownNonZero(Y, DemandedElts, Q, Depth) ||
3100 isKnownNonZero(X, DemandedElts, Q, Depth))
3101 return true;
3102
3103 // If X and Y are both negative (as signed values) then their sum is not
3104 // zero unless both X and Y equal INT_MIN.
3105 if (XKnown.isNegative() && YKnown.isNegative()) {
3107 // The sign bit of X is set. If some other bit is set then X is not equal
3108 // to INT_MIN.
3109 if (XKnown.One.intersects(Mask))
3110 return true;
3111 // The sign bit of Y is set. If some other bit is set then Y is not equal
3112 // to INT_MIN.
3113 if (YKnown.One.intersects(Mask))
3114 return true;
3115 }
3116
3117 // The sum of a non-negative number and a power of two is not zero.
3118 if (XKnown.isNonNegative() &&
3119 isKnownToBeAPowerOfTwo(Y, /*OrZero*/ false, Q, Depth))
3120 return true;
3121 if (YKnown.isNonNegative() &&
3122 isKnownToBeAPowerOfTwo(X, /*OrZero*/ false, Q, Depth))
3123 return true;
3124
3125 return KnownBits::add(XKnown, YKnown, NSW, NUW).isNonZero();
3126}
3127
3128static bool isNonZeroSub(const APInt &DemandedElts, const SimplifyQuery &Q,
3129 unsigned BitWidth, Value *X, Value *Y,
3130 unsigned Depth) {
3131 // (X - (X != 0)) is non zero
3132 // ((X != 0) - X) is non zero
3133 if (matchOpWithOpEqZero(X, Y))
3134 return true;
3135
3136 // TODO: Move this case into isKnownNonEqual().
3137 if (auto *C = dyn_cast<Constant>(X))
3138 if (C->isNullValue() && isKnownNonZero(Y, DemandedElts, Q, Depth))
3139 return true;
3140
3141 return ::isKnownNonEqual(X, Y, DemandedElts, Q, Depth);
3142}
3143
3144static bool isNonZeroMul(const APInt &DemandedElts, const SimplifyQuery &Q,
3145 unsigned BitWidth, Value *X, Value *Y, bool NSW,
3146 bool NUW, unsigned Depth) {
3147 // If X and Y are non-zero then so is X * Y as long as the multiplication
3148 // does not overflow.
3149 if (NSW || NUW)
3150 return isKnownNonZero(X, DemandedElts, Q, Depth) &&
3151 isKnownNonZero(Y, DemandedElts, Q, Depth);
3152
3153 // If either X or Y is odd, then if the other is non-zero the result can't
3154 // be zero.
3155 KnownBits XKnown = computeKnownBits(X, DemandedElts, Q, Depth);
3156 if (XKnown.One[0])
3157 return isKnownNonZero(Y, DemandedElts, Q, Depth);
3158
3159 KnownBits YKnown = computeKnownBits(Y, DemandedElts, Q, Depth);
3160 if (YKnown.One[0])
3161 return XKnown.isNonZero() || isKnownNonZero(X, DemandedElts, Q, Depth);
3162
3163 // If there exists any subset of X (sX) and subset of Y (sY) s.t sX * sY is
3164 // non-zero, then X * Y is non-zero. We can find sX and sY by just taking
3165 // the lowest known One of X and Y. If they are non-zero, the result
3166 // must be non-zero. We can check if LSB(X) * LSB(Y) != 0 by doing
3167 // X.CountLeadingZeros + Y.CountLeadingZeros < BitWidth.
3168 return (XKnown.countMaxTrailingZeros() + YKnown.countMaxTrailingZeros()) <
3169 BitWidth;
3170}
3171
3172static bool isNonZeroShift(const Operator *I, const APInt &DemandedElts,
3173 const SimplifyQuery &Q, const KnownBits &KnownVal,
3174 unsigned Depth) {
3175 auto ShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3176 switch (I->getOpcode()) {
3177 case Instruction::Shl:
3178 return Lhs.shl(Rhs);
3179 case Instruction::LShr:
3180 return Lhs.lshr(Rhs);
3181 case Instruction::AShr:
3182 return Lhs.ashr(Rhs);
3183 default:
3184 llvm_unreachable("Unknown Shift Opcode");
3185 }
3186 };
3187
3188 auto InvShiftOp = [&](const APInt &Lhs, const APInt &Rhs) {
3189 switch (I->getOpcode()) {
3190 case Instruction::Shl:
3191 return Lhs.lshr(Rhs);
3192 case Instruction::LShr:
3193 case Instruction::AShr:
3194 return Lhs.shl(Rhs);
3195 default:
3196 llvm_unreachable("Unknown Shift Opcode");
3197 }
3198 };
3199
3200 if (KnownVal.isUnknown())
3201 return false;
3202
3203 KnownBits KnownCnt =
3204 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3205 APInt MaxShift = KnownCnt.getMaxValue();
3206 unsigned NumBits = KnownVal.getBitWidth();
3207 if (MaxShift.uge(NumBits))
3208 return false;
3209
3210 if (!ShiftOp(KnownVal.One, MaxShift).isZero())
3211 return true;
3212
3213 // If all of the bits shifted out are known to be zero, and Val is known
3214 // non-zero then at least one non-zero bit must remain.
3215 if (InvShiftOp(KnownVal.Zero, NumBits - MaxShift)
3216 .eq(InvShiftOp(APInt::getAllOnes(NumBits), NumBits - MaxShift)) &&
3217 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth))
3218 return true;
3219
3220 return false;
3221}
3222
3224 const APInt &DemandedElts,
3225 const SimplifyQuery &Q, unsigned Depth) {
3226 unsigned BitWidth = getBitWidth(I->getType()->getScalarType(), Q.DL);
3227 switch (I->getOpcode()) {
3228 case Instruction::Alloca:
3229 // Alloca never returns null, malloc might.
3230 return I->getType()->getPointerAddressSpace() == 0;
3231 case Instruction::GetElementPtr:
3232 if (I->getType()->isPointerTy())
3234 break;
3235 case Instruction::BitCast: {
3236 // We need to be a bit careful here. We can only peek through the bitcast
3237 // if the scalar size of elements in the operand are smaller than and a
3238 // multiple of the size they are casting too. Take three cases:
3239 //
3240 // 1) Unsafe:
3241 // bitcast <2 x i16> %NonZero to <4 x i8>
3242 //
3243 // %NonZero can have 2 non-zero i16 elements, but isKnownNonZero on a
3244 // <4 x i8> requires that all 4 i8 elements be non-zero which isn't
3245 // guranteed (imagine just sign bit set in the 2 i16 elements).
3246 //
3247 // 2) Unsafe:
3248 // bitcast <4 x i3> %NonZero to <3 x i4>
3249 //
3250 // Even though the scalar size of the src (`i3`) is smaller than the
3251 // scalar size of the dst `i4`, because `i3` is not a multiple of `i4`
3252 // its possible for the `3 x i4` elements to be zero because there are
3253 // some elements in the destination that don't contain any full src
3254 // element.
3255 //
3256 // 3) Safe:
3257 // bitcast <4 x i8> %NonZero to <2 x i16>
3258 //
3259 // This is always safe as non-zero in the 4 i8 elements implies
3260 // non-zero in the combination of any two adjacent ones. Since i8 is a
3261 // multiple of i16, each i16 is guranteed to have 2 full i8 elements.
3262 // This all implies the 2 i16 elements are non-zero.
3263 Type *FromTy = I->getOperand(0)->getType();
3264 if ((FromTy->isIntOrIntVectorTy() || FromTy->isPtrOrPtrVectorTy()) &&
3265 (BitWidth % getBitWidth(FromTy->getScalarType(), Q.DL)) == 0)
3266 return isKnownNonZero(I->getOperand(0), Q, Depth);
3267 } break;
3268 case Instruction::IntToPtr:
3269 // Note that we have to take special care to avoid looking through
3270 // truncating casts, e.g., int2ptr/ptr2int with appropriate sizes, as well
3271 // as casts that can alter the value, e.g., AddrSpaceCasts.
3272 if (!isa<ScalableVectorType>(I->getType()) &&
3273 Q.DL.getTypeSizeInBits(I->getOperand(0)->getType()).getFixedValue() <=
3274 Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
3275 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3276 break;
3277 case Instruction::PtrToAddr:
3278 // isKnownNonZero() for pointers refers to the address bits being non-zero,
3279 // so we can directly forward.
3280 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3281 case Instruction::PtrToInt:
3282 // For inttoptr, make sure the result size is >= the address size. If the
3283 // address is non-zero, any larger value is also non-zero.
3284 if (Q.DL.getAddressSizeInBits(I->getOperand(0)->getType()) <=
3285 I->getType()->getScalarSizeInBits())
3286 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3287 break;
3288 case Instruction::Trunc:
3289 // nuw/nsw trunc preserves zero/non-zero status of input.
3290 if (auto *TI = dyn_cast<TruncInst>(I))
3291 if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
3292 return isKnownNonZero(TI->getOperand(0), DemandedElts, Q, Depth);
3293 break;
3294
3295 // Iff x - y != 0, then x ^ y != 0
3296 // Therefore we can do the same exact checks
3297 case Instruction::Xor:
3298 case Instruction::Sub:
3299 return isNonZeroSub(DemandedElts, Q, BitWidth, I->getOperand(0),
3300 I->getOperand(1), Depth);
3301 case Instruction::Or:
3302 // (X | (X != 0)) is non zero
3303 if (matchOpWithOpEqZero(I->getOperand(0), I->getOperand(1)))
3304 return true;
3305 // X | Y != 0 if X != Y.
3306 if (isKnownNonEqual(I->getOperand(0), I->getOperand(1), DemandedElts, Q,
3307 Depth))
3308 return true;
3309 // X | Y != 0 if X != 0 or Y != 0.
3310 return isKnownNonZero(I->getOperand(1), DemandedElts, Q, Depth) ||
3311 isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3312 case Instruction::SExt:
3313 case Instruction::ZExt:
3314 // ext X != 0 if X != 0.
3315 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3316
3317 case Instruction::Shl: {
3318 // shl nsw/nuw can't remove any non-zero bits.
3320 if (Q.IIQ.hasNoUnsignedWrap(BO) || Q.IIQ.hasNoSignedWrap(BO))
3321 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3322
3323 // shl X, Y != 0 if X is odd. Note that the value of the shift is undefined
3324 // if the lowest bit is shifted off the end.
3326 computeKnownBits(I->getOperand(0), DemandedElts, Known, Q, Depth);
3327 if (Known.One[0])
3328 return true;
3329
3330 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3331 }
3332 case Instruction::LShr:
3333 case Instruction::AShr: {
3334 // shr exact can only shift out zero bits.
3336 if (BO->isExact())
3337 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3338
3339 // shr X, Y != 0 if X is negative. Note that the value of the shift is not
3340 // defined if the sign bit is shifted off the end.
3342 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3343 if (Known.isNegative())
3344 return true;
3345
3346 // shr (add nuw A, B), C is non-zero if A or B has a known-one bit at
3347 // position >= C, because the sum >= max(A, B).
3348 Value *A, *B;
3349 const APInt *C;
3350 if (Depth + 1 < MaxAnalysisRecursionDepth &&
3351 match(I->getOperand(0), m_NUWAdd(m_Value(A), m_Value(B))) &&
3352 match(I->getOperand(1), m_APInt(C)) && C->ult(BitWidth)) {
3353 KnownBits KnownA = computeKnownBits(A, DemandedElts, Q, Depth + 1);
3354 if (!KnownA.One.lshr(*C).isZero())
3355 return true;
3356 KnownBits KnownB = computeKnownBits(B, DemandedElts, Q, Depth + 1);
3357 if (!KnownB.One.lshr(*C).isZero())
3358 return true;
3359 }
3360
3361 return isNonZeroShift(I, DemandedElts, Q, Known, Depth);
3362 }
3363 case Instruction::UDiv:
3364 case Instruction::SDiv: {
3365 // X / Y
3366 // div exact can only produce a zero if the dividend is zero.
3367 if (cast<PossiblyExactOperator>(I)->isExact())
3368 return isKnownNonZero(I->getOperand(0), DemandedElts, Q, Depth);
3369
3370 KnownBits XKnown =
3371 computeKnownBits(I->getOperand(0), DemandedElts, Q, Depth);
3372 // If X is fully unknown we won't be able to figure anything out so don't
3373 // both computing knownbits for Y.
3374 if (XKnown.isUnknown())
3375 return false;
3376
3377 KnownBits YKnown =
3378 computeKnownBits(I->getOperand(1), DemandedElts, Q, Depth);
3379 if (I->getOpcode() == Instruction::SDiv) {
3380 // For signed division need to compare abs value of the operands.
3381 XKnown = XKnown.abs(/*IntMinIsPoison*/ false);
3382 YKnown = YKnown.abs(/*IntMinIsPoison*/ false);
3383 }
3384 // If X u>= Y then div is non zero (0/0 is UB).
3385 std::optional<bool> XUgeY = KnownBits::uge(XKnown, YKnown);
3386 // If X is total unknown or X u< Y we won't be able to prove non-zero
3387 // with compute known bits so just return early.
3388 return XUgeY && *XUgeY;
3389 }
3390 case Instruction::Add: {
3391 // X + Y.
3392
3393 // If Add has nuw wrap flag, then if either X or Y is non-zero the result is
3394 // non-zero.
3396 return isNonZeroAdd(DemandedElts, Q, BitWidth, I->getOperand(0),
3397 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3398 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3399 }
3400 case Instruction::Mul: {
3402 return isNonZeroMul(DemandedElts, Q, BitWidth, I->getOperand(0),
3403 I->getOperand(1), Q.IIQ.hasNoSignedWrap(BO),
3404 Q.IIQ.hasNoUnsignedWrap(BO), Depth);
3405 }
3406 case Instruction::Select: {
3407 // (C ? X : Y) != 0 if X != 0 and Y != 0.
3408
3409 // First check if the arm is non-zero using `isKnownNonZero`. If that fails,
3410 // then see if the select condition implies the arm is non-zero. For example
3411 // (X != 0 ? X : Y), we know the true arm is non-zero as the `X` "return" is
3412 // dominated by `X != 0`.
3413 auto SelectArmIsNonZero = [&](bool IsTrueArm) {
3414 Value *Op;
3415 Op = IsTrueArm ? I->getOperand(1) : I->getOperand(2);
3416 // Op is trivially non-zero.
3417 if (isKnownNonZero(Op, DemandedElts, Q, Depth))
3418 return true;
3419
3420 // The condition of the select dominates the true/false arm. Check if the
3421 // condition implies that a given arm is non-zero.
3422 Value *X;
3423 CmpPredicate Pred;
3424 if (!match(I->getOperand(0), m_c_ICmp(Pred, m_Specific(Op), m_Value(X))))
3425 return false;
3426
3427 if (!IsTrueArm)
3428 Pred = ICmpInst::getInversePredicate(Pred);
3429
3430 return cmpExcludesZero(Pred, X);
3431 };
3432
3433 if (SelectArmIsNonZero(/* IsTrueArm */ true) &&
3434 SelectArmIsNonZero(/* IsTrueArm */ false))
3435 return true;
3436 break;
3437 }
3438 case Instruction::PHI: {
3439 auto *PN = cast<PHINode>(I);
3441 return true;
3442
3443 // Check if all incoming values are non-zero using recursion.
3445 unsigned NewDepth = std::max(Depth, MaxAnalysisRecursionDepth - 1);
3446 return llvm::all_of(PN->operands(), [&](const Use &U) {
3447 if (U.get() == PN)
3448 return true;
3449 RecQ.CxtI = PN->getIncomingBlock(U)->getTerminator();
3450 // Check if the branch on the phi excludes zero.
3451 CmpPredicate Pred;
3452 Value *X;
3453 BasicBlock *TrueSucc, *FalseSucc;
3454 if (match(RecQ.CxtI,
3455 m_Br(m_c_ICmp(Pred, m_Specific(U.get()), m_Value(X)),
3456 m_BasicBlock(TrueSucc), m_BasicBlock(FalseSucc)))) {
3457 // Check for cases of duplicate successors.
3458 if ((TrueSucc == PN->getParent()) != (FalseSucc == PN->getParent())) {
3459 // If we're using the false successor, invert the predicate.
3460 if (FalseSucc == PN->getParent())
3461 Pred = CmpInst::getInversePredicate(Pred);
3462 if (cmpExcludesZero(Pred, X))
3463 return true;
3464 }
3465 }
3466 // Finally recurse on the edge and check it directly.
3467 return isKnownNonZero(U.get(), DemandedElts, RecQ, NewDepth);
3468 });
3469 }
3470 case Instruction::InsertElement: {
3471 if (isa<ScalableVectorType>(I->getType()))
3472 break;
3473
3474 const Value *Vec = I->getOperand(0);
3475 const Value *Elt = I->getOperand(1);
3476 auto *CIdx = dyn_cast<ConstantInt>(I->getOperand(2));
3477
3478 unsigned NumElts = DemandedElts.getBitWidth();
3479 APInt DemandedVecElts = DemandedElts;
3480 bool SkipElt = false;
3481 // If we know the index we are inserting too, clear it from Vec check.
3482 if (CIdx && CIdx->getValue().ult(NumElts)) {
3483 DemandedVecElts.clearBit(CIdx->getZExtValue());
3484 SkipElt = !DemandedElts[CIdx->getZExtValue()];
3485 }
3486
3487 // Result is zero if Elt is non-zero and rest of the demanded elts in Vec
3488 // are non-zero.
3489 return (SkipElt || isKnownNonZero(Elt, Q, Depth)) &&
3490 (DemandedVecElts.isZero() ||
3491 isKnownNonZero(Vec, DemandedVecElts, Q, Depth));
3492 }
3493 case Instruction::ExtractElement:
3494 if (const auto *EEI = dyn_cast<ExtractElementInst>(I)) {
3495 const Value *Vec = EEI->getVectorOperand();
3496 const Value *Idx = EEI->getIndexOperand();
3497 auto *CIdx = dyn_cast<ConstantInt>(Idx);
3498 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
3499 unsigned NumElts = VecTy->getNumElements();
3500 APInt DemandedVecElts = APInt::getAllOnes(NumElts);
3501 if (CIdx && CIdx->getValue().ult(NumElts))
3502 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
3503 return isKnownNonZero(Vec, DemandedVecElts, Q, Depth);
3504 }
3505 }
3506 break;
3507 case Instruction::ShuffleVector: {
3508 auto *Shuf = dyn_cast<ShuffleVectorInst>(I);
3509 if (!Shuf)
3510 break;
3511 APInt DemandedLHS, DemandedRHS;
3512 // For undef elements, we don't know anything about the common state of
3513 // the shuffle result.
3514 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
3515 break;
3516 // If demanded elements for both vecs are non-zero, the shuffle is non-zero.
3517 return (DemandedRHS.isZero() ||
3518 isKnownNonZero(Shuf->getOperand(1), DemandedRHS, Q, Depth)) &&
3519 (DemandedLHS.isZero() ||
3520 isKnownNonZero(Shuf->getOperand(0), DemandedLHS, Q, Depth));
3521 }
3522 case Instruction::Freeze:
3523 return isKnownNonZero(I->getOperand(0), Q, Depth) &&
3524 isGuaranteedNotToBePoison(I->getOperand(0), Q.AC, Q.CxtI, Q.DT,
3525 Depth);
3526 case Instruction::Load: {
3527 auto *LI = cast<LoadInst>(I);
3528 // A Load tagged with nonnull or dereferenceable with null pointer undefined
3529 // is never null.
3530 if (auto *PtrT = dyn_cast<PointerType>(I->getType())) {
3531 if (Q.IIQ.getMetadata(LI, LLVMContext::MD_nonnull) ||
3532 (Q.IIQ.getMetadata(LI, LLVMContext::MD_dereferenceable) &&
3533 !NullPointerIsDefined(LI->getFunction(), PtrT->getAddressSpace())))
3534 return true;
3535 } else if (MDNode *Ranges = Q.IIQ.getMetadata(LI, LLVMContext::MD_range)) {
3537 }
3538
3539 // No need to fall through to computeKnownBits as range metadata is already
3540 // handled in isKnownNonZero.
3541 return false;
3542 }
3543 case Instruction::ExtractValue: {
3544 const WithOverflowInst *WO;
3546 switch (WO->getBinaryOp()) {
3547 default:
3548 break;
3549 case Instruction::Add:
3550 return isNonZeroAdd(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3551 WO->getArgOperand(1),
3552 /*NSW=*/false,
3553 /*NUW=*/false, Depth);
3554 case Instruction::Sub:
3555 return isNonZeroSub(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3556 WO->getArgOperand(1), Depth);
3557 case Instruction::Mul:
3558 return isNonZeroMul(DemandedElts, Q, BitWidth, WO->getArgOperand(0),
3559 WO->getArgOperand(1),
3560 /*NSW=*/false, /*NUW=*/false, Depth);
3561 break;
3562 }
3563 }
3564 break;
3565 }
3566 case Instruction::Call:
3567 case Instruction::Invoke: {
3568 const auto *Call = cast<CallBase>(I);
3569 if (I->getType()->isPointerTy()) {
3570 if (Call->isReturnNonNull())
3571 return true;
3572 if (const auto *RP = getArgumentAliasingToReturnedPointer(
3573 Call, /*MustPreserveOffset=*/true))
3574 return isKnownNonZero(RP, Q, Depth);
3575 } else {
3576 if (MDNode *Ranges = Q.IIQ.getMetadata(Call, LLVMContext::MD_range))
3578 if (std::optional<ConstantRange> Range = Call->getRange()) {
3579 const APInt ZeroValue(Range->getBitWidth(), 0);
3580 if (!Range->contains(ZeroValue))
3581 return true;
3582 }
3583 if (const Value *RV = Call->getReturnedArgOperand())
3584 if (RV->getType() == I->getType() && isKnownNonZero(RV, Q, Depth))
3585 return true;
3586 }
3587
3588 if (auto *II = dyn_cast<IntrinsicInst>(I)) {
3589 switch (II->getIntrinsicID()) {
3590 case Intrinsic::sshl_sat:
3591 case Intrinsic::ushl_sat:
3592 case Intrinsic::abs:
3593 case Intrinsic::bitreverse:
3594 case Intrinsic::bswap:
3595 case Intrinsic::ctpop:
3596 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3597 // NB: We don't do usub_sat here as in any case we can prove its
3598 // non-zero, we will fold it to `sub nuw` in InstCombine.
3599 case Intrinsic::ssub_sat:
3600 // For most types, if x != y then ssub.sat x, y != 0. But
3601 // ssub.sat.i1 0, -1 = 0, because 1 saturates to 0. This means
3602 // isNonZeroSub will do the wrong thing for ssub.sat.i1.
3603 if (BitWidth == 1)
3604 return false;
3605 return isNonZeroSub(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3606 II->getArgOperand(1), Depth);
3607 case Intrinsic::sadd_sat:
3608 return isNonZeroAdd(DemandedElts, Q, BitWidth, II->getArgOperand(0),
3609 II->getArgOperand(1),
3610 /*NSW=*/true, /* NUW=*/false, Depth);
3611 // Vec reverse preserves zero/non-zero status from input vec.
3612 case Intrinsic::vector_reverse:
3613 return isKnownNonZero(II->getArgOperand(0), DemandedElts.reverseBits(),
3614 Q, Depth);
3615 // umin/smin/smax/smin/or of all non-zero elements is always non-zero.
3616 case Intrinsic::vector_reduce_or:
3617 case Intrinsic::vector_reduce_umax:
3618 case Intrinsic::vector_reduce_umin:
3619 case Intrinsic::vector_reduce_smax:
3620 case Intrinsic::vector_reduce_smin:
3621 return isKnownNonZero(II->getArgOperand(0), Q, Depth);
3622 case Intrinsic::umax:
3623 case Intrinsic::uadd_sat:
3624 // umax(X, (X != 0)) is non zero
3625 // X +usat (X != 0) is non zero
3626 if (matchOpWithOpEqZero(II->getArgOperand(0), II->getArgOperand(1)))
3627 return true;
3628
3629 return isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth) ||
3630 isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3631 case Intrinsic::smax: {
3632 // If either arg is strictly positive the result is non-zero. Otherwise
3633 // the result is non-zero if both ops are non-zero.
3634 auto IsNonZero = [&](Value *Op, std::optional<bool> &OpNonZero,
3635 const KnownBits &OpKnown) {
3636 if (!OpNonZero.has_value())
3637 OpNonZero = OpKnown.isNonZero() ||
3638 isKnownNonZero(Op, DemandedElts, Q, Depth);
3639 return *OpNonZero;
3640 };
3641 // Avoid re-computing isKnownNonZero.
3642 std::optional<bool> Op0NonZero, Op1NonZero;
3643 KnownBits Op1Known =
3644 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3645 if (Op1Known.isNonNegative() &&
3646 IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known))
3647 return true;
3648 KnownBits Op0Known =
3649 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3650 if (Op0Known.isNonNegative() &&
3651 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known))
3652 return true;
3653 return IsNonZero(II->getArgOperand(1), Op1NonZero, Op1Known) &&
3654 IsNonZero(II->getArgOperand(0), Op0NonZero, Op0Known);
3655 }
3656 case Intrinsic::smin: {
3657 // If either arg is negative the result is non-zero. Otherwise
3658 // the result is non-zero if both ops are non-zero.
3659 KnownBits Op1Known =
3660 computeKnownBits(II->getArgOperand(1), DemandedElts, Q, Depth);
3661 if (Op1Known.isNegative())
3662 return true;
3663 KnownBits Op0Known =
3664 computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth);
3665 if (Op0Known.isNegative())
3666 return true;
3667
3668 if (Op1Known.isNonZero() && Op0Known.isNonZero())
3669 return true;
3670 }
3671 [[fallthrough]];
3672 case Intrinsic::umin:
3673 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth) &&
3674 isKnownNonZero(II->getArgOperand(1), DemandedElts, Q, Depth);
3675 case Intrinsic::cttz:
3676 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3677 .Zero[0];
3678 case Intrinsic::ctlz:
3679 return computeKnownBits(II->getArgOperand(0), DemandedElts, Q, Depth)
3680 .isNonNegative();
3681 case Intrinsic::fshr:
3682 case Intrinsic::fshl:
3683 // If Op0 == Op1, this is a rotate. rotate(x, y) != 0 iff x != 0.
3684 if (II->getArgOperand(0) == II->getArgOperand(1))
3685 return isKnownNonZero(II->getArgOperand(0), DemandedElts, Q, Depth);
3686 break;
3687 case Intrinsic::vscale:
3688 return true;
3689 case Intrinsic::experimental_get_vector_length:
3690 return isKnownNonZero(I->getOperand(0), Q, Depth);
3691 default:
3692 break;
3693 }
3694 break;
3695 }
3696
3697 return false;
3698 }
3699 }
3700
3702 computeKnownBits(I, DemandedElts, Known, Q, Depth);
3703 return Known.One != 0;
3704}
3705
3706/// Return true if the given value is known to be non-zero when defined. For
3707/// vectors, return true if every demanded element is known to be non-zero when
3708/// defined. For pointers, if the context instruction and dominator tree are
3709/// specified, perform context-sensitive analysis and return true if the
3710/// pointer couldn't possibly be null at the specified instruction.
3711/// Supports values with integer or pointer type and vectors of integers.
3712bool isKnownNonZero(const Value *V, const APInt &DemandedElts,
3713 const SimplifyQuery &Q, unsigned Depth) {
3714 Type *Ty = V->getType();
3715
3716#ifndef NDEBUG
3717 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
3718
3719 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
3720 assert(
3721 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
3722 "DemandedElt width should equal the fixed vector number of elements");
3723 } else {
3724 assert(DemandedElts == APInt(1, 1) &&
3725 "DemandedElt width should be 1 for scalars");
3726 }
3727#endif
3728
3729 if (auto *C = dyn_cast<Constant>(V)) {
3730 if (C->isNullValue())
3731 return false;
3732 if (isa<ConstantInt>(C))
3733 // Must be non-zero due to null test above.
3734 return true;
3735
3736 // For constant vectors, check that all elements are poison or known
3737 // non-zero to determine that the whole vector is known non-zero.
3738 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
3739 for (unsigned i = 0, e = VecTy->getNumElements(); i != e; ++i) {
3740 if (!DemandedElts[i])
3741 continue;
3742 Constant *Elt = C->getAggregateElement(i);
3743 if (!Elt || Elt->isNullValue())
3744 return false;
3745 if (!isa<PoisonValue>(Elt) && !isa<ConstantInt>(Elt))
3746 return false;
3747 }
3748 return true;
3749 }
3750
3751 // Constant ptrauth can be null, iff the base pointer can be.
3752 if (auto *CPA = dyn_cast<ConstantPtrAuth>(V))
3753 return isKnownNonZero(CPA->getPointer(), DemandedElts, Q, Depth);
3754
3755 // A global variable in address space 0 is non null unless extern weak
3756 // or an absolute symbol reference. Other address spaces may have null as a
3757 // valid address for a global, so we can't assume anything.
3758 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
3759 if (!GV->isAbsoluteSymbolRef() && !GV->hasExternalWeakLinkage() &&
3760 GV->getType()->getAddressSpace() == 0)
3761 return true;
3762 }
3763
3764 // For constant expressions, fall through to the Operator code below.
3765 if (!isa<ConstantExpr>(V))
3766 return false;
3767 }
3768
3769 if (const auto *A = dyn_cast<Argument>(V))
3770 if (std::optional<ConstantRange> Range = A->getRange()) {
3771 const APInt ZeroValue(Range->getBitWidth(), 0);
3772 if (!Range->contains(ZeroValue))
3773 return true;
3774 }
3775
3776 if (!isa<Constant>(V) && isKnownNonZeroFromAssume(V, Q))
3777 return true;
3778
3779 // Some of the tests below are recursive, so bail out if we hit the limit.
3781 return false;
3782
3783 // Check for pointer simplifications.
3784
3785 if (PointerType *PtrTy = dyn_cast<PointerType>(Ty)) {
3786 // A byval, inalloca may not be null in a non-default addres space. A
3787 // nonnull argument is assumed never 0.
3788 if (const Argument *A = dyn_cast<Argument>(V)) {
3789 if (((A->hasPassPointeeByValueCopyAttr() &&
3790 !NullPointerIsDefined(A->getParent(), PtrTy->getAddressSpace())) ||
3791 A->hasNonNullAttr()))
3792 return true;
3793 }
3794 }
3795
3796 if (const auto *I = dyn_cast<Operator>(V))
3797 if (isKnownNonZeroFromOperator(I, DemandedElts, Q, Depth))
3798 return true;
3799
3800 if (!isa<Constant>(V) &&
3802 return true;
3803
3804 if (const Value *Stripped = stripNullTest(V))
3805 return isKnownNonZero(Stripped, DemandedElts, Q, Depth);
3806
3807 return false;
3808}
3809
3811 unsigned Depth) {
3812 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
3813 APInt DemandedElts =
3814 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
3815 return ::isKnownNonZero(V, DemandedElts, Q, Depth);
3816}
3817
3818/// If the pair of operators are the same invertible function, return the
3819/// the operands of the function corresponding to each input. Otherwise,
3820/// return std::nullopt. An invertible function is one that is 1-to-1 and maps
3821/// every input value to exactly one output value. This is equivalent to
3822/// saying that Op1 and Op2 are equal exactly when the specified pair of
3823/// operands are equal, (except that Op1 and Op2 may be poison more often.)
3824static std::optional<std::pair<Value*, Value*>>
3826 const Operator *Op2) {
3827 if (Op1->getOpcode() != Op2->getOpcode())
3828 return std::nullopt;
3829
3830 auto getOperands = [&](unsigned OpNum) -> auto {
3831 return std::make_pair(Op1->getOperand(OpNum), Op2->getOperand(OpNum));
3832 };
3833
3834 switch (Op1->getOpcode()) {
3835 default:
3836 break;
3837 case Instruction::Or:
3838 if (!cast<PossiblyDisjointInst>(Op1)->isDisjoint() ||
3839 !cast<PossiblyDisjointInst>(Op2)->isDisjoint())
3840 break;
3841 [[fallthrough]];
3842 case Instruction::Xor:
3843 case Instruction::Add: {
3844 Value *Other;
3845 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(0)), m_Value(Other))))
3846 return std::make_pair(Op1->getOperand(1), Other);
3847 if (match(Op2, m_c_BinOp(m_Specific(Op1->getOperand(1)), m_Value(Other))))
3848 return std::make_pair(Op1->getOperand(0), Other);
3849 break;
3850 }
3851 case Instruction::Sub:
3852 if (Op1->getOperand(0) == Op2->getOperand(0))
3853 return getOperands(1);
3854 if (Op1->getOperand(1) == Op2->getOperand(1))
3855 return getOperands(0);
3856 break;
3857 case Instruction::Mul: {
3858 // invertible if A * B == (A * B) mod 2^N where A, and B are integers
3859 // and N is the bitwdith. The nsw case is non-obvious, but proven by
3860 // alive2: https://alive2.llvm.org/ce/z/Z6D5qK
3861 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3862 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3863 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3864 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3865 break;
3866
3867 // Assume operand order has been canonicalized
3868 if (Op1->getOperand(1) == Op2->getOperand(1) &&
3869 isa<ConstantInt>(Op1->getOperand(1)) &&
3870 !cast<ConstantInt>(Op1->getOperand(1))->isZero())
3871 return getOperands(0);
3872 break;
3873 }
3874 case Instruction::Shl: {
3875 // Same as multiplies, with the difference that we don't need to check
3876 // for a non-zero multiply. Shifts always multiply by non-zero.
3877 auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
3878 auto *OBO2 = cast<OverflowingBinaryOperator>(Op2);
3879 if ((!OBO1->hasNoUnsignedWrap() || !OBO2->hasNoUnsignedWrap()) &&
3880 (!OBO1->hasNoSignedWrap() || !OBO2->hasNoSignedWrap()))
3881 break;
3882
3883 if (Op1->getOperand(1) == Op2->getOperand(1))
3884 return getOperands(0);
3885 break;
3886 }
3887 case Instruction::AShr:
3888 case Instruction::LShr: {
3889 auto *PEO1 = cast<PossiblyExactOperator>(Op1);
3890 auto *PEO2 = cast<PossiblyExactOperator>(Op2);
3891 if (!PEO1->isExact() || !PEO2->isExact())
3892 break;
3893
3894 if (Op1->getOperand(1) == Op2->getOperand(1))
3895 return getOperands(0);
3896 break;
3897 }
3898 case Instruction::SExt:
3899 case Instruction::ZExt:
3900 if (Op1->getOperand(0)->getType() == Op2->getOperand(0)->getType())
3901 return getOperands(0);
3902 break;
3903 case Instruction::PHI: {
3904 const PHINode *PN1 = cast<PHINode>(Op1);
3905 const PHINode *PN2 = cast<PHINode>(Op2);
3906
3907 // If PN1 and PN2 are both recurrences, can we prove the entire recurrences
3908 // are a single invertible function of the start values? Note that repeated
3909 // application of an invertible function is also invertible
3910 BinaryOperator *BO1 = nullptr;
3911 Value *Start1 = nullptr, *Step1 = nullptr;
3912 BinaryOperator *BO2 = nullptr;
3913 Value *Start2 = nullptr, *Step2 = nullptr;
3914 if (PN1->getParent() != PN2->getParent() ||
3915 !matchSimpleRecurrence(PN1, BO1, Start1, Step1) ||
3916 !matchSimpleRecurrence(PN2, BO2, Start2, Step2))
3917 break;
3918
3920 cast<Operator>(BO2));
3921 if (!Values)
3922 break;
3923
3924 // We have to be careful of mutually defined recurrences here. Ex:
3925 // * X_i = X_(i-1) OP Y_(i-1), and Y_i = X_(i-1) OP V
3926 // * X_i = Y_i = X_(i-1) OP Y_(i-1)
3927 // The invertibility of these is complicated, and not worth reasoning
3928 // about (yet?).
3929 if (Values->first != PN1 || Values->second != PN2)
3930 break;
3931
3932 return std::make_pair(Start1, Start2);
3933 }
3934 }
3935 return std::nullopt;
3936}
3937
3938/// Return true if V1 == (binop V2, X), where X is known non-zero.
3939/// Only handle a small subset of binops where (binop V2, X) with non-zero X
3940/// implies V2 != V1.
3941static bool isModifyingBinopOfNonZero(const Value *V1, const Value *V2,
3942 const APInt &DemandedElts,
3943 const SimplifyQuery &Q, unsigned Depth) {
3945 if (!BO)
3946 return false;
3947 switch (BO->getOpcode()) {
3948 default:
3949 break;
3950 case Instruction::Or:
3951 if (!cast<PossiblyDisjointInst>(V1)->isDisjoint())
3952 break;
3953 [[fallthrough]];
3954 case Instruction::Xor:
3955 case Instruction::Add:
3956 Value *Op = nullptr;
3957 if (V2 == BO->getOperand(0))
3958 Op = BO->getOperand(1);
3959 else if (V2 == BO->getOperand(1))
3960 Op = BO->getOperand(0);
3961 else
3962 return false;
3963 return isKnownNonZero(Op, DemandedElts, Q, Depth + 1);
3964 }
3965 return false;
3966}
3967
3968/// Return true if V2 == V1 * C, where V1 is known non-zero, C is not 0/1 and
3969/// the multiplication is nuw or nsw.
3970static bool isNonEqualMul(const Value *V1, const Value *V2,
3971 const APInt &DemandedElts, const SimplifyQuery &Q,
3972 unsigned Depth) {
3973 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3974 const APInt *C;
3975 return match(OBO, m_Mul(m_Specific(V1), m_APInt(C))) &&
3976 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3977 !C->isZero() && !C->isOne() &&
3978 isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
3979 }
3980 return false;
3981}
3982
3983/// Return true if V2 == V1 << C, where V1 is known non-zero, C is not 0 and
3984/// the shift is nuw or nsw.
3985static bool isNonEqualShl(const Value *V1, const Value *V2,
3986 const APInt &DemandedElts, const SimplifyQuery &Q,
3987 unsigned Depth) {
3988 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(V2)) {
3989 const APInt *C;
3990 return match(OBO, m_Shl(m_Specific(V1), m_APInt(C))) &&
3991 (OBO->hasNoUnsignedWrap() || OBO->hasNoSignedWrap()) &&
3992 !C->isZero() && isKnownNonZero(V1, DemandedElts, Q, Depth + 1);
3993 }
3994 return false;
3995}
3996
3997static bool isNonEqualPHIs(const PHINode *PN1, const PHINode *PN2,
3998 const APInt &DemandedElts, const SimplifyQuery &Q,
3999 unsigned Depth) {
4000 // Check two PHIs are in same block.
4001 if (PN1->getParent() != PN2->getParent())
4002 return false;
4003
4005 bool UsedFullRecursion = false;
4006 for (const BasicBlock *IncomBB : PN1->blocks()) {
4007 if (!VisitedBBs.insert(IncomBB).second)
4008 continue; // Don't reprocess blocks that we have dealt with already.
4009 const Value *IV1 = PN1->getIncomingValueForBlock(IncomBB);
4010 const Value *IV2 = PN2->getIncomingValueForBlock(IncomBB);
4011 const APInt *C1, *C2;
4012 if (match(IV1, m_APInt(C1)) && match(IV2, m_APInt(C2)) && *C1 != *C2)
4013 continue;
4014
4015 // Only one pair of phi operands is allowed for full recursion.
4016 if (UsedFullRecursion)
4017 return false;
4018
4020 RecQ.CxtI = IncomBB->getTerminator();
4021 if (!isKnownNonEqual(IV1, IV2, DemandedElts, RecQ, Depth + 1))
4022 return false;
4023 UsedFullRecursion = true;
4024 }
4025 return true;
4026}
4027
4028static bool isNonEqualSelect(const Value *V1, const Value *V2,
4029 const APInt &DemandedElts, const SimplifyQuery &Q,
4030 unsigned Depth) {
4031 const SelectInst *SI1 = dyn_cast<SelectInst>(V1);
4032 if (!SI1)
4033 return false;
4034
4035 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2)) {
4036 const Value *Cond1 = SI1->getCondition();
4037 const Value *Cond2 = SI2->getCondition();
4038 if (Cond1 == Cond2)
4039 return isKnownNonEqual(SI1->getTrueValue(), SI2->getTrueValue(),
4040 DemandedElts, Q, Depth + 1) &&
4041 isKnownNonEqual(SI1->getFalseValue(), SI2->getFalseValue(),
4042 DemandedElts, Q, Depth + 1);
4043 }
4044 return isKnownNonEqual(SI1->getTrueValue(), V2, DemandedElts, Q, Depth + 1) &&
4045 isKnownNonEqual(SI1->getFalseValue(), V2, DemandedElts, Q, Depth + 1);
4046}
4047
4048// Check to see if A is both a GEP and is the incoming value for a PHI in the
4049// loop, and B is either a ptr or another GEP. If the PHI has 2 incoming values,
4050// one of them being the recursive GEP A and the other a ptr at same base and at
4051// the same/higher offset than B we are only incrementing the pointer further in
4052// loop if offset of recursive GEP is greater than 0.
4054 const SimplifyQuery &Q) {
4055 if (!A->getType()->isPointerTy() || !B->getType()->isPointerTy())
4056 return false;
4057
4058 auto *GEPA = dyn_cast<GEPOperator>(A);
4059 if (!GEPA || GEPA->getNumIndices() != 1 || !isa<Constant>(GEPA->idx_begin()))
4060 return false;
4061
4062 // Handle 2 incoming PHI values with one being a recursive GEP.
4063 auto *PN = dyn_cast<PHINode>(GEPA->getPointerOperand());
4064 if (!PN || PN->getNumIncomingValues() != 2)
4065 return false;
4066
4067 // Search for the recursive GEP as an incoming operand, and record that as
4068 // Step.
4069 Value *Start = nullptr;
4070 Value *Step = const_cast<Value *>(A);
4071 if (PN->getIncomingValue(0) == Step)
4072 Start = PN->getIncomingValue(1);
4073 else if (PN->getIncomingValue(1) == Step)
4074 Start = PN->getIncomingValue(0);
4075 else
4076 return false;
4077
4078 // Other incoming node base should match the B base.
4079 // StartOffset >= OffsetB && StepOffset > 0?
4080 // StartOffset <= OffsetB && StepOffset < 0?
4081 // Is non-equal if above are true.
4082 // We use stripAndAccumulateInBoundsConstantOffsets to restrict the
4083 // optimisation to inbounds GEPs only.
4084 unsigned IndexWidth = Q.DL.getIndexTypeSizeInBits(Start->getType());
4085 APInt StartOffset(IndexWidth, 0);
4086 Start = Start->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StartOffset);
4087 APInt StepOffset(IndexWidth, 0);
4088 Step = Step->stripAndAccumulateInBoundsConstantOffsets(Q.DL, StepOffset);
4089
4090 // Check if Base Pointer of Step matches the PHI.
4091 if (Step != PN)
4092 return false;
4093 APInt OffsetB(IndexWidth, 0);
4094 B = B->stripAndAccumulateInBoundsConstantOffsets(Q.DL, OffsetB);
4095 return Start == B &&
4096 ((StartOffset.sge(OffsetB) && StepOffset.isStrictlyPositive()) ||
4097 (StartOffset.sle(OffsetB) && StepOffset.isNegative()));
4098}
4099
4100static bool isKnownNonEqualFromContext(const Value *V1, const Value *V2,
4101 const SimplifyQuery &Q, unsigned Depth) {
4102 if (!Q.CxtI)
4103 return false;
4104
4105 // Try to infer NonEqual based on information from dominating conditions.
4106 if (Q.DC && Q.DT) {
4107 auto IsKnownNonEqualFromDominatingCondition = [&](const Value *V) {
4108 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4109 Value *Cond = BI->getCondition();
4110 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4111 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()) &&
4113 /*LHSIsTrue=*/true, Depth)
4114 .value_or(false))
4115 return true;
4116
4117 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4118 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()) &&
4120 /*LHSIsTrue=*/false, Depth)
4121 .value_or(false))
4122 return true;
4123 }
4124
4125 return false;
4126 };
4127
4128 if (IsKnownNonEqualFromDominatingCondition(V1) ||
4129 IsKnownNonEqualFromDominatingCondition(V2))
4130 return true;
4131 }
4132
4133 if (!Q.AC)
4134 return false;
4135
4136 // Try to infer NonEqual based on information from assumptions.
4137 for (auto &AssumeVH : Q.AC->assumptionsFor(V1)) {
4138 if (!AssumeVH)
4139 continue;
4140 CallInst *I = cast<CallInst>(AssumeVH);
4141
4142 assert(I->getFunction() == Q.CxtI->getFunction() &&
4143 "Got assumption for the wrong function!");
4144 assert(I->getIntrinsicID() == Intrinsic::assume &&
4145 "must be an assume intrinsic");
4146
4147 if (isImpliedCondition(I->getArgOperand(0), ICmpInst::ICMP_NE, V1, V2, Q.DL,
4148 /*LHSIsTrue=*/true, Depth)
4149 .value_or(false) &&
4151 return true;
4152 }
4153
4154 return false;
4155}
4156
4157static bool isNonEqualURem(const Value *X, const Value *Rem,
4158 const SimplifyQuery &Q) {
4159 const Value *Y;
4160 if (!match(Rem, m_URem(m_Specific(X), m_Value(Y))))
4161 return false;
4162
4163 // For a defined urem, X != X urem Y exactly when X u>= Y.
4164 // isTruePredicate does not handle UGE, so use the equivalent Y u<= X.
4166 return true;
4167
4168 std::optional<bool> Implied =
4170 return Implied && *Implied;
4171}
4172
4173/// Return true if it is known that V1 != V2.
4174static bool isKnownNonEqual(const Value *V1, const Value *V2,
4175 const APInt &DemandedElts, const SimplifyQuery &Q,
4176 unsigned Depth) {
4177 if (V1 == V2)
4178 return false;
4179 if (V1->getType() != V2->getType())
4180 // We can't look through casts yet.
4181 return false;
4182
4184 return false;
4185
4186 // See if we can recurse through (exactly one of) our operands. This
4187 // requires our operation be 1-to-1 and map every input value to exactly
4188 // one output value. Such an operation is invertible.
4189 auto *O1 = dyn_cast<Operator>(V1);
4190 auto *O2 = dyn_cast<Operator>(V2);
4191 if (O1 && O2 && O1->getOpcode() == O2->getOpcode()) {
4192 if (auto Values = getInvertibleOperands(O1, O2))
4193 return isKnownNonEqual(Values->first, Values->second, DemandedElts, Q,
4194 Depth + 1);
4195
4196 if (const PHINode *PN1 = dyn_cast<PHINode>(V1)) {
4197 const PHINode *PN2 = cast<PHINode>(V2);
4198 // FIXME: This is missing a generalization to handle the case where one is
4199 // a PHI and another one isn't.
4200 if (isNonEqualPHIs(PN1, PN2, DemandedElts, Q, Depth))
4201 return true;
4202 };
4203 }
4204
4205 if (isModifyingBinopOfNonZero(V1, V2, DemandedElts, Q, Depth) ||
4206 isModifyingBinopOfNonZero(V2, V1, DemandedElts, Q, Depth))
4207 return true;
4208
4209 if (isNonEqualMul(V1, V2, DemandedElts, Q, Depth) ||
4210 isNonEqualMul(V2, V1, DemandedElts, Q, Depth))
4211 return true;
4212
4213 if (isNonEqualShl(V1, V2, DemandedElts, Q, Depth) ||
4214 isNonEqualShl(V2, V1, DemandedElts, Q, Depth))
4215 return true;
4216
4217 if (V1->getType()->isIntOrIntVectorTy()) {
4218 // Are any known bits in V1 contradictory to known bits in V2? If V1
4219 // has a known zero where V2 has a known one, they must not be equal.
4220 KnownBits Known1 = computeKnownBits(V1, DemandedElts, Q, Depth);
4221 if (!Known1.isUnknown()) {
4222 KnownBits Known2 = computeKnownBits(V2, DemandedElts, Q, Depth);
4223 if (Known1.Zero.intersects(Known2.One) ||
4224 Known2.Zero.intersects(Known1.One))
4225 return true;
4226 }
4227 }
4228
4229 if (isNonEqualSelect(V1, V2, DemandedElts, Q, Depth) ||
4230 isNonEqualSelect(V2, V1, DemandedElts, Q, Depth))
4231 return true;
4232
4235 return true;
4236
4237 Value *A, *B;
4238 // PtrToInts are NonEqual if their Ptrs are NonEqual.
4239 // Check PtrToInt type matches the pointer size.
4240 if (match(V1, m_PtrToIntSameSize(Q.DL, m_Value(A))) &&
4242 return isKnownNonEqual(A, B, DemandedElts, Q, Depth + 1);
4243
4244 if (isNonEqualURem(V1, V2, Q) || isNonEqualURem(V2, V1, Q))
4245 return true;
4246
4247 if (isKnownNonEqualFromContext(V1, V2, Q, Depth))
4248 return true;
4249
4250 return false;
4251}
4252
4253/// For vector constants, loop over the elements and find the constant with the
4254/// minimum number of sign bits. Return 0 if the value is not a vector constant
4255/// or if any element was not analyzed; otherwise, return the count for the
4256/// element with the minimum number of sign bits.
4258 const APInt &DemandedElts,
4259 unsigned TyBits) {
4260 const auto *CV = dyn_cast<Constant>(V);
4261 if (!CV || !isa<FixedVectorType>(CV->getType()))
4262 return 0;
4263
4264 unsigned MinSignBits = TyBits;
4265 unsigned NumElts = cast<FixedVectorType>(CV->getType())->getNumElements();
4266 for (unsigned i = 0; i != NumElts; ++i) {
4267 if (!DemandedElts[i])
4268 continue;
4269 // If we find a non-ConstantInt, bail out.
4270 auto *Elt = dyn_cast_or_null<ConstantInt>(CV->getAggregateElement(i));
4271 if (!Elt)
4272 return 0;
4273
4274 MinSignBits = std::min(MinSignBits, Elt->getValue().getNumSignBits());
4275 }
4276
4277 return MinSignBits;
4278}
4279
4280static unsigned ComputeNumSignBitsImpl(const Value *V,
4281 const APInt &DemandedElts,
4282 const SimplifyQuery &Q, unsigned Depth);
4283
4284static unsigned ComputeNumSignBits(const Value *V, const APInt &DemandedElts,
4285 const SimplifyQuery &Q, unsigned Depth) {
4286 unsigned Result = ComputeNumSignBitsImpl(V, DemandedElts, Q, Depth);
4287 assert(Result > 0 && "At least one sign bit needs to be present!");
4288 return Result;
4289}
4290
4291/// Return the number of times the sign bit of the register is replicated into
4292/// the other bits. We know that at least 1 bit is always equal to the sign bit
4293/// (itself), but other cases can give us information. For example, immediately
4294/// after an "ashr X, 2", we know that the top 3 bits are all equal to each
4295/// other, so we return 3. For vectors, return the number of sign bits for the
4296/// vector element with the minimum number of known sign bits of the demanded
4297/// elements in the vector specified by DemandedElts.
4298static unsigned ComputeNumSignBitsImpl(const Value *V,
4299 const APInt &DemandedElts,
4300 const SimplifyQuery &Q, unsigned Depth) {
4301 Type *Ty = V->getType();
4302#ifndef NDEBUG
4303 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
4304
4305 if (auto *FVTy = dyn_cast<FixedVectorType>(Ty)) {
4306 assert(
4307 FVTy->getNumElements() == DemandedElts.getBitWidth() &&
4308 "DemandedElt width should equal the fixed vector number of elements");
4309 } else {
4310 assert(DemandedElts == APInt(1, 1) &&
4311 "DemandedElt width should be 1 for scalars");
4312 }
4313#endif
4314
4315 // We return the minimum number of sign bits that are guaranteed to be present
4316 // in V, so for undef we have to conservatively return 1. We don't have the
4317 // same behavior for poison though -- that's a FIXME today.
4318
4319 Type *ScalarTy = Ty->getScalarType();
4320 unsigned TyBits = ScalarTy->isPointerTy() ?
4321 Q.DL.getPointerTypeSizeInBits(ScalarTy) :
4322 Q.DL.getTypeSizeInBits(ScalarTy);
4323
4324 unsigned Tmp, Tmp2;
4325 unsigned FirstAnswer = 1;
4326
4327 // Note that ConstantInt is handled by the general computeKnownBits case
4328 // below.
4329
4331 return 1;
4332
4333 if (auto *U = dyn_cast<Operator>(V)) {
4334 switch (Operator::getOpcode(V)) {
4335 default: break;
4336 case Instruction::BitCast: {
4337 Value *Src = U->getOperand(0);
4338 Type *SrcTy = Src->getType();
4339
4340 // Skip if the source type is not an integer or integer vector type
4341 // This ensures we only process integer-like types
4342 if (!SrcTy->isIntOrIntVectorTy())
4343 break;
4344
4345 unsigned SrcBits = SrcTy->getScalarSizeInBits();
4346
4347 // Bitcast 'large element' scalar/vector to 'small element' vector.
4348 if ((SrcBits % TyBits) != 0)
4349 break;
4350
4351 // Only proceed if the destination type is a fixed-size vector
4352 if (isa<FixedVectorType>(Ty)) {
4353 // Fast case - sign splat can be simply split across the small elements.
4354 // This works for both vector and scalar sources
4355 Tmp = ComputeNumSignBits(Src, Q, Depth + 1);
4356 if (Tmp == SrcBits)
4357 return TyBits;
4358 }
4359 break;
4360 }
4361 case Instruction::SExt:
4362 Tmp = TyBits - U->getOperand(0)->getType()->getScalarSizeInBits();
4363 return ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1) +
4364 Tmp;
4365
4366 case Instruction::SDiv: {
4367 const APInt *Denominator;
4368 // sdiv X, C -> adds log(C) sign bits.
4369 if (match(U->getOperand(1), m_APInt(Denominator))) {
4370
4371 // Ignore non-positive denominator.
4372 if (!Denominator->isStrictlyPositive())
4373 break;
4374
4375 // Calculate the incoming numerator bits.
4376 unsigned NumBits =
4377 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4378
4379 // Add floor(log(C)) bits to the numerator bits.
4380 return std::min(TyBits, NumBits + Denominator->logBase2());
4381 }
4382 break;
4383 }
4384
4385 case Instruction::SRem: {
4386 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4387
4388 const APInt *Denominator;
4389 // srem X, C -> we know that the result is within [-C+1,C) when C is a
4390 // positive constant. This let us put a lower bound on the number of sign
4391 // bits.
4392 if (match(U->getOperand(1), m_APInt(Denominator))) {
4393
4394 // Ignore non-positive denominator.
4395 if (Denominator->isStrictlyPositive()) {
4396 // Calculate the leading sign bit constraints by examining the
4397 // denominator. Given that the denominator is positive, there are two
4398 // cases:
4399 //
4400 // 1. The numerator is positive. The result range is [0,C) and
4401 // [0,C) u< (1 << ceilLogBase2(C)).
4402 //
4403 // 2. The numerator is negative. Then the result range is (-C,0] and
4404 // integers in (-C,0] are either 0 or >u (-1 << ceilLogBase2(C)).
4405 //
4406 // Thus a lower bound on the number of sign bits is `TyBits -
4407 // ceilLogBase2(C)`.
4408
4409 unsigned ResBits = TyBits - Denominator->ceilLogBase2();
4410 Tmp = std::max(Tmp, ResBits);
4411 }
4412 }
4413 return Tmp;
4414 }
4415
4416 case Instruction::AShr: {
4417 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4418 // ashr X, C -> adds C sign bits. Vectors too.
4419 const APInt *ShAmt;
4420 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4421 if (ShAmt->uge(TyBits))
4422 break; // Bad shift.
4423 unsigned ShAmtLimited = ShAmt->getZExtValue();
4424 Tmp += ShAmtLimited;
4425 if (Tmp > TyBits) Tmp = TyBits;
4426 }
4427 return Tmp;
4428 }
4429 case Instruction::Shl: {
4430 const APInt *ShAmt;
4431 Value *X = nullptr;
4432 if (match(U->getOperand(1), m_APInt(ShAmt))) {
4433 // shl destroys sign bits.
4434 if (ShAmt->uge(TyBits))
4435 break; // Bad shift.
4436 // We can look through a zext (more or less treating it as a sext) if
4437 // all extended bits are shifted out.
4438 if (match(U->getOperand(0), m_ZExt(m_Value(X))) &&
4439 ShAmt->uge(TyBits - X->getType()->getScalarSizeInBits())) {
4440 Tmp = ComputeNumSignBits(X, DemandedElts, Q, Depth + 1);
4441 Tmp += TyBits - X->getType()->getScalarSizeInBits();
4442 } else
4443 Tmp =
4444 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4445 if (ShAmt->uge(Tmp))
4446 break; // Shifted all sign bits out.
4447 Tmp2 = ShAmt->getZExtValue();
4448 return Tmp - Tmp2;
4449 }
4450 break;
4451 }
4452 case Instruction::And:
4453 case Instruction::Or:
4454 case Instruction::Xor: // NOT is handled here.
4455 // Logical binary ops preserve the number of sign bits at the worst.
4456 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4457 if (Tmp != 1) {
4458 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4459 FirstAnswer = std::min(Tmp, Tmp2);
4460 // We computed what we know about the sign bits as our first
4461 // answer. Now proceed to the generic code that uses
4462 // computeKnownBits, and pick whichever answer is better.
4463 }
4464 break;
4465
4466 case Instruction::Select: {
4467 // If we have a clamp pattern, we know that the number of sign bits will
4468 // be the minimum of the clamp min/max range.
4469 const Value *X;
4470 const APInt *CLow, *CHigh;
4471 if (isSignedMinMaxClamp(U, X, CLow, CHigh))
4472 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4473
4474 Tmp = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4475 if (Tmp == 1)
4476 break;
4477 Tmp2 = ComputeNumSignBits(U->getOperand(2), DemandedElts, Q, Depth + 1);
4478 return std::min(Tmp, Tmp2);
4479 }
4480
4481 case Instruction::Add:
4482 // Add can have at most one carry bit. Thus we know that the output
4483 // is, at worst, one more bit than the inputs.
4484 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4485 if (Tmp == 1) break;
4486
4487 // Special case decrementing a value (ADD X, -1):
4488 if (const auto *CRHS = dyn_cast<Constant>(U->getOperand(1)))
4489 if (CRHS->isAllOnesValue()) {
4490 KnownBits Known(TyBits);
4491 computeKnownBits(U->getOperand(0), DemandedElts, Known, Q, Depth + 1);
4492
4493 // If the input is known to be 0 or 1, the output is 0/-1, which is
4494 // all sign bits set.
4495 if ((Known.Zero | 1).isAllOnes())
4496 return TyBits;
4497
4498 // If we are subtracting one from a positive number, there is no carry
4499 // out of the result.
4500 if (Known.isNonNegative())
4501 return Tmp;
4502 }
4503
4504 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4505 if (Tmp2 == 1)
4506 break;
4507 return std::min(Tmp, Tmp2) - 1;
4508
4509 case Instruction::Sub:
4510 Tmp2 = ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4511 if (Tmp2 == 1)
4512 break;
4513
4514 // Handle NEG.
4515 if (const auto *CLHS = dyn_cast<Constant>(U->getOperand(0)))
4516 if (CLHS->isNullValue()) {
4517 KnownBits Known(TyBits);
4518 computeKnownBits(U->getOperand(1), DemandedElts, Known, Q, Depth + 1);
4519 // If the input is known to be 0 or 1, the output is 0/-1, which is
4520 // all sign bits set.
4521 if ((Known.Zero | 1).isAllOnes())
4522 return TyBits;
4523
4524 // If the input is known to be positive (the sign bit is known clear),
4525 // the output of the NEG has the same number of sign bits as the
4526 // input.
4527 if (Known.isNonNegative())
4528 return Tmp2;
4529
4530 // Otherwise, we treat this like a SUB.
4531 }
4532
4533 // Sub can have at most one carry bit. Thus we know that the output
4534 // is, at worst, one more bit than the inputs.
4535 Tmp = ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4536 if (Tmp == 1)
4537 break;
4538 return std::min(Tmp, Tmp2) - 1;
4539
4540 case Instruction::Mul: {
4541 // The output of the Mul can be at most twice the valid bits in the
4542 // inputs.
4543 unsigned SignBitsOp0 =
4544 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4545 if (SignBitsOp0 == 1)
4546 break;
4547 unsigned SignBitsOp1 =
4548 ComputeNumSignBits(U->getOperand(1), DemandedElts, Q, Depth + 1);
4549 if (SignBitsOp1 == 1)
4550 break;
4551 unsigned OutValidBits =
4552 (TyBits - SignBitsOp0 + 1) + (TyBits - SignBitsOp1 + 1);
4553 return OutValidBits > TyBits ? 1 : TyBits - OutValidBits + 1;
4554 }
4555
4556 case Instruction::PHI: {
4557 const PHINode *PN = cast<PHINode>(U);
4558 unsigned NumIncomingValues = PN->getNumIncomingValues();
4559 // Don't analyze large in-degree PHIs.
4560 if (NumIncomingValues > 4) break;
4561 // Unreachable blocks may have zero-operand PHI nodes.
4562 if (NumIncomingValues == 0) break;
4563
4564 // Take the minimum of all incoming values. This can't infinitely loop
4565 // because of our depth threshold.
4567 Tmp = TyBits;
4568 for (unsigned i = 0, e = NumIncomingValues; i != e; ++i) {
4569 if (Tmp == 1) return Tmp;
4570 RecQ.CxtI = PN->getIncomingBlock(i)->getTerminator();
4571 Tmp = std::min(Tmp, ComputeNumSignBits(PN->getIncomingValue(i),
4572 DemandedElts, RecQ, Depth + 1));
4573 }
4574 return Tmp;
4575 }
4576
4577 case Instruction::Trunc: {
4578 // If the input contained enough sign bits that some remain after the
4579 // truncation, then we can make use of that. Otherwise we don't know
4580 // anything.
4581 Tmp = ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4582 unsigned OperandTyBits = U->getOperand(0)->getType()->getScalarSizeInBits();
4583 if (Tmp > (OperandTyBits - TyBits))
4584 return Tmp - (OperandTyBits - TyBits);
4585
4586 return 1;
4587 }
4588
4589 case Instruction::ExtractElement:
4590 // Look through extract element. At the moment we keep this simple and
4591 // skip tracking the specific element. But at least we might find
4592 // information valid for all elements of the vector (for example if vector
4593 // is sign extended, shifted, etc).
4594 return ComputeNumSignBits(U->getOperand(0), Q, Depth + 1);
4595
4596 case Instruction::ShuffleVector: {
4597 // Collect the minimum number of sign bits that are shared by every vector
4598 // element referenced by the shuffle.
4599 auto *Shuf = dyn_cast<ShuffleVectorInst>(U);
4600 if (!Shuf) {
4601 // FIXME: Add support for shufflevector constant expressions.
4602 return 1;
4603 }
4604 APInt DemandedLHS, DemandedRHS;
4605 // For undef elements, we don't know anything about the common state of
4606 // the shuffle result.
4607 if (!getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
4608 return 1;
4609 Tmp = std::numeric_limits<unsigned>::max();
4610 if (!!DemandedLHS) {
4611 const Value *LHS = Shuf->getOperand(0);
4612 Tmp = ComputeNumSignBits(LHS, DemandedLHS, Q, Depth + 1);
4613 }
4614 // If we don't know anything, early out and try computeKnownBits
4615 // fall-back.
4616 if (Tmp == 1)
4617 break;
4618 if (!!DemandedRHS) {
4619 const Value *RHS = Shuf->getOperand(1);
4620 Tmp2 = ComputeNumSignBits(RHS, DemandedRHS, Q, Depth + 1);
4621 Tmp = std::min(Tmp, Tmp2);
4622 }
4623 // If we don't know anything, early out and try computeKnownBits
4624 // fall-back.
4625 if (Tmp == 1)
4626 break;
4627 assert(Tmp <= TyBits && "Failed to determine minimum sign bits");
4628 return Tmp;
4629 }
4630 case Instruction::Call: {
4631 if (const auto *II = dyn_cast<IntrinsicInst>(U)) {
4632 switch (II->getIntrinsicID()) {
4633 default:
4634 break;
4635 case Intrinsic::abs:
4636 Tmp =
4637 ComputeNumSignBits(U->getOperand(0), DemandedElts, Q, Depth + 1);
4638 if (Tmp == 1)
4639 break;
4640
4641 // Absolute value reduces number of sign bits by at most 1.
4642 return Tmp - 1;
4643 case Intrinsic::smin:
4644 case Intrinsic::smax: {
4645 const APInt *CLow, *CHigh;
4646 if (isSignedMinMaxIntrinsicClamp(II, CLow, CHigh))
4647 return std::min(CLow->getNumSignBits(), CHigh->getNumSignBits());
4648 }
4649 }
4650 }
4651 }
4652 }
4653 }
4654
4655 // Finally, if we can prove that the top bits of the result are 0's or 1's,
4656 // use this information.
4657
4658 // If we can examine all elements of a vector constant successfully, we're
4659 // done (we can't do any better than that). If not, keep trying.
4660 if (unsigned VecSignBits =
4661 computeNumSignBitsVectorConstant(V, DemandedElts, TyBits))
4662 return VecSignBits;
4663
4664 KnownBits Known(TyBits);
4665 computeKnownBits(V, DemandedElts, Known, Q, Depth);
4666
4667 // If we know that the sign bit is either zero or one, determine the number of
4668 // identical bits in the top of the input value.
4669 return std::max(FirstAnswer, Known.countMinSignBits());
4670}
4671
4673 const TargetLibraryInfo *TLI) {
4674 const Function *F = CB.getCalledFunction();
4675 if (!F)
4677
4678 if (F->isIntrinsic())
4679 return F->getIntrinsicID();
4680
4681 // We are going to infer semantics of a library function based on mapping it
4682 // to an LLVM intrinsic. Check that the library function is available from
4683 // this callbase and in this environment.
4684 if (F->hasLocalLinkage() || !TLI || !CB.onlyReadsMemory())
4686
4687 LibFunc Func = TLI->getLibFunc(CB);
4688 if (Func == NotLibFunc)
4690
4691 switch (Func) {
4692 default:
4693 break;
4694 case LibFunc_sin:
4695 case LibFunc_sinf:
4696 case LibFunc_sinl:
4697 return Intrinsic::sin;
4698 case LibFunc_cos:
4699 case LibFunc_cosf:
4700 case LibFunc_cosl:
4701 return Intrinsic::cos;
4702 case LibFunc_tan:
4703 case LibFunc_tanf:
4704 case LibFunc_tanl:
4705 return Intrinsic::tan;
4706 case LibFunc_asin:
4707 case LibFunc_asinf:
4708 case LibFunc_asinl:
4709 return Intrinsic::asin;
4710 case LibFunc_acos:
4711 case LibFunc_acosf:
4712 case LibFunc_acosl:
4713 return Intrinsic::acos;
4714 case LibFunc_atan:
4715 case LibFunc_atanf:
4716 case LibFunc_atanl:
4717 return Intrinsic::atan;
4718 case LibFunc_atan2:
4719 case LibFunc_atan2f:
4720 case LibFunc_atan2l:
4721 return Intrinsic::atan2;
4722 case LibFunc_sinh:
4723 case LibFunc_sinhf:
4724 case LibFunc_sinhl:
4725 return Intrinsic::sinh;
4726 case LibFunc_cosh:
4727 case LibFunc_coshf:
4728 case LibFunc_coshl:
4729 return Intrinsic::cosh;
4730 case LibFunc_tanh:
4731 case LibFunc_tanhf:
4732 case LibFunc_tanhl:
4733 return Intrinsic::tanh;
4734 case LibFunc_exp:
4735 case LibFunc_expf:
4736 case LibFunc_expl:
4737 return Intrinsic::exp;
4738 case LibFunc_exp2:
4739 case LibFunc_exp2f:
4740 case LibFunc_exp2l:
4741 return Intrinsic::exp2;
4742 case LibFunc_exp10:
4743 case LibFunc_exp10f:
4744 case LibFunc_exp10l:
4745 return Intrinsic::exp10;
4746 case LibFunc_log:
4747 case LibFunc_logf:
4748 case LibFunc_logl:
4749 return Intrinsic::log;
4750 case LibFunc_log10:
4751 case LibFunc_log10f:
4752 case LibFunc_log10l:
4753 return Intrinsic::log10;
4754 case LibFunc_log2:
4755 case LibFunc_log2f:
4756 case LibFunc_log2l:
4757 return Intrinsic::log2;
4758 case LibFunc_fabs:
4759 case LibFunc_fabsf:
4760 case LibFunc_fabsl:
4761 return Intrinsic::fabs;
4762 case LibFunc_fmin:
4763 case LibFunc_fminf:
4764 case LibFunc_fminl:
4765 return Intrinsic::minnum;
4766 case LibFunc_fmax:
4767 case LibFunc_fmaxf:
4768 case LibFunc_fmaxl:
4769 return Intrinsic::maxnum;
4770 case LibFunc_copysign:
4771 case LibFunc_copysignf:
4772 case LibFunc_copysignl:
4773 return Intrinsic::copysign;
4774 case LibFunc_floor:
4775 case LibFunc_floorf:
4776 case LibFunc_floorl:
4777 return Intrinsic::floor;
4778 case LibFunc_ceil:
4779 case LibFunc_ceilf:
4780 case LibFunc_ceill:
4781 return Intrinsic::ceil;
4782 case LibFunc_trunc:
4783 case LibFunc_truncf:
4784 case LibFunc_truncl:
4785 return Intrinsic::trunc;
4786 case LibFunc_rint:
4787 case LibFunc_rintf:
4788 case LibFunc_rintl:
4789 return Intrinsic::rint;
4790 case LibFunc_nearbyint:
4791 case LibFunc_nearbyintf:
4792 case LibFunc_nearbyintl:
4793 return Intrinsic::nearbyint;
4794 case LibFunc_round:
4795 case LibFunc_roundf:
4796 case LibFunc_roundl:
4797 return Intrinsic::round;
4798 case LibFunc_roundeven:
4799 case LibFunc_roundevenf:
4800 case LibFunc_roundevenl:
4801 return Intrinsic::roundeven;
4802 case LibFunc_pow:
4803 case LibFunc_powf:
4804 case LibFunc_powl:
4805 return Intrinsic::pow;
4806 case LibFunc_sqrt:
4807 case LibFunc_sqrtf:
4808 case LibFunc_sqrtl:
4809 return Intrinsic::sqrt;
4810 }
4811
4813}
4814
4815/// Given an exploded icmp instruction, return true if the comparison only
4816/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
4817/// the result of the comparison is true when the input value is signed.
4819 bool &TrueIfSigned) {
4820 switch (Pred) {
4821 case ICmpInst::ICMP_SLT: // True if LHS s< 0
4822 TrueIfSigned = true;
4823 return RHS.isZero();
4824 case ICmpInst::ICMP_SLE: // True if LHS s<= -1
4825 TrueIfSigned = true;
4826 return RHS.isAllOnes();
4827 case ICmpInst::ICMP_SGT: // True if LHS s> -1
4828 TrueIfSigned = false;
4829 return RHS.isAllOnes();
4830 case ICmpInst::ICMP_SGE: // True if LHS s>= 0
4831 TrueIfSigned = false;
4832 return RHS.isZero();
4833 case ICmpInst::ICMP_UGT:
4834 // True if LHS u> RHS and RHS == sign-bit-mask - 1
4835 TrueIfSigned = true;
4836 return RHS.isMaxSignedValue();
4837 case ICmpInst::ICMP_UGE:
4838 // True if LHS u>= RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4839 TrueIfSigned = true;
4840 return RHS.isMinSignedValue();
4841 case ICmpInst::ICMP_ULT:
4842 // True if LHS u< RHS and RHS == sign-bit-mask (2^7, 2^15, 2^31, etc)
4843 TrueIfSigned = false;
4844 return RHS.isMinSignedValue();
4845 case ICmpInst::ICMP_ULE:
4846 // True if LHS u<= RHS and RHS == sign-bit-mask - 1
4847 TrueIfSigned = false;
4848 return RHS.isMaxSignedValue();
4849 default:
4850 return false;
4851 }
4852}
4853
4855 bool CondIsTrue,
4856 const Instruction *CxtI,
4857 KnownFPClass &KnownFromContext,
4858 unsigned Depth = 0) {
4859 Value *A, *B;
4861 (CondIsTrue ? match(Cond, m_LogicalAnd(m_Value(A), m_Value(B)))
4862 : match(Cond, m_LogicalOr(m_Value(A), m_Value(B))))) {
4863 computeKnownFPClassFromCond(V, A, CondIsTrue, CxtI, KnownFromContext,
4864 Depth + 1);
4865 computeKnownFPClassFromCond(V, B, CondIsTrue, CxtI, KnownFromContext,
4866 Depth + 1);
4867 return;
4868 }
4870 computeKnownFPClassFromCond(V, A, !CondIsTrue, CxtI, KnownFromContext,
4871 Depth + 1);
4872 return;
4873 }
4874 CmpPredicate Pred;
4875 Value *LHS;
4876 uint64_t ClassVal = 0;
4877 const APFloat *CRHS;
4878 const APInt *RHS;
4879 if (match(Cond, m_FCmp(Pred, m_Value(LHS), m_APFloat(CRHS)))) {
4880 auto [CmpVal, MaskIfTrue, MaskIfFalse] = fcmpImpliesClass(
4881 Pred, *cast<Instruction>(Cond)->getParent()->getParent(), LHS, *CRHS,
4882 LHS != V);
4883 if (CmpVal == V)
4884 KnownFromContext.knownNot(~(CondIsTrue ? MaskIfTrue : MaskIfFalse));
4886 m_Specific(V), m_ConstantInt(ClassVal)))) {
4887 FPClassTest Mask = static_cast<FPClassTest>(ClassVal);
4888 KnownFromContext.knownNot(CondIsTrue ? ~Mask : Mask);
4889 } else if (match(Cond, m_ICmp(Pred, m_ElementWiseBitCast(m_Specific(V)),
4890 m_APInt(RHS)))) {
4891 bool TrueIfSigned;
4892 if (!isSignBitCheck(Pred, *RHS, TrueIfSigned))
4893 return;
4894 if (TrueIfSigned == CondIsTrue)
4895 KnownFromContext.signBitMustBeOne();
4896 else
4897 KnownFromContext.signBitMustBeZero();
4898 }
4899}
4900
4901/// Compute the minimum and maximum values (inclusive) for the exponent of \p V,
4902/// assuming it is not nan. Returns {min, max, max-assuming-nonzero}. A value
4903/// frexp(0) = 0, so the tighter max-assuming-nonzero bound is only usable when
4904/// \p V is known not to be a logical zero (e.g., for fabs(x) < 0.25, the non-0
4905/// exponent range is [-149, -2], but the 0 edge case is above this range).
4906static std::tuple<int, int, int>
4908 if (!Q.CxtI || !Q.DC || !Q.DT)
4910
4911 // Intersect the bounds implied by every dominating condition, keeping the
4912 // tightest maximum. A value may participate in multiple compares
4913 // (e.g. fabs(x) < 2.0 and fabs(x) < 1.0), and the tighter one wins.
4914 int MaxExp = APFloat::IEK_Inf;
4915 int MaxExpNonZero = APFloat::IEK_Inf;
4916
4917 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4918 CmpPredicate Pred;
4919 const APFloat *LimitC;
4920 if (!match(BI->getCondition(),
4921 m_FCmp(Pred, m_FAbs(m_Specific(V)), m_Finite(LimitC))))
4922 continue;
4923
4924 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO ||
4925 Pred == FCmpInst::FCMP_TRUE || Pred == FCmpInst::FCMP_FALSE)
4926 continue;
4927
4928 // If fabs(x) <= K, implies the exponent min exp range.
4929 // if fabs(x) >= K, swap the successor
4930 bool IsLessEqual =
4931 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE ||
4932 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE ||
4933 Pred == FCmpInst::FCMP_OEQ || Pred == FCmpInst::FCMP_UEQ;
4934
4935 bool KnownStrictlyLess =
4936 Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_ULT ||
4937 Pred == FCmpInst::FCMP_OGE || Pred == FCmpInst::FCMP_UGE;
4938
4939 BasicBlockEdge Edge1(BI->getParent(),
4940 BI->getSuccessor(IsLessEqual ? 0 : 1));
4941 if (Q.DT->dominates(Edge1, Q.CxtI->getParent())) {
4942 // frexp returns an exponent one greater than ilogb.
4943 int Exp = ilogb(*LimitC) + 1;
4944
4945 // A strict bound fabs(V) < 2^n forces ilogb(V) <= n - 1, so the max frexp
4946 // exponent drops by one when K is exact power of two.
4947 if (KnownStrictlyLess && LimitC->getExactLog2Abs() != INT_MIN)
4948 --Exp;
4949
4950 // frexp(0) = 0, which the bound above (assuming a normal nonzero value)
4951 // may exclude.
4952
4953 // TODO: Figure out lower bound to detect no-underflow.
4954 MaxExpNonZero = std::min(MaxExpNonZero, Exp);
4955 MaxExp = std::min(MaxExp, std::max(Exp, 0));
4956 }
4957 }
4958
4959 return {APFloat::IEK_NaN, MaxExp, MaxExpNonZero};
4960}
4961
4963 const SimplifyQuery &Q) {
4964 KnownFPClass KnownFromContext;
4965
4966 if (Q.CC && Q.CC->AffectedValues.contains(V))
4968 KnownFromContext);
4969
4970 if (!Q.CxtI)
4971 return KnownFromContext;
4972
4973 if (Q.DC && Q.DT) {
4974 // Handle dominating conditions.
4975 for (CondBrInst *BI : Q.DC->conditionsFor(V)) {
4976 Value *Cond = BI->getCondition();
4977
4978 BasicBlockEdge Edge0(BI->getParent(), BI->getSuccessor(0));
4979 if (Q.DT->dominates(Edge0, Q.CxtI->getParent()))
4980 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/true, Q.CxtI,
4981 KnownFromContext);
4982
4983 BasicBlockEdge Edge1(BI->getParent(), BI->getSuccessor(1));
4984 if (Q.DT->dominates(Edge1, Q.CxtI->getParent()))
4985 computeKnownFPClassFromCond(V, Cond, /*CondIsTrue=*/false, Q.CxtI,
4986 KnownFromContext);
4987 }
4988 }
4989
4990 if (!Q.AC)
4991 return KnownFromContext;
4992
4993 // Try to restrict the floating-point classes based on information from
4994 // assumptions.
4995 for (auto &AssumeVH : Q.AC->assumptionsFor(V)) {
4996 if (!AssumeVH)
4997 continue;
4998 CallInst *I = cast<CallInst>(AssumeVH);
4999
5000 assert(I->getFunction() == Q.CxtI->getParent()->getParent() &&
5001 "Got assumption for the wrong function!");
5002 assert(I->getIntrinsicID() == Intrinsic::assume &&
5003 "must be an assume intrinsic");
5004
5005 if (!isValidAssumeForContext(I, Q))
5006 continue;
5007
5008 computeKnownFPClassFromCond(V, I->getArgOperand(0),
5009 /*CondIsTrue=*/true, Q.CxtI, KnownFromContext);
5010 }
5011
5012 return KnownFromContext;
5013}
5014
5016 Value *Arm, bool Invert,
5017 const SimplifyQuery &SQ,
5018 unsigned Depth) {
5019
5020 KnownFPClass KnownSrc;
5022 /*CondIsTrue=*/!Invert, SQ.CxtI, KnownSrc,
5023 Depth + 1);
5024 KnownSrc = KnownSrc.unionWith(Known);
5025 if (KnownSrc.isUnknown())
5026 return;
5027
5028 if (isGuaranteedNotToBeUndef(Arm, SQ.AC, SQ.CxtI, SQ.DT, Depth + 1))
5029 Known = KnownSrc;
5030}
5031
5032void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5033 FPClassTest InterestedClasses, KnownFPClass &Known,
5034 const SimplifyQuery &Q, unsigned Depth);
5035
5037 FPClassTest InterestedClasses,
5038 const SimplifyQuery &Q, unsigned Depth) {
5039 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
5040 APInt DemandedElts =
5041 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
5042 computeKnownFPClass(V, DemandedElts, InterestedClasses, Known, Q, Depth);
5043}
5044
5046 const APInt &DemandedElts,
5047 FPClassTest InterestedClasses,
5049 const SimplifyQuery &Q,
5050 unsigned Depth) {
5051 if ((InterestedClasses &
5053 return;
5054
5055 KnownFPClass KnownSrc;
5056 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5057 KnownSrc, Q, Depth + 1);
5058 Known = KnownFPClass::fptrunc(KnownSrc);
5059}
5060
5062 switch (IID) {
5063 case Intrinsic::minimum:
5065 case Intrinsic::maximum:
5067 case Intrinsic::minimumnum:
5069 case Intrinsic::maximumnum:
5071 case Intrinsic::minnum:
5073 case Intrinsic::maxnum:
5075 default:
5076 llvm_unreachable("not a floating-point min-max intrinsic");
5077 }
5078}
5079
5080/// \return true if this is a floating point value that is known to have a
5081/// magnitude smaller than 1. i.e., fabs(X) <= 1.0 or is nan.
5082static bool isAbsoluteValueULEOne(const Value *V) {
5083 // TODO: Handle frexp
5084 // TODO: Other rounding intrinsics?
5085 // TODO: Try computeKnownExponentRangeFromContext
5086
5087 // fabs(x - floor(x)) <= 1
5088 const Value *SubFloorX;
5089 if (match(V, m_FSub(m_Value(SubFloorX),
5091 return true;
5092
5095}
5096
5097void computeKnownFPClass(const Value *V, const APInt &DemandedElts,
5098 FPClassTest InterestedClasses, KnownFPClass &Known,
5099 const SimplifyQuery &Q, unsigned Depth) {
5100 assert(Known.isUnknown() && "should not be called with known information");
5101
5102 if (!DemandedElts) {
5103 // No demanded elts, better to assume we don't know anything.
5104 Known.resetAll();
5105 return;
5106 }
5107
5108 assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
5109
5110 if (auto *CFP = dyn_cast<ConstantFP>(V)) {
5111 Known = KnownFPClass(CFP->getValueAPF());
5112 return;
5113 }
5114
5116 Known.KnownFPClasses = fcPosZero;
5117 Known.SignBit = false;
5118 return;
5119 }
5120
5121 if (isa<PoisonValue>(V)) {
5122 Known.KnownFPClasses = fcNone;
5123 Known.SignBit = false;
5124 return;
5125 }
5126
5127 // Try to handle fixed width vector constants
5128 auto *VFVTy = dyn_cast<FixedVectorType>(V->getType());
5129 const Constant *CV = dyn_cast<Constant>(V);
5130 if (VFVTy && CV) {
5131 Known.KnownFPClasses = fcNone;
5132 bool SignBitAllZero = true;
5133 bool SignBitAllOne = true;
5134
5135 // For vectors, verify that each element is not NaN.
5136 unsigned NumElts = VFVTy->getNumElements();
5137 for (unsigned i = 0; i != NumElts; ++i) {
5138 if (!DemandedElts[i])
5139 continue;
5140
5141 Constant *Elt = CV->getAggregateElement(i);
5142 if (!Elt) {
5143 Known = KnownFPClass();
5144 return;
5145 }
5146 if (isa<PoisonValue>(Elt))
5147 continue;
5148 auto *CElt = dyn_cast<ConstantFP>(Elt);
5149 if (!CElt) {
5150 Known = KnownFPClass();
5151 return;
5152 }
5153
5154 const APFloat &C = CElt->getValueAPF();
5155 Known.KnownFPClasses |= C.classify();
5156 if (C.isNegative())
5157 SignBitAllZero = false;
5158 else
5159 SignBitAllOne = false;
5160 }
5161 if (SignBitAllOne != SignBitAllZero)
5162 Known.SignBit = SignBitAllOne;
5163 return;
5164 }
5165
5166 if (const auto *CDS = dyn_cast<ConstantDataSequential>(V)) {
5167 Known.KnownFPClasses = fcNone;
5168 for (size_t I = 0, E = CDS->getNumElements(); I != E; ++I)
5169 Known |= CDS->getElementAsAPFloat(I).classify();
5170 return;
5171 }
5172
5173 if (const auto *CA = dyn_cast<ConstantAggregate>(V)) {
5174 // TODO: Handle complex aggregates
5175 Known.KnownFPClasses = fcNone;
5176 for (const Use &Op : CA->operands()) {
5177 auto *CFP = dyn_cast<ConstantFP>(Op.get());
5178 if (!CFP) {
5179 Known = KnownFPClass();
5180 return;
5181 }
5182
5183 Known |= CFP->getValueAPF().classify();
5184 }
5185
5186 return;
5187 }
5188
5189 FPClassTest KnownNotFromFlags = fcNone;
5190 if (const auto *CB = dyn_cast<CallBase>(V))
5191 KnownNotFromFlags |= CB->getRetNoFPClass();
5192 else if (const auto *Arg = dyn_cast<Argument>(V))
5193 KnownNotFromFlags |= Arg->getNoFPClass();
5194
5195 const Operator *Op = dyn_cast<Operator>(V);
5197 if (FPOp->hasNoNaNs())
5198 KnownNotFromFlags |= fcNan;
5199 if (FPOp->hasNoInfs())
5200 KnownNotFromFlags |= fcInf;
5201 }
5202
5203 KnownFPClass AssumedClasses = computeKnownFPClassFromContext(V, Q);
5204 KnownNotFromFlags |= ~AssumedClasses.KnownFPClasses;
5205
5206 // We no longer need to find out about these bits from inputs if we can
5207 // assume this from flags/attributes.
5208 InterestedClasses &= ~KnownNotFromFlags;
5209
5210 llvm::scope_exit ClearClassesFromFlags([=, &Known] {
5211 Known.knownNot(KnownNotFromFlags);
5212 if (!Known.SignBit && AssumedClasses.SignBit) {
5213 if (*AssumedClasses.SignBit)
5214 Known.signBitMustBeOne();
5215 else
5216 Known.signBitMustBeZero();
5217 }
5218 });
5219
5220 if (!Op)
5221 return;
5222
5223 // All recursive calls that increase depth must come after this.
5225 return;
5226
5227 const unsigned Opc = Op->getOpcode();
5228 switch (Opc) {
5229 case Instruction::FNeg: {
5230 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
5231 Known, Q, Depth + 1);
5232 Known.fneg();
5233 break;
5234 }
5235 case Instruction::Select: {
5236 auto ComputeForArm = [&](Value *Arm, bool Invert) {
5237 KnownFPClass Res;
5238 computeKnownFPClass(Arm, DemandedElts, InterestedClasses, Res, Q,
5239 Depth + 1);
5240 adjustKnownFPClassForSelectArm(Res, Op->getOperand(0), Arm, Invert, Q,
5241 Depth);
5242 return Res;
5243 };
5244 // Only known if known in both the LHS and RHS.
5245 Known =
5246 ComputeForArm(Op->getOperand(1), /*Invert=*/false)
5247 .intersectWith(ComputeForArm(Op->getOperand(2), /*Invert=*/true));
5248 break;
5249 }
5250 case Instruction::Load: {
5251 const MDNode *NoFPClass =
5252 cast<LoadInst>(Op)->getMetadata(LLVMContext::MD_nofpclass);
5253 if (!NoFPClass)
5254 break;
5255
5256 ConstantInt *MaskVal =
5258 Known.knownNot(static_cast<FPClassTest>(MaskVal->getZExtValue()));
5259 break;
5260 }
5261 case Instruction::Call: {
5262 const CallInst *II = cast<CallInst>(Op);
5263 const Intrinsic::ID IID = II->getIntrinsicID();
5264 switch (IID) {
5265 case Intrinsic::fabs: {
5266 if ((InterestedClasses & (fcNan | fcPositive)) != fcNone) {
5267 // If we only care about the sign bit we don't need to inspect the
5268 // operand.
5269 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5270 InterestedClasses, Known, Q, Depth + 1);
5271 }
5272
5273 Known.fabs();
5274 break;
5275 }
5276 case Intrinsic::copysign: {
5277 KnownFPClass KnownSign;
5278
5279 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5280 Known, Q, Depth + 1);
5281 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5282 KnownSign, Q, Depth + 1);
5283 Known.copysign(KnownSign);
5284 break;
5285 }
5286 case Intrinsic::fma:
5287 case Intrinsic::fmuladd: {
5288 if ((InterestedClasses & fcNegative) == fcNone)
5289 break;
5290
5291 // FIXME: This should check isGuaranteedNotToBeUndef
5292 if (II->getArgOperand(0) == II->getArgOperand(1)) {
5293 KnownFPClass KnownSrc, KnownAddend;
5294 computeKnownFPClass(II->getArgOperand(2), DemandedElts,
5295 InterestedClasses, KnownAddend, Q, Depth + 1);
5296 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5297 InterestedClasses, KnownSrc, Q, Depth + 1);
5298
5299 const Function *F = II->getFunction();
5300 const fltSemantics &FltSem =
5301 II->getType()->getScalarType()->getFltSemantics();
5303 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5304
5305 if (KnownNotFromFlags & fcNan) {
5306 KnownSrc.knownNot(fcNan);
5307 KnownAddend.knownNot(fcNan);
5308 }
5309
5310 if (KnownNotFromFlags & fcInf) {
5311 KnownSrc.knownNot(fcInf);
5312 KnownAddend.knownNot(fcInf);
5313 }
5314
5315 Known = KnownFPClass::fma_square(KnownSrc, KnownAddend, Mode);
5316 break;
5317 }
5318
5319 KnownFPClass KnownSrc[3];
5320 for (int I = 0; I != 3; ++I) {
5321 computeKnownFPClass(II->getArgOperand(I), DemandedElts,
5322 InterestedClasses, KnownSrc[I], Q, Depth + 1);
5323 if (KnownSrc[I].isUnknown())
5324 return;
5325
5326 if (KnownNotFromFlags & fcNan)
5327 KnownSrc[I].knownNot(fcNan);
5328 if (KnownNotFromFlags & fcInf)
5329 KnownSrc[I].knownNot(fcInf);
5330 }
5331
5332 const Function *F = II->getFunction();
5333 const fltSemantics &FltSem =
5334 II->getType()->getScalarType()->getFltSemantics();
5336 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5337 Known = KnownFPClass::fma(KnownSrc[0], KnownSrc[1], KnownSrc[2], Mode);
5338 break;
5339 }
5340 case Intrinsic::sqrt:
5341 case Intrinsic::experimental_constrained_sqrt: {
5342 KnownFPClass KnownSrc;
5343 FPClassTest InterestedSrcs = InterestedClasses;
5344 if (InterestedClasses & fcNan)
5345 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5346
5347 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5348 KnownSrc, Q, Depth + 1);
5349
5351
5352 bool HasNSZ = Q.IIQ.hasNoSignedZeros(II);
5353 if (!HasNSZ) {
5354 const Function *F = II->getFunction();
5355 const fltSemantics &FltSem =
5356 II->getType()->getScalarType()->getFltSemantics();
5357 Mode = F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5358 }
5359
5360 Known = KnownFPClass::sqrt(KnownSrc, Mode);
5361 if (HasNSZ)
5362 Known.knownNot(fcNegZero);
5363
5364 break;
5365 }
5366 case Intrinsic::sin: {
5367 KnownFPClass KnownSrc;
5368 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5369 KnownSrc, Q, Depth + 1);
5370 Known = KnownFPClass::sin(KnownSrc);
5371 break;
5372 }
5373 case Intrinsic::cos: {
5374 KnownFPClass KnownSrc;
5375 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5376 KnownSrc, Q, Depth + 1);
5377 Known = KnownFPClass::cos(KnownSrc);
5378 break;
5379 }
5380 case Intrinsic::tan: {
5381 KnownFPClass KnownSrc;
5382 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5383 KnownSrc, Q, Depth + 1);
5384 Known = KnownFPClass::tan(KnownSrc);
5385 break;
5386 }
5387 case Intrinsic::sinh: {
5388 KnownFPClass KnownSrc;
5389 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5390 KnownSrc, Q, Depth + 1);
5391 Known = KnownFPClass::sinh(KnownSrc);
5392 break;
5393 }
5394 case Intrinsic::cosh: {
5395 KnownFPClass KnownSrc;
5396 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5397 KnownSrc, Q, Depth + 1);
5398 Known = KnownFPClass::cosh(KnownSrc);
5399 break;
5400 }
5401 case Intrinsic::tanh: {
5402 KnownFPClass KnownSrc;
5403 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5404 KnownSrc, Q, Depth + 1);
5405 Known = KnownFPClass::tanh(KnownSrc);
5406 break;
5407 }
5408 case Intrinsic::asin: {
5409 KnownFPClass KnownSrc;
5410 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5411 KnownSrc, Q, Depth + 1);
5412 Known = KnownFPClass::asin(KnownSrc);
5413 break;
5414 }
5415 case Intrinsic::acos: {
5416 KnownFPClass KnownSrc;
5417 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5418 KnownSrc, Q, Depth + 1);
5419 Known = KnownFPClass::acos(KnownSrc);
5420 break;
5421 }
5422 case Intrinsic::atan: {
5423 KnownFPClass KnownSrc;
5424 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5425 KnownSrc, Q, Depth + 1);
5426 Known = KnownFPClass::atan(KnownSrc);
5427 break;
5428 }
5429 case Intrinsic::atan2: {
5430 FPClassTest InterestedY = InterestedClasses;
5431 FPClassTest InterestedX = InterestedClasses;
5432
5433 // We can rule out zero and subnormal if x cannot have a positive value.
5434 if ((InterestedClasses & (fcZero | fcSubnormal)) != fcNone)
5435 InterestedX |= fcPositive | fcNegSubnormal;
5436
5437 KnownFPClass KnownY, KnownX;
5438 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedY,
5439 KnownY, Q, Depth + 1);
5440 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedX,
5441 KnownX, Q, Depth + 1);
5442
5443 const Function *F = II->getFunction();
5445 F ? F->getDenormalMode(
5446 II->getType()->getScalarType()->getFltSemantics())
5448 Known = KnownFPClass::atan2(KnownY, KnownX, Mode);
5449 break;
5450 }
5451 case Intrinsic::maxnum:
5452 case Intrinsic::minnum:
5453 case Intrinsic::minimum:
5454 case Intrinsic::maximum:
5455 case Intrinsic::minimumnum:
5456 case Intrinsic::maximumnum: {
5457 KnownFPClass KnownLHS, KnownRHS;
5458 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5459 KnownLHS, Q, Depth + 1);
5460 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedClasses,
5461 KnownRHS, Q, Depth + 1);
5462
5463 const Function *F = II->getFunction();
5464
5466 F ? F->getDenormalMode(
5467 II->getType()->getScalarType()->getFltSemantics())
5469
5470 Known = KnownFPClass::minMaxLike(KnownLHS, KnownRHS, getMinMaxKind(IID),
5471 Mode);
5472 break;
5473 }
5474 case Intrinsic::canonicalize: {
5475 KnownFPClass KnownSrc;
5476 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5477 KnownSrc, Q, Depth + 1);
5478
5479 const Function *F = II->getFunction();
5480 DenormalMode DenormMode =
5481 F ? F->getDenormalMode(
5482 II->getType()->getScalarType()->getFltSemantics())
5484 Known = KnownFPClass::canonicalize(KnownSrc, DenormMode);
5485 break;
5486 }
5487 case Intrinsic::vector_reduce_fmax:
5488 case Intrinsic::vector_reduce_fmin:
5489 case Intrinsic::vector_reduce_fmaximum:
5490 case Intrinsic::vector_reduce_fminimum:
5491 case Intrinsic::vector_reduce_fmaximumnum:
5492 case Intrinsic::vector_reduce_fminimumnum: {
5493 // reduce min/max will choose an element from one of the vector elements,
5494 // so we can infer and class information that is common to all elements.
5495 Known = computeKnownFPClass(II->getArgOperand(0), II->getFastMathFlags(),
5496 InterestedClasses, Q, Depth + 1);
5497 // Can only propagate sign if output is never NaN.
5498 if (!Known.isKnownNeverNaN())
5499 Known.SignBit.reset();
5500 break;
5501 }
5502 // reverse preserves all characteristics of the input vec's element.
5503 case Intrinsic::vector_reverse:
5505 II->getArgOperand(0), DemandedElts.reverseBits(),
5506 II->getFastMathFlags(), InterestedClasses, Q, Depth + 1);
5507 break;
5508 case Intrinsic::trunc:
5509 case Intrinsic::floor:
5510 case Intrinsic::ceil:
5511 case Intrinsic::rint:
5512 case Intrinsic::nearbyint:
5513 case Intrinsic::round:
5514 case Intrinsic::roundeven: {
5515 KnownFPClass KnownSrc;
5516 FPClassTest InterestedSrcs = InterestedClasses;
5517 if (InterestedSrcs & fcPosFinite)
5518 InterestedSrcs |= fcPosFinite;
5519 if (InterestedSrcs & fcNegFinite)
5520 InterestedSrcs |= fcNegFinite;
5521 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5522 KnownSrc, Q, Depth + 1);
5523
5525 KnownSrc, IID == Intrinsic::trunc,
5526 V->getType()->getScalarType()->isMultiUnitFPType());
5527 break;
5528 }
5529 case Intrinsic::exp:
5530 case Intrinsic::exp2:
5531 case Intrinsic::exp10:
5532 case Intrinsic::amdgcn_exp2: {
5533 KnownFPClass KnownSrc;
5534 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5535 KnownSrc, Q, Depth + 1);
5536
5537 Known = KnownFPClass::exp(KnownSrc);
5538
5539 Type *EltTy = II->getType()->getScalarType();
5540 if (IID == Intrinsic::amdgcn_exp2 && EltTy->isFloatTy())
5541 Known.knownNot(fcSubnormal);
5542
5543 break;
5544 }
5545 case Intrinsic::fptrunc_round: {
5546 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known,
5547 Q, Depth);
5548 break;
5549 }
5550 case Intrinsic::log:
5551 case Intrinsic::log10:
5552 case Intrinsic::log2:
5553 case Intrinsic::experimental_constrained_log:
5554 case Intrinsic::experimental_constrained_log10:
5555 case Intrinsic::experimental_constrained_log2:
5556 case Intrinsic::amdgcn_log: {
5557 Type *EltTy = II->getType()->getScalarType();
5558
5559 // log(+inf) -> +inf
5560 // log([+-]0.0) -> -inf
5561 // log(-inf) -> nan
5562 // log(-x) -> nan
5563 if ((InterestedClasses & (fcNan | fcInf)) != fcNone) {
5564 FPClassTest InterestedSrcs = InterestedClasses;
5565 if ((InterestedClasses & fcNegInf) != fcNone)
5566 InterestedSrcs |= fcZero | fcSubnormal;
5567 if ((InterestedClasses & fcNan) != fcNone)
5568 InterestedSrcs |= fcNan | fcNegative;
5569
5570 KnownFPClass KnownSrc;
5571 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5572 KnownSrc, Q, Depth + 1);
5573
5574 const Function *F = II->getFunction();
5575 DenormalMode Mode = F ? F->getDenormalMode(EltTy->getFltSemantics())
5577 Known = KnownFPClass::log(KnownSrc, Mode);
5578 }
5579
5580 break;
5581 }
5582 case Intrinsic::pow: {
5583 const bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5584 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5585 if (!WantNaN && !WantNegative)
5586 break;
5587
5588 FPClassTest InterestedLHS = fcNone;
5589 FPClassTest InterestedRHS = fcNone;
5590 if (WantNaN) {
5591 // pow may return NaN if one of the arguments is NaN. NaN may also be
5592 // produced from a negative, non-zero finite base and a non-integer
5593 // exponent.
5594 InterestedLHS |= fcNan | fcNegNormal | fcNegSubnormal;
5595 InterestedRHS |= fcNan;
5596 }
5597 if (WantNegative) {
5598 // A negative value is returned when a negative base is raised to an odd
5599 // integer power. Only normal values can be odd integers.
5600 InterestedLHS |= fcNegative;
5601 InterestedRHS |= fcNormal;
5602 }
5603
5604 KnownFPClass KnownLHS;
5605 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedLHS,
5606 KnownLHS, Q, Depth + 1);
5607
5608 // If the LHS is unknown, then querying the RHS is only useful for rare
5609 // edge cases.
5610 if (KnownLHS.isUnknown())
5611 break;
5612
5613 KnownFPClass KnownRHS;
5614 computeKnownFPClass(II->getArgOperand(1), DemandedElts, InterestedRHS,
5615 KnownRHS, Q, Depth + 1);
5616 Known = KnownFPClass::pow(KnownLHS, KnownRHS);
5617 break;
5618 }
5619 case Intrinsic::powi: {
5620 if ((InterestedClasses & (fcNan | fcInf | fcNegative)) == fcNone)
5621 break;
5622
5623 // The exponent is always a scalar, even when raising a vector to a power.
5624 const Value *Exp = II->getArgOperand(1);
5625 unsigned BitWidth = Exp->getType()->getIntegerBitWidth();
5626 KnownBits ExponentKnownBits(BitWidth);
5627 computeKnownBits(Exp, APInt(1, 1), ExponentKnownBits, Q, Depth + 1);
5628
5629 FPClassTest InterestedSrcs = fcNone;
5630 if (InterestedClasses & fcNan)
5631 InterestedSrcs |= fcNan;
5632 if (!ExponentKnownBits.isZero()) {
5633 if (InterestedClasses & fcInf)
5634 InterestedSrcs |= fcFinite | fcInf;
5635 if ((InterestedClasses & fcNegative) && !ExponentKnownBits.isEven())
5636 InterestedSrcs |= fcNegative;
5637 }
5638
5639 KnownFPClass KnownSrc;
5640 if (InterestedSrcs != fcNone)
5641 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedSrcs,
5642 KnownSrc, Q, Depth + 1);
5643
5644 Known = KnownFPClass::powi(KnownSrc, ExponentKnownBits);
5645 break;
5646 }
5647 case Intrinsic::ldexp: {
5648 KnownFPClass KnownSrc;
5649 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5650 KnownSrc, Q, Depth + 1);
5651 // Can refine inf/zero handling based on the exponent operand.
5652 const FPClassTest ExpInfoMask = fcZero | fcSubnormal | fcInf;
5653
5654 const Value *ExpArg = II->getArgOperand(1);
5655 ConstantRange ExpKnownRange =
5656 ((KnownSrc.KnownFPClasses & ExpInfoMask) != fcNone)
5657 ? computeConstantRange(ExpArg, /*ForSigned=*/true, Q, Depth + 1)
5658 : ConstantRange::getFull(
5659 ExpArg->getType()->getScalarSizeInBits());
5660
5661 const fltSemantics &Flt =
5662 II->getType()->getScalarType()->getFltSemantics();
5663
5664 const Function *F = II->getFunction();
5666 F ? F->getDenormalMode(Flt) : DenormalMode::getDynamic();
5667
5668 Known = KnownFPClass::ldexp(KnownSrc, ExpKnownRange.getSignedMin(),
5669 ExpKnownRange.getSignedMax(), Flt, Mode);
5670 break;
5671 }
5672 case Intrinsic::arithmetic_fence: {
5673 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5674 Known, Q, Depth + 1);
5675 break;
5676 }
5677 case Intrinsic::experimental_constrained_sitofp:
5678 case Intrinsic::experimental_constrained_uitofp:
5679 // Cannot produce nan
5680 Known.knownNot(fcNan);
5681
5682 // sitofp and uitofp turn into +0.0 for zero.
5683 Known.knownNot(fcNegZero);
5684
5685 // Integers cannot be subnormal
5686 Known.knownNot(fcSubnormal);
5687
5688 if (IID == Intrinsic::experimental_constrained_uitofp)
5689 Known.signBitMustBeZero();
5690
5691 // TODO: Copy inf handling from instructions
5692 break;
5693
5694 case Intrinsic::amdgcn_fract: {
5695 Known.knownNot(fcInf);
5696
5697 if (InterestedClasses & fcNan) {
5698 KnownFPClass KnownSrc;
5699 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
5700 InterestedClasses, KnownSrc, Q, Depth + 1);
5701
5702 if (KnownSrc.isKnownNeverInfOrNaN())
5703 Known.knownNot(fcNan);
5704 else if (KnownSrc.isKnownNever(fcSNan))
5705 Known.knownNot(fcSNan);
5706 }
5707
5708 break;
5709 }
5710 case Intrinsic::amdgcn_rcp: {
5711 KnownFPClass KnownSrc;
5712 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5713 KnownSrc, Q, Depth + 1);
5714
5715 Known.propagateNonNaN(KnownSrc);
5716
5717 Type *EltTy = II->getType()->getScalarType();
5718
5719 // f32 denormal always flushed.
5720 if (EltTy->isFloatTy()) {
5721 Known.knownNot(fcSubnormal);
5722 KnownSrc.knownNot(fcSubnormal);
5723 }
5724
5725 if (KnownSrc.isKnownNever(fcNegative))
5726 Known.knownNot(fcNegative);
5727 if (KnownSrc.isKnownNever(fcPositive))
5728 Known.knownNot(fcPositive);
5729
5730 if (const Function *F = II->getFunction()) {
5731 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5732 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5733 Known.knownNot(fcPosInf);
5734 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5735 Known.knownNot(fcNegInf);
5736 }
5737
5738 break;
5739 }
5740 case Intrinsic::amdgcn_rsq: {
5741 KnownFPClass KnownSrc;
5742 // The only negative value that can be returned is -inf for -0 inputs.
5744
5745 computeKnownFPClass(II->getArgOperand(0), DemandedElts, InterestedClasses,
5746 KnownSrc, Q, Depth + 1);
5747
5748 // Negative -> nan
5749 if (KnownSrc.isKnownNeverNaN() && KnownSrc.cannotBeOrderedLessThanZero())
5750 Known.knownNot(fcNan);
5751 else if (KnownSrc.isKnownNever(fcSNan))
5752 Known.knownNot(fcSNan);
5753
5754 // +inf -> +0
5755 if (KnownSrc.isKnownNeverPosInfinity())
5756 Known.knownNot(fcPosZero);
5757
5758 Type *EltTy = II->getType()->getScalarType();
5759
5760 // f32 denormal always flushed.
5761 if (EltTy->isFloatTy())
5762 Known.knownNot(fcPosSubnormal);
5763
5764 if (const Function *F = II->getFunction()) {
5765 DenormalMode Mode = F->getDenormalMode(EltTy->getFltSemantics());
5766
5767 // -0 -> -inf
5768 if (KnownSrc.isKnownNeverLogicalNegZero(Mode))
5769 Known.knownNot(fcNegInf);
5770
5771 // +0 -> +inf
5772 if (KnownSrc.isKnownNeverLogicalPosZero(Mode))
5773 Known.knownNot(fcPosInf);
5774 }
5775
5776 break;
5777 }
5778 case Intrinsic::amdgcn_trig_preop: {
5779 // Always returns a value [0, 1)
5780 Known.knownNot(fcNan | fcInf | fcNegative);
5781 break;
5782 }
5783 case Intrinsic::convert_from_arbitrary_fp: {
5784 auto *MD = cast<MetadataAsValue>(II->getArgOperand(1))->getMetadata();
5785 StringRef FormatStr = cast<MDString>(MD)->getString();
5786
5787 const fltSemantics *SrcSemantics =
5789 if (!SrcSemantics)
5790 break;
5791
5792 const fltSemantics DstSemantics =
5793 II->getType()->getScalarType()->getFltSemantics();
5794
5795 if (!APFloat::semanticsHasNaN(*SrcSemantics))
5796 Known.knownNot(fcNan);
5797
5798 // fcInf can only be cleared if the source format has no Inf encoding
5799 // and the dst max exp can accommodate src max exp.
5800 if (!APFloat::semanticsHasInf(*SrcSemantics) &&
5801 APFloat::semanticsMaxExponent(*SrcSemantics) <=
5802 APFloat::semanticsMaxExponent(DstSemantics))
5803 Known.knownNot(fcInf);
5804
5805 // Check and clear all neg flags for formats that do not have signed
5806 // representation.
5807 if (!APFloat::semanticsHasSignedRepr(*SrcSemantics))
5808 Known.knownNot(fcNegative);
5809
5810 // Check if format has no zero at all (Float8E8M0FNU), or no negative
5811 // zero.
5812 if (!APFloat::semanticsHasZero(*SrcSemantics))
5813 Known.knownNot(fcZero);
5814 else if (SrcSemantics->nanEncoding == fltNanEncoding::NegativeZero)
5815 Known.knownNot(fcNegZero);
5816
5817 // If src lands normally in dest, the result can never be subnormal.
5818 if (APFloat::isRepresentableAsNormalIn(*SrcSemantics, DstSemantics))
5819 Known.knownNot(fcSubnormal);
5820 break;
5821 }
5822 default:
5823 break;
5824 }
5825
5826 break;
5827 }
5828 case Instruction::FAdd:
5829 case Instruction::FSub: {
5830 KnownFPClass KnownLHS, KnownRHS;
5831 bool WantNegative =
5832 Op->getOpcode() == Instruction::FAdd &&
5833 (InterestedClasses & KnownFPClass::OrderedLessThanZeroMask) != fcNone;
5834 bool WantNaN = (InterestedClasses & fcNan) != fcNone;
5835 bool WantNegZero = (InterestedClasses & fcNegZero) != fcNone;
5836
5837 if (!WantNaN && !WantNegative && !WantNegZero)
5838 break;
5839
5840 FPClassTest InterestedSrcs = InterestedClasses;
5841 if (WantNegative)
5842 InterestedSrcs |= KnownFPClass::OrderedLessThanZeroMask;
5843 if (InterestedClasses & fcNan)
5844 InterestedSrcs |= fcInf;
5845 computeKnownFPClass(Op->getOperand(1), DemandedElts, InterestedSrcs,
5846 KnownRHS, Q, Depth + 1);
5847
5848 // Special case fadd x, x, which is the canonical form of fmul x, 2.
5849 bool Self = Op->getOperand(0) == Op->getOperand(1) &&
5850 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT,
5851 Depth + 1);
5852 if (Self)
5853 KnownLHS = KnownRHS;
5854
5855 if ((WantNaN && KnownRHS.isKnownNeverNaN()) ||
5856 (WantNegative && KnownRHS.cannotBeOrderedLessThanZero()) ||
5857 WantNegZero || Opc == Instruction::FSub) {
5858
5859 // FIXME: Context function should always be passed in separately
5860 const Function *F = cast<Instruction>(Op)->getFunction();
5861 const fltSemantics &FltSem =
5862 Op->getType()->getScalarType()->getFltSemantics();
5864 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5865
5866 if (Self && Opc == Instruction::FAdd) {
5867 Known = KnownFPClass::fadd_self(KnownLHS, Mode);
5868 } else {
5869 // RHS is canonically cheaper to compute. Skip inspecting the LHS if
5870 // there's no point.
5871
5872 if (!Self) {
5873 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedSrcs,
5874 KnownLHS, Q, Depth + 1);
5875 }
5876
5877 Known = Opc == Instruction::FAdd
5878 ? KnownFPClass::fadd(KnownLHS, KnownRHS, Mode)
5879 : KnownFPClass::fsub(KnownLHS, KnownRHS, Mode);
5880 }
5881 }
5882
5883 break;
5884 }
5885 case Instruction::FMul: {
5886 const Function *F = cast<Instruction>(Op)->getFunction();
5888 F ? F->getDenormalMode(
5889 Op->getType()->getScalarType()->getFltSemantics())
5891
5892 Value *LHS = Op->getOperand(0);
5893 Value *RHS = Op->getOperand(1);
5894 // X * X is always non-negative or a NaN.
5895 // FIXME: Should check isGuaranteedNotToBeUndef
5896 if (LHS == RHS) {
5897 KnownFPClass KnownSrc;
5898 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownSrc, Q,
5899 Depth + 1);
5900 Known = KnownFPClass::square(KnownSrc, Mode);
5901 break;
5902 }
5903
5904 KnownFPClass KnownLHS, KnownRHS;
5905
5906 const APFloat *CRHS;
5907 if (match(RHS, m_APFloat(CRHS))) {
5908 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5909 Depth + 1);
5910 Known = KnownFPClass::fmul(KnownLHS, *CRHS, Mode);
5911 } else {
5912 computeKnownFPClass(RHS, DemandedElts, fcAllFlags, KnownRHS, Q,
5913 Depth + 1);
5914 // TODO: Improve accuracy in unfused FMA pattern. We can prove an
5915 // additional not-nan if the addend is known-not negative infinity if the
5916 // multiply is known-not infinity.
5917
5918 computeKnownFPClass(LHS, DemandedElts, fcAllFlags, KnownLHS, Q,
5919 Depth + 1);
5920 Known = KnownFPClass::fmul(KnownLHS, KnownRHS, Mode);
5921 }
5922
5923 /// Propgate no-infs if the other source is known smaller than one, such
5924 /// that this cannot introduce overflow.
5925 if (KnownLHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(RHS))
5926 Known.knownNot(fcInf);
5927 else if (KnownRHS.isKnownNever(fcInf) && isAbsoluteValueULEOne(LHS))
5928 Known.knownNot(fcInf);
5929
5930 break;
5931 }
5932 case Instruction::FDiv: {
5933 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5934
5935 const Function *F = cast<Instruction>(Op)->getFunction();
5936 const fltSemantics &FltSem =
5937 Op->getType()->getScalarType()->getFltSemantics();
5939 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
5940
5941 if (Op->getOperand(0) == Op->getOperand(1) &&
5942 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5943 // X / X is always exactly 1.0 or a NaN.
5944 Known.KnownFPClasses = fcNan | fcPosNormal;
5945
5946 if (!WantNan)
5947 break;
5948
5949 KnownFPClass KnownSrc;
5950 computeKnownFPClass(Op->getOperand(0), DemandedElts,
5951 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
5952 Depth + 1);
5953
5954 Known = KnownFPClass::fdiv_self(KnownSrc, Mode);
5955 break;
5956 }
5957
5958 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
5959 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
5960 if (!WantNan && !WantNegative && !WantPositive)
5961 break;
5962
5963 KnownFPClass KnownLHS, KnownRHS;
5964 computeKnownFPClass(Op->getOperand(1), DemandedElts, fcAllFlags, KnownRHS,
5965 Q, Depth + 1);
5966
5967 bool KnowSomethingUseful =
5968 KnownRHS.isKnownNeverNaN() ||
5971
5972 if (KnowSomethingUseful)
5973 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
5974 Q, Depth + 1);
5975
5976 Known = KnownFPClass::fdiv(KnownLHS, KnownRHS, Mode);
5977 break;
5978 }
5979 case Instruction::FRem: {
5980 const bool WantNan = (InterestedClasses & fcNan) != fcNone;
5981
5982 Known.knownNot(fcInf);
5983
5984 const Function *F = cast<Instruction>(Op)->getFunction();
5986 F ? F->getDenormalMode(
5987 Op->getType()->getScalarType()->getFltSemantics())
5989
5990 if (Op->getOperand(0) == Op->getOperand(1) &&
5991 isGuaranteedNotToBeUndef(Op->getOperand(0), Q.AC, Q.CxtI, Q.DT)) {
5992 // X % X is always exactly [+-]0.0 or a NaN.
5993 Known.KnownFPClasses = fcNan | fcZero;
5994
5995 if (!WantNan)
5996 break;
5997
5998 KnownFPClass KnownSrc;
5999 computeKnownFPClass(Op->getOperand(0), DemandedElts,
6000 fcNan | fcInf | fcZero | fcSubnormal, KnownSrc, Q,
6001 Depth + 1);
6002
6003 Known = KnownFPClass::frem_self(KnownSrc, Mode);
6004 break;
6005 }
6006
6007 const bool WantNegative = (InterestedClasses & fcNegative) != fcNone;
6008 const bool WantPositive = (InterestedClasses & fcPositive) != fcNone;
6009 if (!WantNan && !WantNegative && !WantPositive)
6010 break;
6011
6012 KnownFPClass KnownLHS, KnownRHS;
6013 computeKnownFPClass(Op->getOperand(1), DemandedElts,
6014 fcNan | fcInf | fcZero | fcNegative, KnownRHS, Q,
6015 Depth + 1);
6016
6017 bool KnowSomethingUseful = KnownRHS.isKnownNeverNaN() ||
6018 KnownRHS.isKnownNever(fcNegative) ||
6019 KnownRHS.isKnownNever(fcPositive);
6020
6021 if (KnowSomethingUseful || WantPositive)
6022 computeKnownFPClass(Op->getOperand(0), DemandedElts, fcAllFlags, KnownLHS,
6023 Q, Depth + 1);
6024
6025 Known = KnownFPClass::frem(KnownLHS, KnownRHS, Mode);
6026
6027 break;
6028 }
6029 case Instruction::FPExt: {
6030 KnownFPClass KnownSrc;
6031 computeKnownFPClass(Op->getOperand(0), DemandedElts, InterestedClasses,
6032 KnownSrc, Q, Depth + 1);
6033
6034 const fltSemantics &DstTy =
6035 Op->getType()->getScalarType()->getFltSemantics();
6036 const fltSemantics &SrcTy =
6037 Op->getOperand(0)->getType()->getScalarType()->getFltSemantics();
6038
6039 Known = KnownFPClass::fpext(KnownSrc, DstTy, SrcTy);
6040 break;
6041 }
6042 case Instruction::FPTrunc: {
6043 computeKnownFPClassForFPTrunc(Op, DemandedElts, InterestedClasses, Known, Q,
6044 Depth);
6045 break;
6046 }
6047 case Instruction::SIToFP:
6048 case Instruction::UIToFP: {
6049 // Cannot produce nan
6050 Known.knownNot(fcNan);
6051
6052 // Integers cannot be subnormal
6053 Known.knownNot(fcSubnormal);
6054
6055 // sitofp and uitofp turn into +0.0 for zero.
6056 Known.knownNot(fcNegZero);
6057
6058 // UIToFP is always non-negative regardless of known bits.
6059 if (Op->getOpcode() == Instruction::UIToFP)
6060 Known.signBitMustBeZero();
6061
6062 // Only compute known bits if we can learn something useful from them.
6063 if (!(InterestedClasses & (fcPosZero | fcNormal | fcInf)))
6064 break;
6065
6066 KnownBits IntKnown =
6067 computeKnownBits(Op->getOperand(0), DemandedElts, Q, Depth + 1);
6068
6069 // If the integer is non-zero, the result cannot be +0.0
6070 if (IntKnown.isNonZero())
6071 Known.knownNot(fcPosZero);
6072
6073 if (Op->getOpcode() == Instruction::SIToFP) {
6074 // If the signed integer is known non-negative, the result is
6075 // non-negative. If the signed integer is known negative, the result is
6076 // negative.
6077 if (IntKnown.isNonNegative()) {
6078 Known.signBitMustBeZero();
6079 } else if (IntKnown.isNegative()) {
6080 Known.signBitMustBeOne();
6081 }
6082 }
6083
6084 // Guard kept for ilogb()
6085 if (InterestedClasses & fcInf) {
6086 // Get width of largest magnitude integer known.
6087 // This still works for a signed minimum value because the largest FP
6088 // value is scaled by some fraction close to 2.0 (1.0 + 0.xxxx).
6089 int IntSize = IntKnown.getBitWidth();
6090 if (Op->getOpcode() == Instruction::UIToFP)
6091 IntSize -= IntKnown.countMinLeadingZeros();
6092 else if (Op->getOpcode() == Instruction::SIToFP)
6093 IntSize -= IntKnown.countMinSignBits();
6094
6095 // If the exponent of the largest finite FP value can hold the largest
6096 // integer, the result of the cast must be finite.
6097 Type *FPTy = Op->getType()->getScalarType();
6098 if (ilogb(APFloat::getLargest(FPTy->getFltSemantics())) >= IntSize)
6099 Known.knownNot(fcInf);
6100 }
6101
6102 break;
6103 }
6104 case Instruction::ExtractElement: {
6105 // Look through extract element. If the index is non-constant or
6106 // out-of-range demand all elements, otherwise just the extracted element.
6107 const Value *Vec = Op->getOperand(0);
6108
6109 APInt DemandedVecElts;
6110 if (auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType())) {
6111 unsigned NumElts = VecTy->getNumElements();
6112 DemandedVecElts = APInt::getAllOnes(NumElts);
6113 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(1));
6114 if (CIdx && CIdx->getValue().ult(NumElts))
6115 DemandedVecElts = APInt::getOneBitSet(NumElts, CIdx->getZExtValue());
6116 } else {
6117 DemandedVecElts = APInt(1, 1);
6118 }
6119
6120 return computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known,
6121 Q, Depth + 1);
6122 }
6123 case Instruction::InsertElement: {
6124 if (isa<ScalableVectorType>(Op->getType()))
6125 return;
6126
6127 const Value *Vec = Op->getOperand(0);
6128 const Value *Elt = Op->getOperand(1);
6129 auto *CIdx = dyn_cast<ConstantInt>(Op->getOperand(2));
6130 unsigned NumElts = DemandedElts.getBitWidth();
6131 APInt DemandedVecElts = DemandedElts;
6132 bool NeedsElt = true;
6133 // If we know the index we are inserting to, clear it from Vec check.
6134 if (CIdx && CIdx->getValue().ult(NumElts)) {
6135 DemandedVecElts.clearBit(CIdx->getZExtValue());
6136 NeedsElt = DemandedElts[CIdx->getZExtValue()];
6137 }
6138
6139 // Do we demand the inserted element?
6140 if (NeedsElt) {
6141 computeKnownFPClass(Elt, Known, InterestedClasses, Q, Depth + 1);
6142 // If we don't know any bits, early out.
6143 if (Known.isUnknown())
6144 break;
6145 } else {
6146 Known.KnownFPClasses = fcNone;
6147 }
6148
6149 // Do we need anymore elements from Vec?
6150 if (!DemandedVecElts.isZero()) {
6151 KnownFPClass Known2;
6152 computeKnownFPClass(Vec, DemandedVecElts, InterestedClasses, Known2, Q,
6153 Depth + 1);
6154 Known |= Known2;
6155 }
6156
6157 break;
6158 }
6159 case Instruction::ShuffleVector: {
6160 // Handle vector splat idiom
6161 if (Value *Splat = getSplatValue(V)) {
6162 computeKnownFPClass(Splat, Known, InterestedClasses, Q, Depth + 1);
6163 break;
6164 }
6165
6166 // For undef elements, we don't know anything about the common state of
6167 // the shuffle result.
6168 APInt DemandedLHS, DemandedRHS;
6169 auto *Shuf = dyn_cast<ShuffleVectorInst>(Op);
6170 if (!Shuf || !getShuffleDemandedElts(Shuf, DemandedElts, DemandedLHS, DemandedRHS))
6171 return;
6172
6173 if (!!DemandedLHS) {
6174 const Value *LHS = Shuf->getOperand(0);
6175 computeKnownFPClass(LHS, DemandedLHS, InterestedClasses, Known, Q,
6176 Depth + 1);
6177
6178 // If we don't know any bits, early out.
6179 if (Known.isUnknown())
6180 break;
6181 } else {
6182 Known.KnownFPClasses = fcNone;
6183 }
6184
6185 if (!!DemandedRHS) {
6186 KnownFPClass Known2;
6187 const Value *RHS = Shuf->getOperand(1);
6188 computeKnownFPClass(RHS, DemandedRHS, InterestedClasses, Known2, Q,
6189 Depth + 1);
6190 Known |= Known2;
6191 }
6192
6193 break;
6194 }
6195 case Instruction::ExtractValue: {
6196 const ExtractValueInst *Extract = cast<ExtractValueInst>(Op);
6197 ArrayRef<unsigned> Indices = Extract->getIndices();
6198 const Value *Src = Extract->getAggregateOperand();
6199 if (isa<StructType>(Src->getType()) && Indices.size() == 1 &&
6200 Indices[0] == 0) {
6201 if (const auto *II = dyn_cast<IntrinsicInst>(Src)) {
6202 switch (II->getIntrinsicID()) {
6203 case Intrinsic::frexp: {
6204 Known.knownNot(fcSubnormal);
6205
6206 KnownFPClass KnownSrc;
6207 computeKnownFPClass(II->getArgOperand(0), DemandedElts,
6208 InterestedClasses, KnownSrc, Q, Depth + 1);
6209
6210 const Function *F = cast<Instruction>(Op)->getFunction();
6211 const fltSemantics &FltSem =
6212 Op->getType()->getScalarType()->getFltSemantics();
6213
6215 F ? F->getDenormalMode(FltSem) : DenormalMode::getDynamic();
6216 Known = KnownFPClass::frexp_mant(KnownSrc, Mode);
6217 return;
6218 }
6219 default:
6220 break;
6221 }
6222 }
6223 }
6224
6225 computeKnownFPClass(Src, DemandedElts, InterestedClasses, Known, Q,
6226 Depth + 1);
6227 break;
6228 }
6229 case Instruction::PHI: {
6230 const PHINode *P = cast<PHINode>(Op);
6231 // Unreachable blocks may have zero-operand PHI nodes.
6232 if (P->getNumIncomingValues() == 0)
6233 break;
6234
6235 // Otherwise take the unions of the known bit sets of the operands,
6236 // taking conservative care to avoid excessive recursion.
6237 const unsigned PhiRecursionLimit = MaxAnalysisRecursionDepth - 2;
6238
6239 if (Depth < PhiRecursionLimit) {
6240 // Skip if every incoming value references to ourself.
6241 if (isa_and_nonnull<UndefValue>(P->hasConstantValue()))
6242 break;
6243
6244 bool First = true;
6245
6246 for (const Use &U : P->operands()) {
6247 Value *IncValue;
6248 Instruction *CxtI;
6249 breakSelfRecursivePHI(&U, P, IncValue, CxtI);
6250 // Skip direct self references.
6251 if (IncValue == P)
6252 continue;
6253
6254 KnownFPClass KnownSrc;
6255 // Recurse, but cap the recursion to two levels, because we don't want
6256 // to waste time spinning around in loops. We need at least depth 2 to
6257 // detect known sign bits.
6258 computeKnownFPClass(IncValue, DemandedElts, InterestedClasses, KnownSrc,
6260 PhiRecursionLimit);
6261
6262 if (First) {
6263 Known = KnownSrc;
6264 First = false;
6265 } else {
6266 Known |= KnownSrc;
6267 }
6268
6269 if (Known.KnownFPClasses == fcAllFlags)
6270 break;
6271 }
6272 }
6273
6274 // Look for the case of a for loop which has a positive
6275 // initial value and is incremented by a squared value.
6276 // This will propagate sign information out of such loops.
6277 if (P->getNumIncomingValues() != 2 || Known.cannotBeOrderedLessThanZero())
6278 break;
6279 for (unsigned I = 0; I < 2; I++) {
6280 Value *RecurValue = P->getIncomingValue(1 - I);
6282 if (!II)
6283 continue;
6284 Value *R, *L, *Init;
6285 PHINode *PN;
6287 PN == P) {
6288 switch (II->getIntrinsicID()) {
6289 case Intrinsic::fma:
6290 case Intrinsic::fmuladd: {
6291 KnownFPClass KnownStart;
6292 computeKnownFPClass(Init, DemandedElts, InterestedClasses, KnownStart,
6293 Q, Depth + 1);
6294 if (KnownStart.cannotBeOrderedLessThanZero() && L == R &&
6295 isGuaranteedNotToBeUndef(L, Q.AC, Q.CxtI, Q.DT, Depth + 1))
6297 break;
6298 }
6299 }
6300 }
6301 }
6302 break;
6303 }
6304 case Instruction::BitCast: {
6305 const Value *Src;
6306 if (!match(Op, m_ElementWiseBitCast(m_Value(Src))) ||
6307 !Src->getType()->isIntOrIntVectorTy())
6308 break;
6309
6310 const Type *Ty = Op->getType();
6311
6312 Value *CastLHS, *CastRHS;
6313
6314 // Match bitcast(umax(bitcast(a), bitcast(b)))
6315 if (match(Src, m_c_MaxOrMin(m_BitCast(m_Value(CastLHS)),
6316 m_BitCast(m_Value(CastRHS)))) &&
6317 CastLHS->getType() == Ty && CastRHS->getType() == Ty) {
6318 KnownFPClass KnownLHS, KnownRHS;
6319 computeKnownFPClass(CastRHS, DemandedElts, InterestedClasses, KnownRHS, Q,
6320 Depth + 1);
6321 if (!KnownRHS.isUnknown()) {
6322 computeKnownFPClass(CastLHS, DemandedElts, InterestedClasses, KnownLHS,
6323 Q, Depth + 1);
6324 Known = KnownLHS | KnownRHS;
6325 }
6326
6327 return;
6328 }
6329
6330 const Type *EltTy = Ty->getScalarType();
6331 KnownBits Bits(EltTy->getPrimitiveSizeInBits());
6332 computeKnownBits(Src, DemandedElts, Bits, Q, Depth + 1);
6333
6335 break;
6336 }
6337 default:
6338 break;
6339 }
6340}
6341
6343 const APInt &DemandedElts,
6344 FPClassTest InterestedClasses,
6345 const SimplifyQuery &SQ,
6346 unsigned Depth) {
6347 KnownFPClass KnownClasses;
6348 ::computeKnownFPClass(V, DemandedElts, InterestedClasses, KnownClasses, SQ,
6349 Depth);
6350 return KnownClasses;
6351}
6352
6354 FPClassTest InterestedClasses,
6355 const SimplifyQuery &SQ,
6356 unsigned Depth) {
6358 ::computeKnownFPClass(V, Known, InterestedClasses, SQ, Depth);
6359 return Known;
6360}
6361
6363 const Value *V, const DataLayout &DL, FPClassTest InterestedClasses,
6364 const TargetLibraryInfo *TLI, AssumptionCache *AC, const Instruction *CxtI,
6365 const DominatorTree *DT, bool UseInstrInfo, unsigned Depth) {
6366 return computeKnownFPClass(V, InterestedClasses,
6367 SimplifyQuery(DL, TLI, DT, AC, CxtI, UseInstrInfo),
6368 Depth);
6369}
6370
6372llvm::computeKnownFPClass(const Value *V, const APInt &DemandedElts,
6373 FastMathFlags FMF, FPClassTest InterestedClasses,
6374 const SimplifyQuery &SQ, unsigned Depth) {
6375 if (FMF.noNaNs())
6376 InterestedClasses &= ~fcNan;
6377 if (FMF.noInfs())
6378 InterestedClasses &= ~fcInf;
6379
6380 KnownFPClass Result =
6381 computeKnownFPClass(V, DemandedElts, InterestedClasses, SQ, Depth);
6382
6383 if (FMF.noNaNs())
6384 Result.KnownFPClasses &= ~fcNan;
6385 if (FMF.noInfs())
6386 Result.KnownFPClasses &= ~fcInf;
6387 return Result;
6388}
6389
6391 FPClassTest InterestedClasses,
6392 const SimplifyQuery &SQ,
6393 unsigned Depth) {
6394 auto *FVTy = dyn_cast<FixedVectorType>(V->getType());
6395 APInt DemandedElts =
6396 FVTy ? APInt::getAllOnes(FVTy->getNumElements()) : APInt(1, 1);
6397 return computeKnownFPClass(V, DemandedElts, FMF, InterestedClasses, SQ,
6398 Depth);
6399}
6400
6402 unsigned Depth) {
6404 return Known.isKnownNeverNegZero();
6405}
6406
6408 unsigned Depth) {
6411 return Known.cannotBeOrderedLessThanZero();
6412}
6413
6415 unsigned Depth) {
6417 return Known.isKnownNeverInfinity();
6418}
6419
6420/// Return true if the floating-point value can never contain a NaN or infinity.
6422 unsigned Depth) {
6424 return Known.isKnownNeverNaN() && Known.isKnownNeverInfinity();
6425}
6426
6427/// Return true if the floating-point scalar value is not a NaN or if the
6428/// floating-point vector value has no NaN elements. Return false if a value
6429/// could ever be NaN.
6431 unsigned Depth) {
6433 return Known.isKnownNeverNaN();
6434}
6435
6436/// Return false if we can prove that the specified FP value's sign bit is 0.
6437/// Return true if we can prove that the specified FP value's sign bit is 1.
6438/// Otherwise return std::nullopt.
6439std::optional<bool> llvm::computeKnownFPSignBit(const Value *V,
6440 const SimplifyQuery &SQ,
6441 unsigned Depth) {
6443 return Known.SignBit;
6444}
6445
6447 auto *User = cast<Instruction>(U.getUser());
6448 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6449 if (FPOp->hasNoSignedZeros())
6450 return true;
6451 }
6452
6453 switch (User->getOpcode()) {
6454 case Instruction::FPToSI:
6455 case Instruction::FPToUI:
6456 return true;
6457 case Instruction::FCmp:
6458 // fcmp treats both positive and negative zero as equal.
6459 return true;
6460 case Instruction::Call:
6461 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6462 switch (II->getIntrinsicID()) {
6463 case Intrinsic::fabs:
6464 return true;
6465 case Intrinsic::copysign:
6466 return U.getOperandNo() == 0;
6467 case Intrinsic::is_fpclass: {
6468 auto Test =
6469 static_cast<FPClassTest>(
6470 cast<ConstantInt>(II->getArgOperand(1))->getZExtValue()) &
6473 }
6474 default:
6475 return false;
6476 }
6477 }
6478 return false;
6479 default:
6480 return false;
6481 }
6482}
6483
6485 auto *User = cast<Instruction>(U.getUser());
6486 if (auto *FPOp = dyn_cast<FPMathOperator>(User)) {
6487 if (FPOp->hasNoNaNs())
6488 return true;
6489 }
6490
6491 switch (User->getOpcode()) {
6492 case Instruction::FPToSI:
6493 case Instruction::FPToUI:
6494 return true;
6495 // Proper FP math operations ignore the sign bit of NaN.
6496 case Instruction::FAdd:
6497 case Instruction::FSub:
6498 case Instruction::FMul:
6499 case Instruction::FDiv:
6500 case Instruction::FRem:
6501 case Instruction::FPTrunc:
6502 case Instruction::FPExt:
6503 case Instruction::FCmp:
6504 return true;
6505 // Bitwise FP operations should preserve the sign bit of NaN.
6506 case Instruction::FNeg:
6507 case Instruction::Select:
6508 case Instruction::PHI:
6509 return false;
6510 case Instruction::Ret:
6511 return User->getFunction()->getAttributes().getRetNoFPClass() &
6513 case Instruction::Call:
6514 case Instruction::Invoke: {
6515 if (auto *II = dyn_cast<IntrinsicInst>(User)) {
6516 switch (II->getIntrinsicID()) {
6517 case Intrinsic::fabs:
6518 return true;
6519 case Intrinsic::copysign:
6520 return U.getOperandNo() == 0;
6521 // Other proper FP math intrinsics ignore the sign bit of NaN.
6522 case Intrinsic::maxnum:
6523 case Intrinsic::minnum:
6524 case Intrinsic::maximum:
6525 case Intrinsic::minimum:
6526 case Intrinsic::maximumnum:
6527 case Intrinsic::minimumnum:
6528 case Intrinsic::canonicalize:
6529 case Intrinsic::fma:
6530 case Intrinsic::fmuladd:
6531 case Intrinsic::sqrt:
6532 case Intrinsic::pow:
6533 case Intrinsic::powi:
6534 case Intrinsic::fptoui_sat:
6535 case Intrinsic::fptosi_sat:
6536 case Intrinsic::is_fpclass:
6537 return true;
6538 default:
6539 return false;
6540 }
6541 }
6542
6543 FPClassTest NoFPClass =
6544 cast<CallBase>(User)->getParamNoFPClass(U.getOperandNo());
6545 return NoFPClass & FPClassTest::fcNan;
6546 }
6547 default:
6548 return false;
6549 }
6550}
6551
6553 FastMathFlags FMF) {
6554 if (isa<PoisonValue>(V))
6555 return true;
6556 if (isa<UndefValue>(V))
6557 return false;
6558
6559 if (match(V, m_CheckedFp([](const APFloat &Val) { return Val.isInteger(); })))
6560 return true;
6561
6563 if (!I)
6564 return false;
6565
6566 switch (I->getOpcode()) {
6567 case Instruction::SIToFP:
6568 case Instruction::UIToFP:
6569 // TODO: Could check nofpclass(inf) on incoming argument
6570 if (FMF.noInfs())
6571 return true;
6572
6573 // Need to check int size cannot produce infinity, which computeKnownFPClass
6574 // knows how to do already.
6575 return isKnownNeverInfinity(I, SQ);
6576 case Instruction::Call: {
6577 const CallInst *CI = cast<CallInst>(I);
6578 switch (CI->getIntrinsicID()) {
6579 case Intrinsic::trunc:
6580 case Intrinsic::floor:
6581 case Intrinsic::ceil:
6582 case Intrinsic::rint:
6583 case Intrinsic::nearbyint:
6584 case Intrinsic::round:
6585 case Intrinsic::roundeven:
6586 return (FMF.noInfs() && FMF.noNaNs()) || isKnownNeverInfOrNaN(I, SQ);
6587 default:
6588 break;
6589 }
6590
6591 break;
6592 }
6593 default:
6594 break;
6595 }
6596
6597 return false;
6598}
6599
6601
6602 // All byte-wide stores are splatable, even of arbitrary variables.
6603 if (V->getType()->isIntegerTy(8))
6604 return V;
6605
6606 LLVMContext &Ctx = V->getContext();
6607
6608 // Undef don't care.
6609 auto *UndefInt8 = UndefValue::get(Type::getInt8Ty(Ctx));
6610 if (isa<UndefValue>(V))
6611 return UndefInt8;
6612
6613 // Return poison for zero-sized type.
6614 if (DL.getTypeStoreSize(V->getType()).isZero())
6615 return PoisonValue::get(Type::getInt8Ty(Ctx));
6616
6618 if (!C) {
6619 // Conceptually, we could handle things like:
6620 // %a = zext i8 %X to i16
6621 // %b = shl i16 %a, 8
6622 // %c = or i16 %a, %b
6623 // but until there is an example that actually needs this, it doesn't seem
6624 // worth worrying about.
6625 return nullptr;
6626 }
6627
6628 // Handle 'null' ConstantArrayZero etc.
6629 if (C->isNullValue())
6631
6632 // Constant floating-point values can be handled as integer values if the
6633 // corresponding integer value is "byteable". An important case is 0.0.
6634 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
6635 Type *ScalarTy = CFP->getType()->getScalarType();
6636 if (ScalarTy->isHalfTy() || ScalarTy->isFloatTy() || ScalarTy->isDoubleTy())
6637 return isBytewiseValue(
6638 ConstantInt::get(Ctx, CFP->getValue().bitcastToAPInt()), DL);
6639
6640 // Don't handle long double formats, which have strange constraints.
6641 return nullptr;
6642 }
6643
6644 // We can handle constant integers that are multiple of 8 bits.
6645 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
6646 if (CI->getBitWidth() % 8 == 0) {
6647 if (!CI->getValue().isSplat(8))
6648 return nullptr;
6649 return ConstantInt::get(Ctx, CI->getValue().trunc(8));
6650 }
6651 }
6652
6653 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
6654 if (CE->getOpcode() == Instruction::IntToPtr) {
6655 if (auto *PtrTy = dyn_cast<PointerType>(CE->getType())) {
6656 unsigned BitWidth = DL.getPointerSizeInBits(PtrTy->getAddressSpace());
6658 CE->getOperand(0), Type::getIntNTy(Ctx, BitWidth), false, DL))
6659 return isBytewiseValue(Op, DL);
6660 }
6661 }
6662 }
6663
6664 auto Merge = [&](Value *LHS, Value *RHS) -> Value * {
6665 if (LHS == RHS)
6666 return LHS;
6667 if (!LHS || !RHS)
6668 return nullptr;
6669 if (LHS == UndefInt8)
6670 return RHS;
6671 if (RHS == UndefInt8)
6672 return LHS;
6673 return nullptr;
6674 };
6675
6677 Value *Val = UndefInt8;
6678 for (uint64_t I = 0, E = CA->getNumElements(); I != E; ++I)
6679 if (!(Val = Merge(Val, isBytewiseValue(CA->getElementAsConstant(I), DL))))
6680 return nullptr;
6681 return Val;
6682 }
6683
6685 Value *Val = UndefInt8;
6686 for (Value *Op : C->operands())
6687 if (!(Val = Merge(Val, isBytewiseValue(Op, DL))))
6688 return nullptr;
6689 return Val;
6690 }
6691
6692 // Don't try to handle the handful of other constants.
6693 return nullptr;
6694}
6695
6696// This is the recursive version of BuildSubAggregate. It takes a few different
6697// arguments. Idxs is the index within the nested struct From that we are
6698// looking at now (which is of type IndexedType). IdxSkip is the number of
6699// indices from Idxs that should be left out when inserting into the resulting
6700// struct. To is the result struct built so far, new insertvalue instructions
6701// build on that.
6702static Value *BuildSubAggregate(Value *From, Value *To, Type *IndexedType,
6704 unsigned IdxSkip,
6705 BasicBlock::iterator InsertBefore) {
6706 StructType *STy = dyn_cast<StructType>(IndexedType);
6707 if (STy) {
6708 // Save the original To argument so we can modify it
6709 Value *OrigTo = To;
6710 // General case, the type indexed by Idxs is a struct
6711 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6712 // Process each struct element recursively
6713 Idxs.push_back(i);
6714 Value *PrevTo = To;
6715 To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip,
6716 InsertBefore);
6717 Idxs.pop_back();
6718 if (!To) {
6719 // Couldn't find any inserted value for this index? Cleanup
6720 while (PrevTo != OrigTo) {
6722 PrevTo = Del->getAggregateOperand();
6723 Del->eraseFromParent();
6724 }
6725 // Stop processing elements
6726 break;
6727 }
6728 }
6729 // If we successfully found a value for each of our subaggregates
6730 if (To)
6731 return To;
6732 }
6733 // Base case, the type indexed by SourceIdxs is not a struct, or not all of
6734 // the struct's elements had a value that was inserted directly. In the latter
6735 // case, perhaps we can't determine each of the subelements individually, but
6736 // we might be able to find the complete struct somewhere.
6737
6738 // Find the value that is at that particular spot
6739 Value *V = FindInsertedValue(From, Idxs);
6740
6741 if (!V)
6742 return nullptr;
6743
6744 // Insert the value in the new (sub) aggregate
6745 return InsertValueInst::Create(To, V, ArrayRef(Idxs).slice(IdxSkip), "tmp",
6746 InsertBefore);
6747}
6748
6749// This helper takes a nested struct and extracts a part of it (which is again a
6750// struct) into a new value. For example, given the struct:
6751// { a, { b, { c, d }, e } }
6752// and the indices "1, 1" this returns
6753// { c, d }.
6754//
6755// It does this by inserting an insertvalue for each element in the resulting
6756// struct, as opposed to just inserting a single struct. This will only work if
6757// each of the elements of the substruct are known (ie, inserted into From by an
6758// insertvalue instruction somewhere).
6759//
6760// All inserted insertvalue instructions are inserted before InsertBefore
6762 BasicBlock::iterator InsertBefore) {
6763 Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(),
6764 idx_range);
6765 Value *To = PoisonValue::get(IndexedType);
6766 SmallVector<unsigned, 10> Idxs(idx_range);
6767 unsigned IdxSkip = Idxs.size();
6768
6769 return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
6770}
6771
6772/// Given an aggregate and a sequence of indices, see if the scalar value
6773/// indexed is already around as a register, for example if it was inserted
6774/// directly into the aggregate.
6775///
6776/// If InsertBefore is not null, this function will duplicate (modified)
6777/// insertvalues when a part of a nested struct is extracted.
6778Value *
6780 std::optional<BasicBlock::iterator> InsertBefore) {
6781 // Nothing to index? Just return V then (this is useful at the end of our
6782 // recursion).
6783 if (idx_range.empty())
6784 return V;
6785 // We have indices, so V should have an indexable type.
6786 assert((V->getType()->isStructTy() || V->getType()->isArrayTy()) &&
6787 "Not looking at a struct or array?");
6788 assert(ExtractValueInst::getIndexedType(V->getType(), idx_range) &&
6789 "Invalid indices for type?");
6790
6791 if (Constant *C = dyn_cast<Constant>(V)) {
6792 C = C->getAggregateElement(idx_range[0]);
6793 if (!C) return nullptr;
6794 return FindInsertedValue(C, idx_range.slice(1), InsertBefore);
6795 }
6796
6798 // Loop the indices for the insertvalue instruction in parallel with the
6799 // requested indices
6800 const unsigned *req_idx = idx_range.begin();
6801 for (const unsigned *i = I->idx_begin(), *e = I->idx_end();
6802 i != e; ++i, ++req_idx) {
6803 if (req_idx == idx_range.end()) {
6804 // We can't handle this without inserting insertvalues
6805 if (!InsertBefore)
6806 return nullptr;
6807
6808 // The requested index identifies a part of a nested aggregate. Handle
6809 // this specially. For example,
6810 // %A = insertvalue { i32, {i32, i32 } } undef, i32 10, 1, 0
6811 // %B = insertvalue { i32, {i32, i32 } } %A, i32 11, 1, 1
6812 // %C = extractvalue {i32, { i32, i32 } } %B, 1
6813 // This can be changed into
6814 // %A = insertvalue {i32, i32 } undef, i32 10, 0
6815 // %C = insertvalue {i32, i32 } %A, i32 11, 1
6816 // which allows the unused 0,0 element from the nested struct to be
6817 // removed.
6818 return BuildSubAggregate(V, ArrayRef(idx_range.begin(), req_idx),
6819 *InsertBefore);
6820 }
6821
6822 // This insert value inserts something else than what we are looking for.
6823 // See if the (aggregate) value inserted into has the value we are
6824 // looking for, then.
6825 if (*req_idx != *i)
6826 return FindInsertedValue(I->getAggregateOperand(), idx_range,
6827 InsertBefore);
6828 }
6829 // If we end up here, the indices of the insertvalue match with those
6830 // requested (though possibly only partially). Now we recursively look at
6831 // the inserted value, passing any remaining indices.
6832 return FindInsertedValue(I->getInsertedValueOperand(),
6833 ArrayRef(req_idx, idx_range.end()), InsertBefore);
6834 }
6835
6837 // If we're extracting a value from an aggregate that was extracted from
6838 // something else, we can extract from that something else directly instead.
6839 // However, we will need to chain I's indices with the requested indices.
6840
6841 // Calculate the number of indices required
6842 unsigned size = I->getNumIndices() + idx_range.size();
6843 // Allocate some space to put the new indices in
6845 Idxs.reserve(size);
6846 // Add indices from the extract value instruction
6847 Idxs.append(I->idx_begin(), I->idx_end());
6848
6849 // Add requested indices
6850 Idxs.append(idx_range.begin(), idx_range.end());
6851
6852 assert(Idxs.size() == size
6853 && "Number of indices added not correct?");
6854
6855 return FindInsertedValue(I->getAggregateOperand(), Idxs, InsertBefore);
6856 }
6857 // Otherwise, we don't know (such as, extracting from a function return value
6858 // or load instruction)
6859 return nullptr;
6860}
6861
6862// If V refers to an initialized global constant, set Slice either to
6863// its initializer if the size of its elements equals ElementSize, or,
6864// for ElementSize == 8, to its representation as an array of unsiged
6865// char. Return true on success.
6866// Offset is in the unit "nr of ElementSize sized elements".
6869 unsigned ElementSize, uint64_t Offset) {
6870 assert(V && "V should not be null.");
6871 assert((ElementSize % 8) == 0 &&
6872 "ElementSize expected to be a multiple of the size of a byte.");
6873 unsigned ElementSizeInBytes = ElementSize / 8;
6874
6875 // Drill down into the pointer expression V, ignoring any intervening
6876 // casts, and determine the identity of the object it references along
6877 // with the cumulative byte offset into it.
6878 const GlobalVariable *GV =
6880 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6881 // Fail if V is not based on constant global object.
6882 return false;
6883
6884 const DataLayout &DL = GV->getDataLayout();
6885 APInt Off(DL.getIndexTypeSizeInBits(V->getType()), 0);
6886
6887 if (GV != V->stripAndAccumulateConstantOffsets(DL, Off,
6888 /*AllowNonInbounds*/ true))
6889 // Fail if a constant offset could not be determined.
6890 return false;
6891
6892 uint64_t StartIdx = Off.getLimitedValue();
6893 if (StartIdx == UINT64_MAX)
6894 // Fail if the constant offset is excessive.
6895 return false;
6896
6897 // Off/StartIdx is in the unit of bytes. So we need to convert to number of
6898 // elements. Simply bail out if that isn't possible.
6899 if ((StartIdx % ElementSizeInBytes) != 0)
6900 return false;
6901
6902 Offset += StartIdx / ElementSizeInBytes;
6903 ConstantDataArray *Array = nullptr;
6904 ArrayType *ArrayTy = nullptr;
6905
6906 if (GV->getInitializer()->isNullValue()) {
6907 Type *GVTy = GV->getValueType();
6908 uint64_t SizeInBytes = DL.getTypeStoreSize(GVTy).getFixedValue();
6909 uint64_t Length = SizeInBytes / ElementSizeInBytes;
6910
6911 Slice.Array = nullptr;
6912 Slice.Offset = 0;
6913 // Return an empty Slice for undersized constants to let callers
6914 // transform even undefined library calls into simpler, well-defined
6915 // expressions. This is preferable to making the calls although it
6916 // prevents sanitizers from detecting such calls.
6917 Slice.Length = Length < Offset ? 0 : Length - Offset;
6918 return true;
6919 }
6920
6921 auto *Init = const_cast<Constant *>(GV->getInitializer());
6922 if (auto *ArrayInit = dyn_cast<ConstantDataArray>(Init)) {
6923 Type *InitElTy = ArrayInit->getElementType();
6924 if (InitElTy->isIntegerTy(ElementSize)) {
6925 // If Init is an initializer for an array of the expected type
6926 // and size, use it as is.
6927 Array = ArrayInit;
6928 ArrayTy = ArrayInit->getType();
6929 }
6930 }
6931
6932 if (!Array) {
6933 if (ElementSize != 8)
6934 // TODO: Handle conversions to larger integral types.
6935 return false;
6936
6937 // Otherwise extract the portion of the initializer starting
6938 // at Offset as an array of bytes, and reset Offset.
6940 if (!Init)
6941 return false;
6942
6943 Offset = 0;
6945 ArrayTy = dyn_cast<ArrayType>(Init->getType());
6946 }
6947
6948 uint64_t NumElts = ArrayTy->getArrayNumElements();
6949 if (Offset > NumElts)
6950 return false;
6951
6952 Slice.Array = Array;
6953 Slice.Offset = Offset;
6954 Slice.Length = NumElts - Offset;
6955 return true;
6956}
6957
6958/// Extract bytes from the initializer of the constant array V, which need
6959/// not be a nul-terminated string. On success, store the bytes in Str and
6960/// return true. When TrimAtNul is set, Str will contain only the bytes up
6961/// to but not including the first nul. Return false on failure.
6963 bool TrimAtNul) {
6965 if (!getConstantDataArrayInfo(V, Slice, 8))
6966 return false;
6967
6968 if (Slice.Array == nullptr) {
6969 if (TrimAtNul) {
6970 // Return a nul-terminated string even for an empty Slice. This is
6971 // safe because all existing SimplifyLibcalls callers require string
6972 // arguments and the behavior of the functions they fold is undefined
6973 // otherwise. Folding the calls this way is preferable to making
6974 // the undefined library calls, even though it prevents sanitizers
6975 // from reporting such calls.
6976 Str = StringRef();
6977 return true;
6978 }
6979 if (Slice.Length == 1) {
6980 Str = StringRef("", 1);
6981 return true;
6982 }
6983 // We cannot instantiate a StringRef as we do not have an appropriate string
6984 // of 0s at hand.
6985 return false;
6986 }
6987
6988 // Start out with the entire array in the StringRef.
6989 Str = Slice.Array->getAsString();
6990 // Skip over 'offset' bytes.
6991 Str = Str.substr(Slice.Offset);
6992
6993 if (TrimAtNul) {
6994 // Trim off the \0 and anything after it. If the array is not nul
6995 // terminated, we just return the whole end of string. The client may know
6996 // some other way that the string is length-bound.
6997 Str = Str.substr(0, Str.find('\0'));
6998 }
6999 return true;
7000}
7001
7002// These next two are very similar to the above, but also look through PHI
7003// nodes.
7004// TODO: See if we can integrate these two together.
7005
7006/// If we can compute the length of the string pointed to by
7007/// the specified pointer, return 'len+1'. If we can't, return 0.
7010 unsigned CharSize) {
7011 // Look through noop bitcast instructions.
7012 V = V->stripPointerCasts();
7013
7014 // If this is a PHI node, there are two cases: either we have already seen it
7015 // or we haven't.
7016 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
7017 if (!PHIs.insert(PN).second)
7018 return ~0ULL; // already in the set.
7019
7020 // If it was new, see if all the input strings are the same length.
7021 uint64_t LenSoFar = ~0ULL;
7022 for (Value *IncValue : PN->incoming_values()) {
7023 uint64_t Len = GetStringLengthH(IncValue, PHIs, CharSize);
7024 if (Len == 0) return 0; // Unknown length -> unknown.
7025
7026 if (Len == ~0ULL) continue;
7027
7028 if (Len != LenSoFar && LenSoFar != ~0ULL)
7029 return 0; // Disagree -> unknown.
7030 LenSoFar = Len;
7031 }
7032
7033 // Success, all agree.
7034 return LenSoFar;
7035 }
7036
7037 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
7038 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
7039 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs, CharSize);
7040 if (Len1 == 0) return 0;
7041 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs, CharSize);
7042 if (Len2 == 0) return 0;
7043 if (Len1 == ~0ULL) return Len2;
7044 if (Len2 == ~0ULL) return Len1;
7045 if (Len1 != Len2) return 0;
7046 return Len1;
7047 }
7048
7049 // Otherwise, see if we can read the string.
7051 if (!getConstantDataArrayInfo(V, Slice, CharSize))
7052 return 0;
7053
7054 if (Slice.Array == nullptr)
7055 // Zeroinitializer (including an empty one).
7056 return 1;
7057
7058 // Search for the first nul character. Return a conservative result even
7059 // when there is no nul. This is safe since otherwise the string function
7060 // being folded such as strlen is undefined, and can be preferable to
7061 // making the undefined library call.
7062 unsigned NullIndex = 0;
7063 for (unsigned E = Slice.Length; NullIndex < E; ++NullIndex) {
7064 if (Slice.Array->getElementAsInteger(Slice.Offset + NullIndex) == 0)
7065 break;
7066 }
7067
7068 return NullIndex + 1;
7069}
7070
7071/// If we can compute the length of the string pointed to by
7072/// the specified pointer, return 'len+1'. If we can't, return 0.
7073uint64_t llvm::GetStringLength(const Value *V, unsigned CharSize) {
7074 if (!V->getType()->isPointerTy())
7075 return 0;
7076
7078 uint64_t Len = GetStringLengthH(V, PHIs, CharSize);
7079 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
7080 // an empty string as a length.
7081 return Len == ~0ULL ? 1 : Len;
7082}
7083
7084const Value *
7086 bool MustPreserveOffset) {
7087 assert(Call &&
7088 "getArgumentAliasingToReturnedPointer only works on nonnull calls");
7089 if (const Value *RV = Call->getReturnedArgOperand())
7090 return RV;
7091 // This can be used only as a aliasing property.
7093 Call, MustPreserveOffset))
7094 return Call->getArgOperand(0);
7095 return nullptr;
7096}
7097
7099 const CallBase *Call, bool MustPreserveOffset) {
7100 switch (Call->getIntrinsicID()) {
7101 case Intrinsic::launder_invariant_group:
7102 case Intrinsic::strip_invariant_group:
7103 case Intrinsic::aarch64_irg:
7104 case Intrinsic::aarch64_tagp:
7105 // The amdgcn_make_buffer_rsrc function does not alter the address of the
7106 // input pointer (and thus preserves the byte offset, which is the property
7107 // the MustPreserveOffset flag selects). However, it will not necessarily
7108 // map ptr addrspace(N) null to ptr addrspace(8) null, aka the "null
7109 // descriptor", which has "all loads return 0, all stores are dropped"
7110 // semantics. Given the context of this intrinsic list, no one should be
7111 // relying on such a strict bit-exact null mapping (and, at time of
7112 // writing, they are not), but we document this fact out of an abundance
7113 // of caution.
7114 case Intrinsic::amdgcn_make_buffer_rsrc:
7115 return true;
7116 case Intrinsic::ptrmask:
7117 return !MustPreserveOffset;
7118 case Intrinsic::threadlocal_address:
7119 // The underlying variable changes with thread ID. The Thread ID may change
7120 // at coroutine suspend points.
7121 return !Call->getParent()->getParent()->isPresplitCoroutine();
7122 default:
7123 return false;
7124 }
7125}
7126
7127/// \p PN defines a loop-variant pointer to an object. Check if the
7128/// previous iteration of the loop was referring to the same object as \p PN.
7130 const LoopInfo *LI) {
7131 // Find the loop-defined value.
7132 Loop *L = LI->getLoopFor(PN->getParent());
7133 if (PN->getNumIncomingValues() != 2)
7134 return true;
7135
7136 // Find the value from previous iteration.
7137 auto *PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(0));
7138 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7139 PrevValue = dyn_cast<Instruction>(PN->getIncomingValue(1));
7140 if (!PrevValue || LI->getLoopFor(PrevValue->getParent()) != L)
7141 return true;
7142
7143 // If a new pointer is loaded in the loop, the pointer references a different
7144 // object in every iteration. E.g.:
7145 // for (i)
7146 // int *p = a[i];
7147 // ...
7148 if (auto *Load = dyn_cast<LoadInst>(PrevValue))
7149 if (!L->isLoopInvariant(Load->getPointerOperand()))
7150 return false;
7151 return true;
7152}
7153
7154const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
7155 for (unsigned Count = 0; MaxLookup == 0 || Count < MaxLookup; ++Count) {
7156 if (auto *GEP = dyn_cast<GEPOperator>(V)) {
7157 const Value *PtrOp = GEP->getPointerOperand();
7158 if (!PtrOp->getType()->isPointerTy()) // Only handle scalar pointer base.
7159 return V;
7160 V = PtrOp;
7161 } else if (Operator::getOpcode(V) == Instruction::BitCast ||
7162 Operator::getOpcode(V) == Instruction::AddrSpaceCast) {
7163 Value *NewV = cast<Operator>(V)->getOperand(0);
7164 if (!NewV->getType()->isPointerTy())
7165 return V;
7166 V = NewV;
7167 } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
7168 if (GA->isInterposable())
7169 return V;
7170 V = GA->getAliasee();
7171 } else {
7172 if (auto *PHI = dyn_cast<PHINode>(V)) {
7173 // Look through single-arg phi nodes created by LCSSA.
7174 if (PHI->getNumIncomingValues() == 1) {
7175 V = PHI->getIncomingValue(0);
7176 continue;
7177 }
7178 } else if (auto *Call = dyn_cast<CallBase>(V)) {
7179 // CaptureTracking can know about special capturing properties of some
7180 // intrinsics like launder.invariant.group, that can't be expressed with
7181 // the attributes, but have properties like returning aliasing pointer.
7182 // Because some analysis may assume that nocaptured pointer is not
7183 // returned from some special intrinsic (because function would have to
7184 // be marked with returns attribute), it is crucial to use this function
7185 // because it should be in sync with CaptureTracking. Not using it may
7186 // cause weird miscompilations where 2 aliasing pointers are assumed to
7187 // noalias.
7189 Call, /*MustPreserveOffset=*/false)) {
7190 V = RP;
7191 continue;
7192 }
7193 }
7194
7195 return V;
7196 }
7197 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
7198 }
7199 return V;
7200}
7201
7204 const LoopInfo *LI, unsigned MaxLookup) {
7207 Worklist.push_back(V);
7208 do {
7209 const Value *P = Worklist.pop_back_val();
7210 P = getUnderlyingObject(P, MaxLookup);
7211
7212 if (!Visited.insert(P).second)
7213 continue;
7214
7215 if (auto *SI = dyn_cast<SelectInst>(P)) {
7216 Worklist.push_back(SI->getTrueValue());
7217 Worklist.push_back(SI->getFalseValue());
7218 continue;
7219 }
7220
7221 if (auto *PN = dyn_cast<PHINode>(P)) {
7222 // If this PHI changes the underlying object in every iteration of the
7223 // loop, don't look through it. Consider:
7224 // int **A;
7225 // for (i) {
7226 // Prev = Curr; // Prev = PHI (Prev_0, Curr)
7227 // Curr = A[i];
7228 // *Prev, *Curr;
7229 //
7230 // Prev is tracking Curr one iteration behind so they refer to different
7231 // underlying objects.
7232 if (!LI || !LI->isLoopHeader(PN->getParent()) ||
7234 append_range(Worklist, PN->incoming_values());
7235 else
7236 Objects.push_back(P);
7237 continue;
7238 }
7239
7240 Objects.push_back(P);
7241 } while (!Worklist.empty());
7242}
7243
7245 const unsigned MaxVisited = 8;
7246
7249 Worklist.push_back(V);
7250 const Value *Object = nullptr;
7251 // Used as fallback if we can't find a common underlying object through
7252 // recursion.
7253 bool First = true;
7254 const Value *FirstObject = getUnderlyingObject(V);
7255 do {
7256 const Value *P = Worklist.pop_back_val();
7257 P = First ? FirstObject : getUnderlyingObject(P);
7258 First = false;
7259
7260 if (!Visited.insert(P).second)
7261 continue;
7262
7263 if (Visited.size() == MaxVisited)
7264 return FirstObject;
7265
7266 if (auto *SI = dyn_cast<SelectInst>(P)) {
7267 Worklist.push_back(SI->getTrueValue());
7268 Worklist.push_back(SI->getFalseValue());
7269 continue;
7270 }
7271
7272 if (auto *PN = dyn_cast<PHINode>(P)) {
7273 append_range(Worklist, PN->incoming_values());
7274 continue;
7275 }
7276
7277 if (!Object)
7278 Object = P;
7279 else if (Object != P)
7280 return FirstObject;
7281 } while (!Worklist.empty());
7282
7283 return Object ? Object : FirstObject;
7284}
7285
7286/// This is the function that does the work of looking through basic
7287/// ptrtoint+arithmetic+inttoptr sequences.
7288static const Value *getUnderlyingObjectFromInt(const Value *V) {
7289 do {
7290 if (const Operator *U = dyn_cast<Operator>(V)) {
7291 // If we find a ptrtoint, we can transfer control back to the
7292 // regular getUnderlyingObjectFromInt.
7293 if (U->getOpcode() == Instruction::PtrToInt)
7294 return U->getOperand(0);
7295 // If we find an add of a constant, a multiplied value, or a phi, it's
7296 // likely that the other operand will lead us to the base
7297 // object. We don't have to worry about the case where the
7298 // object address is somehow being computed by the multiply,
7299 // because our callers only care when the result is an
7300 // identifiable object.
7301 if (U->getOpcode() != Instruction::Add ||
7302 (!isa<ConstantInt>(U->getOperand(1)) &&
7303 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
7304 !isa<PHINode>(U->getOperand(1))))
7305 return V;
7306 V = U->getOperand(0);
7307 } else {
7308 return V;
7309 }
7310 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
7311 } while (true);
7312}
7313
7314/// This is a wrapper around getUnderlyingObjects and adds support for basic
7315/// ptrtoint+arithmetic+inttoptr sequences.
7316/// It returns false if unidentified object is found in getUnderlyingObjects.
7318 SmallVectorImpl<Value *> &Objects) {
7320 SmallVector<const Value *, 4> Working(1, V);
7321 do {
7322 V = Working.pop_back_val();
7323
7325 getUnderlyingObjects(V, Objs);
7326
7327 for (const Value *V : Objs) {
7328 if (!Visited.insert(V).second)
7329 continue;
7330 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
7331 const Value *O =
7332 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
7333 if (O->getType()->isPointerTy()) {
7334 Working.push_back(O);
7335 continue;
7336 }
7337 }
7338 // If getUnderlyingObjects fails to find an identifiable object,
7339 // getUnderlyingObjectsForCodeGen also fails for safety.
7340 if (!isIdentifiedObject(V)) {
7341 Objects.clear();
7342 return false;
7343 }
7344 Objects.push_back(const_cast<Value *>(V));
7345 }
7346 } while (!Working.empty());
7347 return true;
7348}
7349
7351 AllocaInst *Result = nullptr;
7353 SmallVector<Value *, 4> Worklist;
7354
7355 auto AddWork = [&](Value *V) {
7356 if (Visited.insert(V).second)
7357 Worklist.push_back(V);
7358 };
7359
7360 AddWork(V);
7361 do {
7362 V = Worklist.pop_back_val();
7363 assert(Visited.count(V));
7364
7365 if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
7366 if (Result && Result != AI)
7367 return nullptr;
7368 Result = AI;
7369 } else if (CastInst *CI = dyn_cast<CastInst>(V)) {
7370 AddWork(CI->getOperand(0));
7371 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
7372 for (Value *IncValue : PN->incoming_values())
7373 AddWork(IncValue);
7374 } else if (auto *SI = dyn_cast<SelectInst>(V)) {
7375 AddWork(SI->getTrueValue());
7376 AddWork(SI->getFalseValue());
7378 if (OffsetZero && !GEP->hasAllZeroIndices())
7379 return nullptr;
7380 AddWork(GEP->getPointerOperand());
7381 } else if (CallBase *CB = dyn_cast<CallBase>(V)) {
7382 Value *Returned = CB->getReturnedArgOperand();
7383 if (Returned)
7384 AddWork(Returned);
7385 else
7386 return nullptr;
7387 } else {
7388 return nullptr;
7389 }
7390 } while (!Worklist.empty());
7391
7392 return Result;
7393}
7394
7396 const Value *V, bool AllowLifetime, bool AllowDroppable) {
7397 for (const User *U : V->users()) {
7399 if (!II)
7400 return false;
7401
7402 if (AllowLifetime && II->isLifetimeStartOrEnd())
7403 continue;
7404
7405 if (AllowDroppable && II->isDroppable())
7406 continue;
7407
7408 return false;
7409 }
7410 return true;
7411}
7412
7415 V, /* AllowLifetime */ true, /* AllowDroppable */ false);
7416}
7419 V, /* AllowLifetime */ true, /* AllowDroppable */ true);
7420}
7421
7423 if (auto *II = dyn_cast<IntrinsicInst>(I))
7424 return isTriviallyVectorizable(II->getIntrinsicID());
7425 auto *Shuffle = dyn_cast<ShuffleVectorInst>(I);
7426 return (!Shuffle || Shuffle->isSelect()) &&
7428}
7429
7431 const Instruction *Inst, const Instruction *CtxI, AssumptionCache *AC,
7432 const DominatorTree *DT, const TargetLibraryInfo *TLI, bool UseVariableInfo,
7433 bool IgnoreUBImplyingAttrs) {
7434 return isSafeToSpeculativelyExecuteWithOpcode(Inst->getOpcode(), Inst, CtxI,
7435 AC, DT, TLI, UseVariableInfo,
7436 IgnoreUBImplyingAttrs);
7437}
7438
7440 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI,
7441 AssumptionCache *AC, const DominatorTree *DT, const TargetLibraryInfo *TLI,
7442 bool UseVariableInfo, bool IgnoreUBImplyingAttrs) {
7443#ifndef NDEBUG
7444 if (Inst->getOpcode() != Opcode) {
7445 // Check that the operands are actually compatible with the Opcode override.
7446 auto hasEqualReturnAndLeadingOperandTypes =
7447 [](const Instruction *Inst, unsigned NumLeadingOperands) {
7448 if (Inst->getNumOperands() < NumLeadingOperands)
7449 return false;
7450 const Type *ExpectedType = Inst->getType();
7451 for (unsigned ItOp = 0; ItOp < NumLeadingOperands; ++ItOp)
7452 if (Inst->getOperand(ItOp)->getType() != ExpectedType)
7453 return false;
7454 return true;
7455 };
7457 hasEqualReturnAndLeadingOperandTypes(Inst, 2));
7458 assert(!Instruction::isUnaryOp(Opcode) ||
7459 hasEqualReturnAndLeadingOperandTypes(Inst, 1));
7460 }
7461#endif
7462
7463 switch (Opcode) {
7464 default:
7465 return true;
7466 case Instruction::UDiv:
7467 case Instruction::URem: {
7468 // x / y is undefined if y == 0.
7469 const APInt *V;
7470 if (match(Inst->getOperand(1), m_APInt(V)))
7471 return *V != 0;
7472 return false;
7473 }
7474 case Instruction::SDiv:
7475 case Instruction::SRem: {
7476 // x / y is undefined if y == 0 or x == INT_MIN and y == -1
7477 const APInt *Numerator, *Denominator;
7478 if (!match(Inst->getOperand(1), m_APInt(Denominator)))
7479 return false;
7480 // We cannot hoist this division if the denominator is 0.
7481 if (*Denominator == 0)
7482 return false;
7483 // It's safe to hoist if the denominator is not 0 or -1.
7484 if (!Denominator->isAllOnes())
7485 return true;
7486 // At this point we know that the denominator is -1. It is safe to hoist as
7487 // long we know that the numerator is not INT_MIN.
7488 if (match(Inst->getOperand(0), m_APInt(Numerator)))
7489 return !Numerator->isMinSignedValue();
7490 // The numerator *might* be MinSignedValue.
7491 return false;
7492 }
7493 case Instruction::Load: {
7494 if (!UseVariableInfo)
7495 return false;
7496
7497 const LoadInst *LI = dyn_cast<LoadInst>(Inst);
7498 if (!LI)
7499 return false;
7500 if (mustSuppressSpeculation(*LI))
7501 return false;
7502 const DataLayout &DL = LI->getDataLayout();
7504 LI->getPointerOperand(), LI->getType(), LI->getAlign(),
7505 SimplifyQuery(DL, TLI, DT, AC, CtxI));
7506 }
7507 case Instruction::Call: {
7508 auto *CI = dyn_cast<const CallInst>(Inst);
7509 if (!CI)
7510 return false;
7511 const Function *Callee = CI->getCalledFunction();
7512
7513 // The called function could have undefined behavior or side-effects, even
7514 // if marked readnone nounwind.
7515 if (!Callee || !Callee->isSpeculatable())
7516 return false;
7517 // Since the operands may be changed after hoisting, undefined behavior may
7518 // be triggered by some UB-implying attributes.
7519 return IgnoreUBImplyingAttrs || !CI->hasUBImplyingAttrs();
7520 }
7521 case Instruction::VAArg:
7522 case Instruction::Alloca:
7523 case Instruction::Invoke:
7524 case Instruction::CallBr:
7525 case Instruction::PHI:
7526 case Instruction::Store:
7527 case Instruction::Ret:
7528 case Instruction::UncondBr:
7529 case Instruction::CondBr:
7530 case Instruction::IndirectBr:
7531 case Instruction::Switch:
7532 case Instruction::Unreachable:
7533 case Instruction::Fence:
7534 case Instruction::AtomicRMW:
7535 case Instruction::AtomicCmpXchg:
7536 case Instruction::LandingPad:
7537 case Instruction::Resume:
7538 case Instruction::CatchSwitch:
7539 case Instruction::CatchPad:
7540 case Instruction::CatchRet:
7541 case Instruction::CleanupPad:
7542 case Instruction::CleanupRet:
7543 return false; // Misc instructions which have effects
7544 }
7545}
7546
7548 if (I.mayReadOrWriteMemory())
7549 // Memory dependency possible
7550 return true;
7552 // Can't move above a maythrow call or infinite loop. Or if an
7553 // inalloca alloca, above a stacksave call.
7554 return true;
7556 // 1) Can't reorder two inf-loop calls, even if readonly
7557 // 2) Also can't reorder an inf-loop call below a instruction which isn't
7558 // safe to speculative execute. (Inverse of above)
7559 return true;
7560 return false;
7561}
7562
7563/// Convert ConstantRange OverflowResult into ValueTracking OverflowResult.
7577
7578/// Combine constant ranges from computeConstantRange() and computeKnownBits().
7581 bool ForSigned,
7582 const SimplifyQuery &SQ) {
7583 ConstantRange CR1 =
7584 ConstantRange::fromKnownBits(V.getKnownBits(SQ), ForSigned);
7585 ConstantRange CR2 = computeConstantRange(V, ForSigned, SQ);
7588 return CR1.intersectWith(CR2, RangeType);
7589}
7590
7592 const Value *RHS,
7593 const SimplifyQuery &SQ,
7594 bool IsNSW) {
7595 ConstantRange LHSRange =
7596 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7597 ConstantRange RHSRange =
7598 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7599
7600 // mul nsw of two non-negative numbers is also nuw.
7601 if (IsNSW && LHSRange.isAllNonNegative() && RHSRange.isAllNonNegative())
7603
7604 return mapOverflowResult(LHSRange.unsignedMulMayOverflow(RHSRange));
7605}
7606
7608 const Value *RHS,
7609 const SimplifyQuery &SQ) {
7610 // Multiplying n * m significant bits yields a result of n + m significant
7611 // bits. If the total number of significant bits does not exceed the
7612 // result bit width (minus 1), there is no overflow.
7613 // This means if we have enough leading sign bits in the operands
7614 // we can guarantee that the result does not overflow.
7615 // Ref: "Hacker's Delight" by Henry Warren
7616 unsigned BitWidth = LHS->getType()->getScalarSizeInBits();
7617
7618 // Note that underestimating the number of sign bits gives a more
7619 // conservative answer.
7620 unsigned SignBits =
7621 ::ComputeNumSignBits(LHS, SQ) + ::ComputeNumSignBits(RHS, SQ);
7622
7623 // First handle the easy case: if we have enough sign bits there's
7624 // definitely no overflow.
7625 if (SignBits > BitWidth + 1)
7627
7628 // There are two ambiguous cases where there can be no overflow:
7629 // SignBits == BitWidth + 1 and
7630 // SignBits == BitWidth
7631 // The second case is difficult to check, therefore we only handle the
7632 // first case.
7633 if (SignBits == BitWidth + 1) {
7634 // It overflows only when both arguments are negative and the true
7635 // product is exactly the minimum negative number.
7636 // E.g. mul i16 with 17 sign bits: 0xff00 * 0xff80 = 0x8000
7637 // For simplicity we just check if at least one side is not negative.
7638 KnownBits LHSKnown = computeKnownBits(LHS, SQ);
7639 KnownBits RHSKnown = computeKnownBits(RHS, SQ);
7640 if (LHSKnown.isNonNegative() || RHSKnown.isNonNegative())
7642 }
7644}
7645
7648 const WithCache<const Value *> &RHS,
7649 const SimplifyQuery &SQ) {
7650 ConstantRange LHSRange =
7651 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7652 ConstantRange RHSRange =
7653 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7654 return mapOverflowResult(LHSRange.unsignedAddMayOverflow(RHSRange));
7655}
7656
7657static OverflowResult
7660 const AddOperator *Add, const SimplifyQuery &SQ) {
7661 if (Add && Add->hasNoSignedWrap()) {
7663 }
7664
7665 // If LHS and RHS each have at least two sign bits, the addition will look
7666 // like
7667 //
7668 // XX..... +
7669 // YY.....
7670 //
7671 // If the carry into the most significant position is 0, X and Y can't both
7672 // be 1 and therefore the carry out of the addition is also 0.
7673 //
7674 // If the carry into the most significant position is 1, X and Y can't both
7675 // be 0 and therefore the carry out of the addition is also 1.
7676 //
7677 // Since the carry into the most significant position is always equal to
7678 // the carry out of the addition, there is no signed overflow.
7679 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7681
7682 ConstantRange LHSRange =
7683 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7684 ConstantRange RHSRange =
7685 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7686 OverflowResult OR =
7687 mapOverflowResult(LHSRange.signedAddMayOverflow(RHSRange));
7689 return OR;
7690
7691 // The remaining code needs Add to be available. Early returns if not so.
7692 if (!Add)
7694
7695 // If the sign of Add is the same as at least one of the operands, this add
7696 // CANNOT overflow. If this can be determined from the known bits of the
7697 // operands the above signedAddMayOverflow() check will have already done so.
7698 // The only other way to improve on the known bits is from an assumption, so
7699 // call computeKnownBitsFromContext() directly.
7700 bool LHSOrRHSKnownNonNegative =
7701 (LHSRange.isAllNonNegative() || RHSRange.isAllNonNegative());
7702 bool LHSOrRHSKnownNegative =
7703 (LHSRange.isAllNegative() || RHSRange.isAllNegative());
7704 if (LHSOrRHSKnownNonNegative || LHSOrRHSKnownNegative) {
7705 KnownBits AddKnown(LHSRange.getBitWidth());
7706 computeKnownBitsFromContext(Add, AddKnown, SQ);
7707 if ((AddKnown.isNonNegative() && LHSOrRHSKnownNonNegative) ||
7708 (AddKnown.isNegative() && LHSOrRHSKnownNegative))
7710 }
7711
7713}
7714
7716 const Value *RHS,
7717 const SimplifyQuery &SQ) {
7718 // X - (X % ?)
7719 // The remainder of a value can't have greater magnitude than itself,
7720 // so the subtraction can't overflow.
7721
7722 // X - (X -nuw ?)
7723 // In the minimal case, this would simplify to "?", so there's no subtract
7724 // at all. But if this analysis is used to peek through casts, for example,
7725 // then determining no-overflow may allow other transforms.
7726
7727 // TODO: There are other patterns like this.
7728 // See simplifyICmpWithBinOpOnLHS() for candidates.
7729 if (match(RHS, m_URem(m_Specific(LHS), m_Value())) ||
7730 match(RHS, m_NUWSub(m_Specific(LHS), m_Value())))
7731 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7733
7734 if (auto C = isImpliedByDomCondition(CmpInst::ICMP_UGE, LHS, RHS, SQ.CxtI,
7735 SQ.DL)) {
7736 if (*C)
7739 }
7740
7741 ConstantRange LHSRange =
7742 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/false, SQ);
7743 ConstantRange RHSRange =
7744 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/false, SQ);
7745 return mapOverflowResult(LHSRange.unsignedSubMayOverflow(RHSRange));
7746}
7747
7749 const Value *RHS,
7750 const SimplifyQuery &SQ) {
7751 // X - (X % ?)
7752 // The remainder of a value can't have greater magnitude than itself,
7753 // so the subtraction can't overflow.
7754
7755 // X - (X -nsw ?)
7756 // In the minimal case, this would simplify to "?", so there's no subtract
7757 // at all. But if this analysis is used to peek through casts, for example,
7758 // then determining no-overflow may allow other transforms.
7759 if (match(RHS, m_SRem(m_Specific(LHS), m_Value())) ||
7760 match(RHS, m_NSWSub(m_Specific(LHS), m_Value())))
7761 if (isGuaranteedNotToBeUndef(LHS, SQ.AC, SQ.CxtI, SQ.DT))
7763
7764 // If LHS and RHS each have at least two sign bits, the subtraction
7765 // cannot overflow.
7766 if (::ComputeNumSignBits(LHS, SQ) > 1 && ::ComputeNumSignBits(RHS, SQ) > 1)
7768
7769 ConstantRange LHSRange =
7770 computeConstantRangeIncludingKnownBits(LHS, /*ForSigned=*/true, SQ);
7771 ConstantRange RHSRange =
7772 computeConstantRangeIncludingKnownBits(RHS, /*ForSigned=*/true, SQ);
7773 return mapOverflowResult(LHSRange.signedSubMayOverflow(RHSRange));
7774}
7775
7777 const DominatorTree &DT) {
7778 SmallVector<const CondBrInst *, 2> GuardingBranches;
7780
7781 for (const User *U : WO->users()) {
7782 if (const auto *EVI = dyn_cast<ExtractValueInst>(U)) {
7783 assert(EVI->getNumIndices() == 1 && "Obvious from CI's type");
7784
7785 if (EVI->getIndices()[0] == 0)
7786 Results.push_back(EVI);
7787 else {
7788 assert(EVI->getIndices()[0] == 1 && "Obvious from CI's type");
7789
7790 for (const auto *U : EVI->users())
7791 if (const auto *B = dyn_cast<CondBrInst>(U))
7792 GuardingBranches.push_back(B);
7793 }
7794 } else {
7795 // We are using the aggregate directly in a way we don't want to analyze
7796 // here (storing it to a global, say).
7797 return false;
7798 }
7799 }
7800
7801 auto AllUsesGuardedByBranch = [&](const CondBrInst *BI) {
7802 BasicBlockEdge NoWrapEdge(BI->getParent(), BI->getSuccessor(1));
7803
7804 // Check if all users of the add are provably no-wrap.
7805 for (const auto *Result : Results) {
7806 // If the extractvalue itself is not executed on overflow, the we don't
7807 // need to check each use separately, since domination is transitive.
7808 if (DT.dominates(NoWrapEdge, Result->getParent()))
7809 continue;
7810
7811 for (const auto &RU : Result->uses())
7812 if (!DT.dominates(NoWrapEdge, RU))
7813 return false;
7814 }
7815
7816 return true;
7817 };
7818
7819 return llvm::any_of(GuardingBranches, AllUsesGuardedByBranch);
7820}
7821
7822/// Shifts return poison if shiftwidth is larger than the bitwidth.
7823static bool shiftAmountKnownInRange(const Value *ShiftAmount) {
7824 auto *C = dyn_cast<Constant>(ShiftAmount);
7825 if (!C)
7826 return false;
7827
7828 // Shifts return poison if shiftwidth is larger than the bitwidth.
7830 if (auto *FVTy = dyn_cast<FixedVectorType>(C->getType())) {
7831 unsigned NumElts = FVTy->getNumElements();
7832 for (unsigned i = 0; i < NumElts; ++i)
7833 ShiftAmounts.push_back(C->getAggregateElement(i));
7834 } else if (isa<ScalableVectorType>(C->getType()))
7835 return false; // Can't tell, just return false to be safe
7836 else
7837 ShiftAmounts.push_back(C);
7838
7839 bool Safe = llvm::all_of(ShiftAmounts, [](const Constant *C) {
7840 auto *CI = dyn_cast_or_null<ConstantInt>(C);
7841 return CI && CI->getValue().ult(C->getType()->getIntegerBitWidth());
7842 });
7843
7844 return Safe;
7845}
7846
7848 bool ConsiderFlagsAndMetadata) {
7849
7850 if (ConsiderFlagsAndMetadata && includesPoison(Kind) &&
7851 Op->hasPoisonGeneratingAnnotations())
7852 return true;
7853
7854 unsigned Opcode = Op->getOpcode();
7855
7856 // Check whether opcode is a poison/undef-generating operation
7857 switch (Opcode) {
7858 case Instruction::Shl:
7859 case Instruction::AShr:
7860 case Instruction::LShr:
7861 return includesPoison(Kind) && !shiftAmountKnownInRange(Op->getOperand(1));
7862 case Instruction::FPToSI:
7863 case Instruction::FPToUI:
7864 // fptosi/ui yields poison if the resulting value does not fit in the
7865 // destination type.
7866 return true;
7867 case Instruction::Call:
7868 if (auto *II = dyn_cast<IntrinsicInst>(Op)) {
7869 switch (II->getIntrinsicID()) {
7870 // NOTE: Use IntrNoCreateUndefOrPoison when possible.
7871 case Intrinsic::ctlz:
7872 case Intrinsic::cttz:
7873 case Intrinsic::abs:
7874 // We're not considering flags so it is safe to just return false.
7875 return false;
7876 case Intrinsic::sshl_sat:
7877 case Intrinsic::ushl_sat:
7878 if (!includesPoison(Kind) ||
7879 shiftAmountKnownInRange(II->getArgOperand(1)))
7880 return false;
7881 break;
7882 }
7883 }
7884 [[fallthrough]];
7885 case Instruction::CallBr:
7886 case Instruction::Invoke: {
7887 const auto *CB = cast<CallBase>(Op);
7888 return !CB->hasRetAttr(Attribute::NoUndef) &&
7889 !CB->hasFnAttr(Attribute::NoCreateUndefOrPoison);
7890 }
7891 case Instruction::InsertElement:
7892 case Instruction::ExtractElement: {
7893 // If index exceeds the length of the vector, it returns poison
7894 auto *VTy = cast<VectorType>(Op->getOperand(0)->getType());
7895 unsigned IdxOp = Op->getOpcode() == Instruction::InsertElement ? 2 : 1;
7896 auto *Idx = dyn_cast<ConstantInt>(Op->getOperand(IdxOp));
7897 if (includesPoison(Kind))
7898 return !Idx ||
7899 Idx->getValue().uge(VTy->getElementCount().getKnownMinValue());
7900 return false;
7901 }
7902 case Instruction::ShuffleVector: {
7904 ? cast<ConstantExpr>(Op)->getShuffleMask()
7905 : cast<ShuffleVectorInst>(Op)->getShuffleMask();
7906 return includesPoison(Kind) && is_contained(Mask, PoisonMaskElem);
7907 }
7908 case Instruction::FNeg:
7909 case Instruction::PHI:
7910 case Instruction::Select:
7911 case Instruction::ExtractValue:
7912 case Instruction::InsertValue:
7913 case Instruction::Freeze:
7914 case Instruction::ICmp:
7915 case Instruction::FCmp:
7916 case Instruction::GetElementPtr:
7917 return false;
7918 case Instruction::AddrSpaceCast:
7919 return true;
7920 default: {
7921 const auto *CE = dyn_cast<ConstantExpr>(Op);
7922 if (isa<CastInst>(Op) || (CE && CE->isCast()))
7923 return false;
7924 else if (Instruction::isBinaryOp(Opcode))
7925 return false;
7926 // Be conservative and return true.
7927 return true;
7928 }
7929 }
7930}
7931
7933 bool ConsiderFlagsAndMetadata) {
7934 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::UndefOrPoison,
7935 ConsiderFlagsAndMetadata);
7936}
7937
7938bool llvm::canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata) {
7939 return ::canCreateUndefOrPoison(Op, UndefPoisonKind::PoisonOnly,
7940 ConsiderFlagsAndMetadata);
7941}
7942
7943static bool directlyImpliesPoison(const Value *ValAssumedPoison, const Value *V,
7944 unsigned Depth) {
7945 if (ValAssumedPoison == V)
7946 return true;
7947
7948 const unsigned MaxDepth = 2;
7949 if (Depth >= MaxDepth)
7950 return false;
7951
7952 if (const auto *I = dyn_cast<Instruction>(V)) {
7953 if (any_of(I->operands(), [=](const Use &Op) {
7954 return propagatesPoison(Op) &&
7955 directlyImpliesPoison(ValAssumedPoison, Op, Depth + 1);
7956 }))
7957 return true;
7958
7959 // V = extractvalue V0, idx
7960 // V2 = extractvalue V0, idx2
7961 // V0's elements are all poison or not. (e.g., add_with_overflow)
7962 const WithOverflowInst *II;
7964 (match(ValAssumedPoison, m_ExtractValue(m_Specific(II))) ||
7965 llvm::is_contained(II->args(), ValAssumedPoison)))
7966 return true;
7967 }
7968 return false;
7969}
7970
7971static bool impliesPoison(const Value *ValAssumedPoison, const Value *V,
7972 unsigned Depth) {
7973 if (isGuaranteedNotToBePoison(ValAssumedPoison))
7974 return true;
7975
7976 if (directlyImpliesPoison(ValAssumedPoison, V, /* Depth */ 0))
7977 return true;
7978
7979 const unsigned MaxDepth = 2;
7980 if (Depth >= MaxDepth)
7981 return false;
7982
7983 const auto *I = dyn_cast<Instruction>(ValAssumedPoison);
7984 if (I && !canCreatePoison(cast<Operator>(I))) {
7985 return all_of(I->operands(), [=](const Value *Op) {
7986 return impliesPoison(Op, V, Depth + 1);
7987 });
7988 }
7989 return false;
7990}
7991
7992bool llvm::impliesPoison(const Value *ValAssumedPoison, const Value *V) {
7993 return ::impliesPoison(ValAssumedPoison, V, /* Depth */ 0);
7994}
7995
7996static bool programUndefinedIfUndefOrPoison(const Value *V, bool PoisonOnly);
7997
7999 const Value *V, AssumptionCache *AC, const Instruction *CtxI,
8000 const DominatorTree *DT, unsigned Depth, UndefPoisonKind Kind) {
8002 return false;
8003
8004 if (isa<MetadataAsValue>(V))
8005 return false;
8006
8007 if (const auto *A = dyn_cast<Argument>(V)) {
8008 if (A->hasAttribute(Attribute::NoUndef) ||
8009 A->hasAttribute(Attribute::Dereferenceable) ||
8010 A->hasAttribute(Attribute::DereferenceableOrNull))
8011 return true;
8012 }
8013
8014 if (auto *C = dyn_cast<Constant>(V)) {
8015 if (isa<PoisonValue>(C))
8016 return !includesPoison(Kind);
8017
8018 if (isa<UndefValue>(C))
8019 return !includesUndef(Kind);
8020
8023 return true;
8024
8025 if (C->getType()->isVectorTy()) {
8026 if (isa<ConstantExpr>(C)) {
8027 // Scalable vectors can use a ConstantExpr to build a splat.
8028 if (Constant *SplatC = C->getSplatValue())
8029 if (isa<ConstantInt>(SplatC) || isa<ConstantFP>(SplatC))
8030 return true;
8031 } else {
8032 if (includesUndef(Kind) && C->containsUndefElement())
8033 return false;
8034 if (includesPoison(Kind) && C->containsPoisonElement())
8035 return false;
8036 return !C->containsConstantExpression();
8037 }
8038 }
8039 }
8040
8041 // Strip cast operations from a pointer value.
8042 // Note that stripPointerCastsSameRepresentation can strip off getelementptr
8043 // inbounds with zero offset. To guarantee that the result isn't poison, the
8044 // stripped pointer is checked as it has to be pointing into an allocated
8045 // object or be null `null` to ensure `inbounds` getelement pointers with a
8046 // zero offset could not produce poison.
8047 // It can strip off addrspacecast that do not change bit representation as
8048 // well. We believe that such addrspacecast is equivalent to no-op.
8049 auto *StrippedV = V->stripPointerCastsSameRepresentation();
8050 if (isa<AllocaInst>(StrippedV) || isa<GlobalVariable>(StrippedV) ||
8051 isa<Function>(StrippedV) || isa<ConstantPointerNull>(StrippedV))
8052 return true;
8053
8054 auto OpCheck = [&](const Value *V) {
8055 return isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth + 1, Kind);
8056 };
8057
8058 if (auto *Opr = dyn_cast<Operator>(V)) {
8059 // If the value is a freeze instruction, then it can never
8060 // be undef or poison.
8061 if (isa<FreezeInst>(V))
8062 return true;
8063
8064 if (const auto *CB = dyn_cast<CallBase>(V)) {
8065 if (CB->hasRetAttr(Attribute::NoUndef) ||
8066 CB->hasRetAttr(Attribute::Dereferenceable) ||
8067 CB->hasRetAttr(Attribute::DereferenceableOrNull))
8068 return true;
8069 }
8070
8071 if (!::canCreateUndefOrPoison(Opr, Kind,
8072 /*ConsiderFlagsAndMetadata=*/true)) {
8073 if (const auto *PN = dyn_cast<PHINode>(V)) {
8074 unsigned Num = PN->getNumIncomingValues();
8075 bool IsWellDefined = true;
8076 for (unsigned i = 0; i < Num; ++i) {
8077 if (PN == PN->getIncomingValue(i))
8078 continue;
8079 auto *TI = PN->getIncomingBlock(i)->getTerminator();
8080 if (!isGuaranteedNotToBeUndefOrPoison(PN->getIncomingValue(i), AC, TI,
8081 DT, Depth + 1, Kind)) {
8082 IsWellDefined = false;
8083 break;
8084 }
8085 }
8086 if (IsWellDefined)
8087 return true;
8088 } else if (auto *Splat = isa<ShuffleVectorInst>(Opr) ? getSplatValue(Opr)
8089 : nullptr) {
8090 // For splats we only need to check the value being splatted.
8091 if (OpCheck(Splat))
8092 return true;
8093 } else if (all_of(Opr->operands(), OpCheck))
8094 return true;
8095 }
8096 }
8097
8098 if (auto *I = dyn_cast<LoadInst>(V))
8099 if (I->hasMetadata(LLVMContext::MD_noundef) ||
8100 I->hasMetadata(LLVMContext::MD_dereferenceable) ||
8101 I->hasMetadata(LLVMContext::MD_dereferenceable_or_null))
8102 return true;
8103
8105 return true;
8106
8107 // CxtI may be null or a cloned instruction.
8108 if (!CtxI || !CtxI->getParent() || !DT)
8109 return false;
8110
8111 auto *DNode = DT->getNode(CtxI->getParent());
8112 if (!DNode)
8113 // Unreachable block
8114 return false;
8115
8116 // If V is used as a branch condition before reaching CtxI, V cannot be
8117 // undef or poison.
8118 // br V, BB1, BB2
8119 // BB1:
8120 // CtxI ; V cannot be undef or poison here
8121 auto *Dominator = DNode->getIDom();
8122 // This check is purely for compile time reasons: we can skip the IDom walk
8123 // if what we are checking for includes undef and the value is not an integer.
8124 if (!includesUndef(Kind) || V->getType()->isIntegerTy())
8125 while (Dominator) {
8126 auto *TI = Dominator->getBlock()->getTerminatorOrNull();
8127
8128 Value *Cond = nullptr;
8129 if (auto BI = dyn_cast_or_null<CondBrInst>(TI)) {
8130 Cond = BI->getCondition();
8131 } else if (auto SI = dyn_cast_or_null<SwitchInst>(TI)) {
8132 Cond = SI->getCondition();
8133 }
8134
8135 if (Cond) {
8136 if (Cond == V)
8137 return true;
8138 else if (!includesUndef(Kind) && isa<Operator>(Cond)) {
8139 // For poison, we can analyze further
8140 auto *Opr = cast<Operator>(Cond);
8141 if (any_of(Opr->operands(), [V](const Use &U) {
8142 return V == U && propagatesPoison(U);
8143 }))
8144 return true;
8145 }
8146 }
8147
8148 Dominator = Dominator->getIDom();
8149 }
8150
8151 if (AC && getKnowledgeValidInContext(V, {Attribute::NoUndef}, *AC, CtxI, DT))
8152 return true;
8153
8154 return false;
8155}
8156
8158 const Instruction *CtxI,
8159 const DominatorTree *DT,
8160 unsigned Depth) {
8161 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8163}
8164
8166 const Instruction *CtxI,
8167 const DominatorTree *DT, unsigned Depth) {
8168 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8170}
8171
8173 const Instruction *CtxI,
8174 const DominatorTree *DT, unsigned Depth) {
8175 return ::isGuaranteedNotToBeUndefOrPoison(V, AC, CtxI, DT, Depth,
8177}
8178
8179/// Return true if undefined behavior would provably be executed on the path to
8180/// OnPathTo if Root produced a posion result. Note that this doesn't say
8181/// anything about whether OnPathTo is actually executed or whether Root is
8182/// actually poison. This can be used to assess whether a new use of Root can
8183/// be added at a location which is control equivalent with OnPathTo (such as
8184/// immediately before it) without introducing UB which didn't previously
8185/// exist. Note that a false result conveys no information.
8187 Instruction *OnPathTo,
8188 DominatorTree *DT) {
8189 // Basic approach is to assume Root is poison, propagate poison forward
8190 // through all users we can easily track, and then check whether any of those
8191 // users are provable UB and must execute before out exiting block might
8192 // exit.
8193
8194 // The set of all recursive users we've visited (which are assumed to all be
8195 // poison because of said visit)
8198 Worklist.push_back(Root);
8199 while (!Worklist.empty()) {
8200 const Instruction *I = Worklist.pop_back_val();
8201
8202 // If we know this must trigger UB on a path leading our target.
8203 if (mustTriggerUB(I, KnownPoison) && DT->dominates(I, OnPathTo))
8204 return true;
8205
8206 // If we can't analyze propagation through this instruction, just skip it
8207 // and transitive users. Safe as false is a conservative result.
8208 if (I != Root && !any_of(I->operands(), [&KnownPoison](const Use &U) {
8209 return KnownPoison.contains(U) && propagatesPoison(U);
8210 }))
8211 continue;
8212
8213 if (KnownPoison.insert(I).second)
8214 for (const User *User : I->users())
8215 Worklist.push_back(cast<Instruction>(User));
8216 }
8217
8218 // Might be non-UB, or might have a path we couldn't prove must execute on
8219 // way to exiting bb.
8220 return false;
8221}
8222
8224 const SimplifyQuery &SQ) {
8225 return ::computeOverflowForSignedAdd(Add->getOperand(0), Add->getOperand(1),
8226 Add, SQ);
8227}
8228
8231 const WithCache<const Value *> &RHS,
8232 const SimplifyQuery &SQ) {
8233 return ::computeOverflowForSignedAdd(LHS, RHS, nullptr, SQ);
8234}
8235
8237 // Note: An atomic operation isn't guaranteed to return in a reasonable amount
8238 // of time because it's possible for another thread to interfere with it for an
8239 // arbitrary length of time, but programs aren't allowed to rely on that.
8240
8241 // If there is no successor, then execution can't transfer to it.
8242 if (isa<ReturnInst>(I))
8243 return false;
8245 return false;
8246
8247 // Note: Do not add new checks here; instead, change Instruction::mayThrow or
8248 // Instruction::willReturn.
8249 //
8250 // FIXME: Move this check into Instruction::willReturn.
8251 if (isa<CatchPadInst>(I)) {
8252 switch (classifyEHPersonality(I->getFunction()->getPersonalityFn())) {
8253 default:
8254 // A catchpad may invoke exception object constructors and such, which
8255 // in some languages can be arbitrary code, so be conservative by default.
8256 return false;
8258 // For CoreCLR, it just involves a type test.
8259 return true;
8260 }
8261 }
8262
8263 // An instruction that returns without throwing must transfer control flow
8264 // to a successor.
8265 return !I->mayThrow() && I->willReturn();
8266}
8267
8269 // TODO: This is slightly conservative for invoke instruction since exiting
8270 // via an exception *is* normal control for them.
8271 for (const Instruction &I : *BB)
8273 return false;
8274 return true;
8275}
8276
8283
8286 assert(ScanLimit && "scan limit must be non-zero");
8287 for (const Instruction &I : Range) {
8288 if (--ScanLimit == 0)
8289 return false;
8291 return false;
8292 }
8293 return true;
8294}
8295
8297 const Loop *L) {
8298 // The loop header is guaranteed to be executed for every iteration.
8299 //
8300 // FIXME: Relax this constraint to cover all basic blocks that are
8301 // guaranteed to be executed at every iteration.
8302 if (I->getParent() != L->getHeader()) return false;
8303
8304 for (const Instruction &LI : *L->getHeader()) {
8305 if (&LI == I) return true;
8306 if (!isGuaranteedToTransferExecutionToSuccessor(&LI)) return false;
8307 }
8308 llvm_unreachable("Instruction not contained in its own parent basic block.");
8309}
8310
8312 switch (IID) {
8313 // TODO: Add more intrinsics.
8314 case Intrinsic::sadd_with_overflow:
8315 case Intrinsic::ssub_with_overflow:
8316 case Intrinsic::smul_with_overflow:
8317 case Intrinsic::uadd_with_overflow:
8318 case Intrinsic::usub_with_overflow:
8319 case Intrinsic::umul_with_overflow:
8320 // If an input is a vector containing a poison element, the
8321 // two output vectors (calculated results, overflow bits)'
8322 // corresponding lanes are poison.
8323 return true;
8324 case Intrinsic::ctpop:
8325 case Intrinsic::ctlz:
8326 case Intrinsic::cttz:
8327 case Intrinsic::abs:
8328 case Intrinsic::smax:
8329 case Intrinsic::smin:
8330 case Intrinsic::umax:
8331 case Intrinsic::umin:
8332 case Intrinsic::scmp:
8333 case Intrinsic::is_fpclass:
8334 case Intrinsic::ptrmask:
8335 case Intrinsic::ucmp:
8336 case Intrinsic::bitreverse:
8337 case Intrinsic::bswap:
8338 case Intrinsic::sadd_sat:
8339 case Intrinsic::ssub_sat:
8340 case Intrinsic::sshl_sat:
8341 case Intrinsic::uadd_sat:
8342 case Intrinsic::usub_sat:
8343 case Intrinsic::ushl_sat:
8344 case Intrinsic::smul_fix:
8345 case Intrinsic::smul_fix_sat:
8346 case Intrinsic::umul_fix:
8347 case Intrinsic::umul_fix_sat:
8348 case Intrinsic::pow:
8349 case Intrinsic::powi:
8350 case Intrinsic::sin:
8351 case Intrinsic::sinh:
8352 case Intrinsic::cos:
8353 case Intrinsic::cosh:
8354 case Intrinsic::sincos:
8355 case Intrinsic::sincospi:
8356 case Intrinsic::tan:
8357 case Intrinsic::tanh:
8358 case Intrinsic::asin:
8359 case Intrinsic::acos:
8360 case Intrinsic::atan:
8361 case Intrinsic::atan2:
8362 case Intrinsic::canonicalize:
8363 case Intrinsic::sqrt:
8364 case Intrinsic::exp:
8365 case Intrinsic::exp2:
8366 case Intrinsic::exp10:
8367 case Intrinsic::log:
8368 case Intrinsic::log2:
8369 case Intrinsic::log10:
8370 case Intrinsic::modf:
8371 case Intrinsic::floor:
8372 case Intrinsic::ceil:
8373 case Intrinsic::trunc:
8374 case Intrinsic::rint:
8375 case Intrinsic::nearbyint:
8376 case Intrinsic::round:
8377 case Intrinsic::roundeven:
8378 case Intrinsic::lrint:
8379 case Intrinsic::llrint:
8380 case Intrinsic::fshl:
8381 case Intrinsic::fshr:
8382 case Intrinsic::frexp:
8383 case Intrinsic::get_active_lane_mask:
8384 return true;
8385 default:
8386 return false;
8387 }
8388}
8389
8390bool llvm::propagatesPoison(const Use &PoisonOp) {
8391 const Operator *I = cast<Operator>(PoisonOp.getUser());
8392 switch (I->getOpcode()) {
8393 case Instruction::Freeze:
8394 case Instruction::PHI:
8395 case Instruction::Invoke:
8396 return false;
8397 case Instruction::Select:
8398 return PoisonOp.getOperandNo() == 0;
8399 case Instruction::Call:
8400 if (auto *II = dyn_cast<IntrinsicInst>(I))
8401 return intrinsicPropagatesPoison(II->getIntrinsicID());
8402 return false;
8403 case Instruction::ICmp:
8404 case Instruction::FCmp:
8405 case Instruction::GetElementPtr:
8406 return true;
8407 default:
8409 return true;
8410
8411 // Be conservative and return false.
8412 return false;
8413 }
8414}
8415
8416/// Enumerates all operands of \p I that are guaranteed to not be undef or
8417/// poison. If the callback \p Handle returns true, stop processing and return
8418/// true. Otherwise, return false.
8419template <typename CallableT>
8421 const CallableT &Handle) {
8422 switch (I->getOpcode()) {
8423 case Instruction::Store:
8424 if (Handle(cast<StoreInst>(I)->getPointerOperand()))
8425 return true;
8426 break;
8427
8428 case Instruction::Load:
8429 if (Handle(cast<LoadInst>(I)->getPointerOperand()))
8430 return true;
8431 break;
8432
8433 // Since dereferenceable attribute imply noundef, atomic operations
8434 // also implicitly have noundef pointers too
8435 case Instruction::AtomicCmpXchg:
8437 return true;
8438 break;
8439
8440 case Instruction::AtomicRMW:
8441 if (Handle(cast<AtomicRMWInst>(I)->getPointerOperand()))
8442 return true;
8443 break;
8444
8445 case Instruction::Call:
8446 case Instruction::Invoke: {
8447 const CallBase *CB = cast<CallBase>(I);
8448 if (CB->isIndirectCall() && Handle(CB->getCalledOperand()))
8449 return true;
8450 for (unsigned i = 0; i < CB->arg_size(); ++i)
8451 if ((CB->paramHasAttr(i, Attribute::NoUndef) ||
8452 CB->paramHasAttr(i, Attribute::Dereferenceable) ||
8453 CB->paramHasAttr(i, Attribute::DereferenceableOrNull)) &&
8454 Handle(CB->getArgOperand(i)))
8455 return true;
8456 break;
8457 }
8458 case Instruction::Ret:
8459 if (I->getFunction()->hasRetAttribute(Attribute::NoUndef) &&
8460 Handle(I->getOperand(0)))
8461 return true;
8462 break;
8463 case Instruction::Switch:
8464 if (Handle(cast<SwitchInst>(I)->getCondition()))
8465 return true;
8466 break;
8467 case Instruction::CondBr:
8468 if (Handle(cast<CondBrInst>(I)->getCondition()))
8469 return true;
8470 break;
8471 default:
8472 break;
8473 }
8474
8475 return false;
8476}
8477
8478/// Enumerates all operands of \p I that are guaranteed to not be poison.
8479template <typename CallableT>
8481 const CallableT &Handle) {
8482 if (handleGuaranteedWellDefinedOps(I, Handle))
8483 return true;
8484 switch (I->getOpcode()) {
8485 // Divisors of these operations are allowed to be partially undef.
8486 case Instruction::UDiv:
8487 case Instruction::SDiv:
8488 case Instruction::URem:
8489 case Instruction::SRem:
8490 return Handle(I->getOperand(1));
8491 default:
8492 return false;
8493 }
8494}
8495
8497 const SmallPtrSetImpl<const Value *> &KnownPoison) {
8499 I, [&](const Value *V) { return KnownPoison.count(V); });
8500}
8501
8503 bool PoisonOnly) {
8504 // We currently only look for uses of values within the same basic
8505 // block, as that makes it easier to guarantee that the uses will be
8506 // executed given that Inst is executed.
8507 //
8508 // FIXME: Expand this to consider uses beyond the same basic block. To do
8509 // this, look out for the distinction between post-dominance and strong
8510 // post-dominance.
8511 const BasicBlock *BB = nullptr;
8513 if (const auto *Inst = dyn_cast<Instruction>(V)) {
8514 BB = Inst->getParent();
8515 Begin = Inst->getIterator();
8516 Begin++;
8517 } else if (const auto *Arg = dyn_cast<Argument>(V)) {
8518 if (Arg->getParent()->isDeclaration())
8519 return false;
8520 BB = &Arg->getParent()->getEntryBlock();
8521 Begin = BB->begin();
8522 } else {
8523 return false;
8524 }
8525
8526 // Limit number of instructions we look at, to avoid scanning through large
8527 // blocks. The current limit is chosen arbitrarily.
8528 unsigned ScanLimit = 32;
8529 BasicBlock::const_iterator End = BB->end();
8530
8531 if (!PoisonOnly) {
8532 // Since undef does not propagate eagerly, be conservative & just check
8533 // whether a value is directly passed to an instruction that must take
8534 // well-defined operands.
8535
8536 for (const auto &I : make_range(Begin, End)) {
8537 if (--ScanLimit == 0)
8538 break;
8539
8540 if (handleGuaranteedWellDefinedOps(&I, [V](const Value *WellDefinedOp) {
8541 return WellDefinedOp == V;
8542 }))
8543 return true;
8544
8546 break;
8547 }
8548 return false;
8549 }
8550
8551 // Set of instructions that we have proved will yield poison if Inst
8552 // does.
8553 SmallPtrSet<const Value *, 16> YieldsPoison;
8555
8556 YieldsPoison.insert(V);
8557 Visited.insert(BB);
8558
8559 while (true) {
8560 for (const auto &I : make_range(Begin, End)) {
8561 if (--ScanLimit == 0)
8562 return false;
8563 if (mustTriggerUB(&I, YieldsPoison))
8564 return true;
8566 return false;
8567
8568 // If an operand is poison and propagates it, mark I as yielding poison.
8569 for (const Use &Op : I.operands()) {
8570 if (YieldsPoison.count(Op) && propagatesPoison(Op)) {
8571 YieldsPoison.insert(&I);
8572 break;
8573 }
8574 }
8575
8576 // Special handling for select, which returns poison if its operand 0 is
8577 // poison (handled in the loop above) *or* if both its true/false operands
8578 // are poison (handled here).
8579 if (I.getOpcode() == Instruction::Select &&
8580 YieldsPoison.count(I.getOperand(1)) &&
8581 YieldsPoison.count(I.getOperand(2))) {
8582 YieldsPoison.insert(&I);
8583 }
8584 }
8585
8586 BB = BB->getSingleSuccessor();
8587 if (!BB || !Visited.insert(BB).second)
8588 break;
8589
8590 Begin = BB->getFirstNonPHIIt();
8591 End = BB->end();
8592 }
8593 return false;
8594}
8595
8597 return ::programUndefinedIfUndefOrPoison(Inst, false);
8598}
8599
8601 return ::programUndefinedIfUndefOrPoison(Inst, true);
8602}
8603
8604static bool isKnownNonNaN(const Value *V, FastMathFlags FMF) {
8605 if (FMF.noNaNs())
8606 return true;
8607
8608 if (auto *C = dyn_cast<ConstantFP>(V))
8609 return !C->isNaN();
8610
8611 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8612 if (!C->getElementType()->isFloatingPointTy())
8613 return false;
8614 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8615 if (C->getElementAsAPFloat(I).isNaN())
8616 return false;
8617 }
8618 return true;
8619 }
8620
8622 return true;
8623
8624 return false;
8625}
8626
8627static bool isKnownNonZero(const Value *V) {
8628 if (auto *C = dyn_cast<ConstantFP>(V))
8629 return !C->isZero();
8630
8631 if (auto *C = dyn_cast<ConstantDataVector>(V)) {
8632 if (!C->getElementType()->isFloatingPointTy())
8633 return false;
8634 for (unsigned I = 0, E = C->getNumElements(); I < E; ++I) {
8635 if (C->getElementAsAPFloat(I).isZero())
8636 return false;
8637 }
8638 return true;
8639 }
8640
8641 return false;
8642}
8643
8644/// Match clamp pattern for float types without care about NaNs or signed zeros.
8645/// Given non-min/max outer cmp/select from the clamp pattern this
8646/// function recognizes if it can be substitued by a "canonical" min/max
8647/// pattern.
8649 Value *CmpLHS, Value *CmpRHS,
8650 Value *TrueVal, Value *FalseVal,
8651 Value *&LHS, Value *&RHS) {
8652 // Try to match
8653 // X < C1 ? C1 : Min(X, C2) --> Max(C1, Min(X, C2))
8654 // X > C1 ? C1 : Max(X, C2) --> Min(C1, Max(X, C2))
8655 // and return description of the outer Max/Min.
8656
8657 // First, check if select has inverse order:
8658 if (CmpRHS == FalseVal) {
8659 std::swap(TrueVal, FalseVal);
8660 Pred = CmpInst::getInversePredicate(Pred);
8661 }
8662
8663 // Assume success now. If there's no match, callers should not use these anyway.
8664 LHS = TrueVal;
8665 RHS = FalseVal;
8666
8667 const APFloat *FC1;
8668 if (CmpRHS != TrueVal || !match(CmpRHS, m_APFloat(FC1)) || !FC1->isFinite())
8669 return {SPF_UNKNOWN, SPNB_NA, false};
8670
8671 const APFloat *FC2;
8672 switch (Pred) {
8673 case CmpInst::FCMP_OLT:
8674 case CmpInst::FCMP_OLE:
8675 case CmpInst::FCMP_ULT:
8676 case CmpInst::FCMP_ULE:
8677 if (match(FalseVal, m_OrdOrUnordFMin(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8678 *FC1 < *FC2)
8679 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8680 if (match(FalseVal, m_FMinNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8681 *FC1 < *FC2)
8682 return {SPF_FMAXNUM, SPNB_RETURNS_ANY, false};
8683 break;
8684 case CmpInst::FCMP_OGT:
8685 case CmpInst::FCMP_OGE:
8686 case CmpInst::FCMP_UGT:
8687 case CmpInst::FCMP_UGE:
8688 if (match(FalseVal, m_OrdOrUnordFMax(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8689 *FC1 > *FC2)
8690 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8691 if (match(FalseVal, m_FMaxNum(m_Specific(CmpLHS), m_APFloat(FC2))) &&
8692 *FC1 > *FC2)
8693 return {SPF_FMINNUM, SPNB_RETURNS_ANY, false};
8694 break;
8695 default:
8696 break;
8697 }
8698
8699 return {SPF_UNKNOWN, SPNB_NA, false};
8700}
8701
8702/// Recognize variations of:
8703/// CLAMP(v,l,h) ==> ((v) < (l) ? (l) : ((v) > (h) ? (h) : (v)))
8705 Value *CmpLHS, Value *CmpRHS,
8706 Value *TrueVal, Value *FalseVal) {
8707 // Swap the select operands and predicate to match the patterns below.
8708 if (CmpRHS != TrueVal) {
8709 Pred = ICmpInst::getSwappedPredicate(Pred);
8710 std::swap(TrueVal, FalseVal);
8711 }
8712 const APInt *C1;
8713 if (CmpRHS == TrueVal && match(CmpRHS, m_APInt(C1))) {
8714 const APInt *C2;
8715 // (X <s C1) ? C1 : SMIN(X, C2) ==> SMAX(SMIN(X, C2), C1)
8716 if (match(FalseVal, m_SMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8717 C1->slt(*C2) && Pred == CmpInst::ICMP_SLT)
8718 return {SPF_SMAX, SPNB_NA, false};
8719
8720 // (X >s C1) ? C1 : SMAX(X, C2) ==> SMIN(SMAX(X, C2), C1)
8721 if (match(FalseVal, m_SMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8722 C1->sgt(*C2) && Pred == CmpInst::ICMP_SGT)
8723 return {SPF_SMIN, SPNB_NA, false};
8724
8725 // (X <u C1) ? C1 : UMIN(X, C2) ==> UMAX(UMIN(X, C2), C1)
8726 if (match(FalseVal, m_UMin(m_Specific(CmpLHS), m_APInt(C2))) &&
8727 C1->ult(*C2) && Pred == CmpInst::ICMP_ULT)
8728 return {SPF_UMAX, SPNB_NA, false};
8729
8730 // (X >u C1) ? C1 : UMAX(X, C2) ==> UMIN(UMAX(X, C2), C1)
8731 if (match(FalseVal, m_UMax(m_Specific(CmpLHS), m_APInt(C2))) &&
8732 C1->ugt(*C2) && Pred == CmpInst::ICMP_UGT)
8733 return {SPF_UMIN, SPNB_NA, false};
8734 }
8735 return {SPF_UNKNOWN, SPNB_NA, false};
8736}
8737
8738/// Recognize variations of:
8739/// a < c ? min(a,b) : min(b,c) ==> min(min(a,b),min(b,c))
8741 Value *CmpLHS, Value *CmpRHS,
8742 Value *TVal, Value *FVal,
8743 unsigned Depth) {
8744 // TODO: Allow FP min/max with nnan/nsz.
8745 assert(CmpInst::isIntPredicate(Pred) && "Expected integer comparison");
8746
8747 Value *A = nullptr, *B = nullptr;
8748 SelectPatternResult L = matchSelectPattern(TVal, A, B, nullptr, Depth + 1);
8749 if (!SelectPatternResult::isMinOrMax(L.Flavor))
8750 return {SPF_UNKNOWN, SPNB_NA, false};
8751
8752 Value *C = nullptr, *D = nullptr;
8753 SelectPatternResult R = matchSelectPattern(FVal, C, D, nullptr, Depth + 1);
8754 if (L.Flavor != R.Flavor)
8755 return {SPF_UNKNOWN, SPNB_NA, false};
8756
8757 // We have something like: x Pred y ? min(a, b) : min(c, d).
8758 // Try to match the compare to the min/max operations of the select operands.
8759 // First, make sure we have the right compare predicate.
8760 switch (L.Flavor) {
8761 case SPF_SMIN:
8762 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE) {
8763 Pred = ICmpInst::getSwappedPredicate(Pred);
8764 std::swap(CmpLHS, CmpRHS);
8765 }
8766 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
8767 break;
8768 return {SPF_UNKNOWN, SPNB_NA, false};
8769 case SPF_SMAX:
8770 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
8771 Pred = ICmpInst::getSwappedPredicate(Pred);
8772 std::swap(CmpLHS, CmpRHS);
8773 }
8774 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
8775 break;
8776 return {SPF_UNKNOWN, SPNB_NA, false};
8777 case SPF_UMIN:
8778 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
8779 Pred = ICmpInst::getSwappedPredicate(Pred);
8780 std::swap(CmpLHS, CmpRHS);
8781 }
8782 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
8783 break;
8784 return {SPF_UNKNOWN, SPNB_NA, false};
8785 case SPF_UMAX:
8786 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
8787 Pred = ICmpInst::getSwappedPredicate(Pred);
8788 std::swap(CmpLHS, CmpRHS);
8789 }
8790 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
8791 break;
8792 return {SPF_UNKNOWN, SPNB_NA, false};
8793 default:
8794 return {SPF_UNKNOWN, SPNB_NA, false};
8795 }
8796
8797 // If there is a common operand in the already matched min/max and the other
8798 // min/max operands match the compare operands (either directly or inverted),
8799 // then this is min/max of the same flavor.
8800
8801 // a pred c ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8802 // ~c pred ~a ? m(a, b) : m(c, b) --> m(m(a, b), m(c, b))
8803 if (D == B) {
8804 if ((CmpLHS == A && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8805 match(A, m_Not(m_Specific(CmpRHS)))))
8806 return {L.Flavor, SPNB_NA, false};
8807 }
8808 // a pred d ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8809 // ~d pred ~a ? m(a, b) : m(b, d) --> m(m(a, b), m(b, d))
8810 if (C == B) {
8811 if ((CmpLHS == A && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8812 match(A, m_Not(m_Specific(CmpRHS)))))
8813 return {L.Flavor, SPNB_NA, false};
8814 }
8815 // b pred c ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8816 // ~c pred ~b ? m(a, b) : m(c, a) --> m(m(a, b), m(c, a))
8817 if (D == A) {
8818 if ((CmpLHS == B && CmpRHS == C) || (match(C, m_Not(m_Specific(CmpLHS))) &&
8819 match(B, m_Not(m_Specific(CmpRHS)))))
8820 return {L.Flavor, SPNB_NA, false};
8821 }
8822 // b pred d ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8823 // ~d pred ~b ? m(a, b) : m(a, d) --> m(m(a, b), m(a, d))
8824 if (C == A) {
8825 if ((CmpLHS == B && CmpRHS == D) || (match(D, m_Not(m_Specific(CmpLHS))) &&
8826 match(B, m_Not(m_Specific(CmpRHS)))))
8827 return {L.Flavor, SPNB_NA, false};
8828 }
8829
8830 return {SPF_UNKNOWN, SPNB_NA, false};
8831}
8832
8833/// If the input value is the result of a 'not' op, constant integer, or vector
8834/// splat of a constant integer, return the bitwise-not source value.
8835/// TODO: This could be extended to handle non-splat vector integer constants.
8837 Value *NotV;
8838 if (match(V, m_Not(m_Value(NotV))))
8839 return NotV;
8840
8841 const APInt *C;
8842 if (match(V, m_APInt(C)))
8843 return ConstantInt::get(V->getType(), ~(*C));
8844
8845 return nullptr;
8846}
8847
8848/// Match non-obvious integer minimum and maximum sequences.
8850 Value *CmpLHS, Value *CmpRHS,
8851 Value *TrueVal, Value *FalseVal,
8852 Value *&LHS, Value *&RHS,
8853 unsigned Depth) {
8854 // Assume success. If there's no match, callers should not use these anyway.
8855 LHS = TrueVal;
8856 RHS = FalseVal;
8857
8858 SelectPatternResult SPR = matchClamp(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal);
8860 return SPR;
8861
8862 SPR = matchMinMaxOfMinMax(Pred, CmpLHS, CmpRHS, TrueVal, FalseVal, Depth);
8864 return SPR;
8865
8866 // Look through 'not' ops to find disguised min/max.
8867 // (X > Y) ? ~X : ~Y ==> (~X < ~Y) ? ~X : ~Y ==> MIN(~X, ~Y)
8868 // (X < Y) ? ~X : ~Y ==> (~X > ~Y) ? ~X : ~Y ==> MAX(~X, ~Y)
8869 if (CmpLHS == getNotValue(TrueVal) && CmpRHS == getNotValue(FalseVal)) {
8870 switch (Pred) {
8871 case CmpInst::ICMP_SGT: return {SPF_SMIN, SPNB_NA, false};
8872 case CmpInst::ICMP_SLT: return {SPF_SMAX, SPNB_NA, false};
8873 case CmpInst::ICMP_UGT: return {SPF_UMIN, SPNB_NA, false};
8874 case CmpInst::ICMP_ULT: return {SPF_UMAX, SPNB_NA, false};
8875 default: break;
8876 }
8877 }
8878
8879 // (X > Y) ? ~Y : ~X ==> (~X < ~Y) ? ~Y : ~X ==> MAX(~Y, ~X)
8880 // (X < Y) ? ~Y : ~X ==> (~X > ~Y) ? ~Y : ~X ==> MIN(~Y, ~X)
8881 if (CmpLHS == getNotValue(FalseVal) && CmpRHS == getNotValue(TrueVal)) {
8882 switch (Pred) {
8883 case CmpInst::ICMP_SGT: return {SPF_SMAX, SPNB_NA, false};
8884 case CmpInst::ICMP_SLT: return {SPF_SMIN, SPNB_NA, false};
8885 case CmpInst::ICMP_UGT: return {SPF_UMAX, SPNB_NA, false};
8886 case CmpInst::ICMP_ULT: return {SPF_UMIN, SPNB_NA, false};
8887 default: break;
8888 }
8889 }
8890
8891 if (Pred != CmpInst::ICMP_SGT && Pred !=