From d6ab839dbb28ff80a639cddb7782cba3b80848c1 Mon Sep 17 00:00:00 2001 From: Egor Bogatov Date: Thu, 19 Nov 2026 22:42:11 +0100 Subject: [PATCH 1/3] Add knownbits opt --- THIRD-PARTY-NOTICES.TXT | 21 + src/coreclr/jit/CMakeLists.txt | 3 + src/coreclr/jit/assertionprop.cpp | 46 +- src/coreclr/jit/compiler.h | 3 +- src/coreclr/jit/knownbits.h | 1653 +++++++++++++++++++++++++ src/coreclr/jit/knownbitsanalysis.cpp | 655 ++++++++++ src/coreclr/jit/knownbitsanalysis.h | 66 + 7 files changed, 2444 insertions(+), 3 deletions(-) create mode 100644 src/coreclr/jit/knownbits.h create mode 100644 src/coreclr/jit/knownbitsanalysis.cpp create mode 100644 src/coreclr/jit/knownbitsanalysis.h diff --git a/THIRD-PARTY-NOTICES.TXT b/THIRD-PARTY-NOTICES.TXT index a90dfd8f8dda9a..4278ece0b3d09c 100644 --- a/THIRD-PARTY-NOTICES.TXT +++ b/THIRD-PARTY-NOTICES.TXT @@ -1803,3 +1803,24 @@ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +License notice for LLVM known bits (src/coreclr/jit/knownbits.h) +------------------------------- + +Derived from https://github.com/llvm/llvm-project: llvm/include/llvm/ADT/APInt.h, llvm/lib/Support/APInt.cpp, +llvm/include/llvm/Support/KnownBits.h, llvm/lib/Support/KnownBits.cpp, llvm/lib/IR/ConstantRange.cpp and +llvm/lib/Analysis/ValueTracking.cpp + +Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. + +Licensed under the Apache License, Version 2.0 (the "License") with LLVM Exceptions; +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +https://llvm.org/LICENSE.txt + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/src/coreclr/jit/CMakeLists.txt b/src/coreclr/jit/CMakeLists.txt index c7fb86030c942e..473dcbd9d5cd41 100644 --- a/src/coreclr/jit/CMakeLists.txt +++ b/src/coreclr/jit/CMakeLists.txt @@ -157,6 +157,7 @@ set( JIT_SOURCES jiteh.cpp jithashtable.cpp jitmetadata.cpp + knownbitsanalysis.cpp layout.cpp lclmorph.cpp lclvars.cpp @@ -387,6 +388,8 @@ set( JIT_HEADERS jitmetadatalist.h jitpch.h jitstd.h + knownbits.h + knownbitsanalysis.h lir.h loopcloning.h loopcloningopts.h diff --git a/src/coreclr/jit/assertionprop.cpp b/src/coreclr/jit/assertionprop.cpp index cc6ad21b1f6887..a3c0ae3c94f828 100644 --- a/src/coreclr/jit/assertionprop.cpp +++ b/src/coreclr/jit/assertionprop.cpp @@ -12,6 +12,7 @@ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX #include "jitpch.h" #include "rangecheck.h" +#include "knownbitsanalysis.h" #ifdef _MSC_VER #pragma hdrstop #endif @@ -861,6 +862,7 @@ void Compiler::optAssertionTraitsInit(AssertionIndex assertionCount) void Compiler::optAssertionInit(bool isLocalProp) { assert(NO_ASSERTION_INDEX == 0); + optKnownBitsPhiCache = nullptr; const unsigned maxTrackedLocals = (unsigned)JitConfig.JitMaxLocalsToTrack(); // We initialize differently for local prop / global prop @@ -1936,9 +1938,32 @@ AssertionInfo Compiler::optCreateJTrueBoundsAssertion(GenTree* tree) ValueNum op1VN = relopFuncApp.GetArg(0); ValueNum op2VN = relopFuncApp.GetArg(1); - if ((genActualType(vnStore->TypeOfVN(op1VN)) != TYP_INT) || (genActualType(vnStore->TypeOfVN(op2VN)) != TYP_INT)) + const var_types op1Type = genActualType(vnStore->TypeOfVN(op1VN)); + const var_types op2Type = genActualType(vnStore->TypeOfVN(op2VN)); + if ((op1Type == TYP_LONG) && (op2Type == TYP_LONG) && !isEqualityRelop) { - // For now, we don't have consumers for assertions derived from non-int32 comparisons + // 64-bit comparisons: we only create "X relop CNS" assertions for these, they are used + // to compute the known bits (and the ranges, if they fit into 32 bits) of 64-bit values. + ssize_t cns; + if (vnStore->IsVNIntegralConstant(op1VN, &cns)) + { + std::swap(op1VN, op2VN); + relopFunc = ValueNumStore::SwapRelop(relopFunc); + } + + if (vnStore->IsVNIntegralConstant(op2VN, &cns) && (!isUnsignedRelop || (cns > 0))) + { + AssertionDsc dsc = AssertionDsc::CreateConstantBound(this, relopFunc, op1VN, op2VN); + AssertionIndex idx = optAddAssertion(dsc); + optCreateComplementaryAssertion(idx); + return idx; + } + return NO_ASSERTION_INDEX; + } + + if ((op1Type != TYP_INT) || (op2Type != TYP_INT)) + { + // For now, we don't have consumers for assertions derived from other comparisons return NO_ASSERTION_INDEX; } @@ -4830,6 +4855,20 @@ GenTree* Compiler::optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, } } + // See if the known bits of "op1" tell us the result of comparing it with a constant. + // This is a hot path, so don't call into the analysis for the relops it can't handle + // anyway (e.g. checks for null or for a handle). + if (op2->IsIntegralConst() && !op2->IsIconHandle() && varTypeIsIntegral(op1)) + { + const KnownBool result = KnownBitsAnalysis(this).EvalRelop(tree->AsOp(), assertions); + if (result.HasValue) + { + JITDUMP("Folding relop [%06u] based on known bits.\n", dspTreeID(tree)); + newTree = gtWrapWithSideEffects(result.Value ? gtNewTrue() : gtNewFalse(), tree, GTF_ALL_EFFECT); + return optAssertionProp_Update(newTree, tree, stmt); + } + } + // The rest is for EQ/NE only. if (!tree->OperIs(GT_EQ, GT_NE)) { @@ -6997,5 +7036,8 @@ PhaseStatus Compiler::optAssertionPropMain() optAssertionPropagatedCurrentStmt = false; // clear it back as we are done with stmts. } + // The cached known bits of PHIs depend on this phase's assertions, don't let them outlive it. + optKnownBitsPhiCache = nullptr; + return madeChanges ? PhaseStatus::MODIFIED_EVERYTHING : PhaseStatus::MODIFIED_NOTHING; } diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index 007f77cb3d3ce5..773170064be24e 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -9389,7 +9389,8 @@ class Compiler { return optAssertionCount; } - ASSERT_TP* bbJtrueAssertionOut; + struct KnownBitsPhiCache* optKnownBitsPhiCache = nullptr; // the known bits of PHIs, see KnownBitsAnalysis + ASSERT_TP* bbJtrueAssertionOut; // Assertion prop helpers. ASSERT_TP& GetAssertionDep(unsigned lclNum, bool mustExist = false); diff --git a/src/coreclr/jit/knownbits.h b/src/coreclr/jit/knownbits.h new file mode 100644 index 00000000000000..5c80dc2d1e9143 --- /dev/null +++ b/src/coreclr/jit/knownbits.h @@ -0,0 +1,1653 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +//===----------------------------------------------------------------------===// +// +// This file is a port of LLVM's "known bits" infrastructure. It tracks, for an integer value, +// which bits are known to be zero and which are known to be one, and provides the transfer +// functions that compute the known bits of an operation's result from those of its operands. +// +// Everything in this file is derived from the LLVM Project: +// +// class APInt - llvm/include/llvm/ADT/APInt.h, llvm/lib/Support/APInt.cpp +// (a subset, limited to values that fit into a single 64-bit word) +// struct KnownBits - llvm/include/llvm/Support/KnownBits.h, llvm/lib/Support/KnownBits.cpp +// struct KnownBitsRange - the KnownBits related parts of llvm/lib/IR/ConstantRange.cpp +// (toKnownBits) +// struct KnownBitsTracking - the IR independent parts of llvm/lib/Analysis/ValueTracking.cpp +// (computeKnownBitsMul) +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +// The code deliberately keeps LLVM's names and structure so that it can be compared against the +// LLVM sources, and it contains nothing that is specific to the JIT: the JIT's own logic (walking +// value numbers and assertions) lives in knownbitsanalysis.cpp. +// +// Differences from LLVM: +// * Only the functions that the JIT uses (directly or indirectly) are here. +// * APInt is limited to 64 bits, std::optional is replaced with KnownBool. +// * Functionality that has no JIT counterpart is omitted: nuw/nsw flags on shifts, exact +// divisions and shifts, saturating arithmetic, funnel shifts, min/max, pext/pdep, etc. +// +//===----------------------------------------------------------------------===// + +#ifndef _KNOWNBITS_H_ +#define _KNOWNBITS_H_ + +// A single-word (at most 64 bits) subset of llvm::APInt: an unsigned integer of a fixed bit width +// with two's complement semantics. Bits above BitWidth are always zero. +class APInt +{ + uint64_t U = 0; + unsigned BitWidth = 1; + + static uint64_t maskTrailingOnes(unsigned N) + { + assert(N <= 64); + return (N == 0) ? 0 : (UINT64_MAX >> (64 - N)); + } + + static int64_t SignExtend64(uint64_t X, unsigned B) + { + assert((B > 0) && (B <= 64)); + return (int64_t)(X << (64 - B)) >> (64 - B); + } + +public: + APInt() = default; + + APInt(unsigned numBits, uint64_t val) + : U(val & maskTrailingOnes(numBits)) + , BitWidth(numBits) + { + } + + static APInt getAllOnes(unsigned numBits) + { + return APInt(numBits, UINT64_MAX); + } + static APInt getMaxValue(unsigned numBits) + { + return getAllOnes(numBits); + } + static APInt getSignedMaxValue(unsigned numBits) + { + APInt API = getAllOnes(numBits); + API.clearBit(numBits - 1); + return API; + } + static APInt getSignedMinValue(unsigned numBits) + { + APInt API(numBits, 0); + API.setBit(numBits - 1); + return API; + } + static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) + { + APInt Res(numBits, 0); + Res.setHighBits(hiBitsSet); + return Res; + } + static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) + { + APInt Res(numBits, 0); + Res.setLowBits(loBitsSet); + return Res; + } + + unsigned getBitWidth() const + { + return BitWidth; + } + uint64_t getZExtValue() const + { + return U; + } + int64_t getSExtValue() const + { + return SignExtend64(U, BitWidth); + } + uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX) const + { + return (U > Limit) ? Limit : U; + } + + bool isNegative() const + { + return (*this)[BitWidth - 1]; + } + bool isNonNegative() const + { + return !isNegative(); + } + bool isSignBitSet() const + { + return (*this)[BitWidth - 1]; + } + bool isSignBitClear() const + { + return !isSignBitSet(); + } + bool isAllOnes() const + { + return U == maskTrailingOnes(BitWidth); + } + bool isZero() const + { + return U == 0; + } + bool isMinSignedValue() const + { + return U == (uint64_t(1) << (BitWidth - 1)); + } + bool isMaxSignedValue() const + { + return U == ((uint64_t(1) << (BitWidth - 1)) - 1); + } + bool isPowerOf2() const + { + return (U != 0) && ((U & (U - 1)) == 0); + } + bool operator[](unsigned bitPosition) const + { + assert(bitPosition < BitWidth); + return ((U >> bitPosition) & 1) != 0; + } + bool intersects(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return (U & RHS.U) != 0; + } + bool isSubsetOf(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return (U & ~RHS.U) == 0; + } + bool isInverseOf(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return (U ^ RHS.U) == maskTrailingOnes(BitWidth); + } + + void setAllBits() + { + U = maskTrailingOnes(BitWidth); + } + void setBit(unsigned BitPosition) + { + assert(BitPosition < BitWidth); + U |= uint64_t(1) << BitPosition; + } + void setSignBit() + { + setBit(BitWidth - 1); + } + void setBits(unsigned loBit, unsigned hiBit) + { + assert((hiBit <= BitWidth) && (loBit <= hiBit)); + if (loBit != hiBit) + { + U |= maskTrailingOnes(hiBit - loBit) << loBit; + } + } + void setBitsFrom(unsigned loBit) + { + setBits(loBit, BitWidth); + } + void setLowBits(unsigned loBits) + { + setBits(0, loBits); + } + void setHighBits(unsigned hiBits) + { + setBits(BitWidth - hiBits, BitWidth); + } + void clearAllBits() + { + U = 0; + } + void clearBit(unsigned BitPosition) + { + assert(BitPosition < BitWidth); + U &= ~(uint64_t(1) << BitPosition); + } + void clearLowBits(unsigned loBits) + { + assert(loBits <= BitWidth); + APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits); + *this &= Keep; + } + void clearSignBit() + { + clearBit(BitWidth - 1); + } + + unsigned countl_zero() const + { + if (U == 0) + { + return BitWidth; + } + return BitOperations::LeadingZeroCount(U) - (64 - BitWidth); + } + unsigned countl_one() const + { + return (~*this).countl_zero(); + } + unsigned countr_zero() const + { + if (U == 0) + { + return BitWidth; + } + return BitOperations::TrailingZeroCount(U); + } + unsigned countr_one() const + { + return (~*this).countr_zero(); + } + unsigned countLeadingZeros() const + { + return countl_zero(); + } + unsigned countLeadingOnes() const + { + return countl_one(); + } + + APInt operator~() const + { + return APInt(BitWidth, ~U); + } + APInt operator-() const + { + return APInt(BitWidth, 0 - U); + } + APInt& operator&=(const APInt& RHS) + { + assert(BitWidth == RHS.BitWidth); + U &= RHS.U; + return *this; + } + APInt& operator|=(const APInt& RHS) + { + assert(BitWidth == RHS.BitWidth); + U |= RHS.U; + return *this; + } + APInt& operator+=(const APInt& RHS) + { + assert(BitWidth == RHS.BitWidth); + U = (U + RHS.U) & maskTrailingOnes(BitWidth); + return *this; + } + APInt& operator<<=(unsigned ShiftAmt) + { + assert(ShiftAmt <= BitWidth); + U = (ShiftAmt >= 64) ? 0 : ((U << ShiftAmt) & maskTrailingOnes(BitWidth)); + return *this; + } + APInt operator&(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return APInt(BitWidth, U & RHS.U); + } + APInt operator|(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return APInt(BitWidth, U | RHS.U); + } + APInt operator^(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return APInt(BitWidth, U ^ RHS.U); + } + APInt operator+(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return APInt(BitWidth, U + RHS.U); + } + APInt operator+(uint64_t RHS) const + { + return APInt(BitWidth, U + RHS); + } + APInt operator-(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return APInt(BitWidth, U - RHS.U); + } + APInt operator-(uint64_t RHS) const + { + return APInt(BitWidth, U - RHS); + } + APInt operator*(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return APInt(BitWidth, U * RHS.U); + } + APInt operator<<(unsigned Bits) const + { + APInt R(*this); + R <<= Bits; + return R; + } + bool operator==(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return U == RHS.U; + } + void lshrInPlace(unsigned ShiftAmt) + { + assert(ShiftAmt <= BitWidth); + U = (ShiftAmt >= 64) ? 0 : (U >> ShiftAmt); + } + APInt lshr(unsigned shiftAmt) const + { + APInt R(*this); + R.lshrInPlace(shiftAmt); + return R; + } + void ashrInPlace(unsigned ShiftAmt) + { + assert(ShiftAmt <= BitWidth); + int64_t SExtVAL = SignExtend64(U, BitWidth); + if (ShiftAmt == BitWidth) + { + U = (uint64_t)(SExtVAL >> 63); // Fill with sign bit. + } + else + { + U = (uint64_t)(SExtVAL >> ShiftAmt); + } + U &= maskTrailingOnes(BitWidth); + } + APInt trunc(unsigned width) const + { + assert(width <= BitWidth); + return APInt(width, U); + } + APInt zext(unsigned width) const + { + assert(width >= BitWidth); + return APInt(width, U); + } + APInt sext(unsigned width) const + { + assert(width >= BitWidth); + return APInt(width, (uint64_t)SignExtend64(U, BitWidth)); + } + APInt zextOrTrunc(unsigned width) const + { + return APInt(width, U); + } + APInt getLoBits(unsigned numBits) const + { + APInt Result(getLowBitsSet(BitWidth, numBits)); + Result &= *this; + return Result; + } + uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const + { + assert((bitPosition < BitWidth) && ((numBits + bitPosition) <= BitWidth)); + return (U >> bitPosition) & maskTrailingOnes(numBits); + } + bool ult(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return U < RHS.U; + } + bool ule(const APInt& RHS) const + { + return !RHS.ult(*this); + } + bool ugt(const APInt& RHS) const + { + return RHS.ult(*this); + } + bool uge(const APInt& RHS) const + { + return !ult(RHS); + } + bool slt(const APInt& RHS) const + { + assert(BitWidth == RHS.BitWidth); + return getSExtValue() < RHS.getSExtValue(); + } + bool sle(const APInt& RHS) const + { + return !RHS.slt(*this); + } + bool sgt(const APInt& RHS) const + { + return RHS.slt(*this); + } + bool sge(const APInt& RHS) const + { + return !slt(RHS); + } + + APInt udiv(const APInt& RHS) const + { + assert((BitWidth == RHS.BitWidth) && (RHS.U != 0)); + return APInt(BitWidth, U / RHS.U); + } + APInt sdiv(const APInt& RHS) const + { + if (isNegative()) + { + if (RHS.isNegative()) + { + return (-(*this)).udiv(-RHS); + } + return -((-(*this)).udiv(RHS)); + } + if (RHS.isNegative()) + { + return -(this->udiv(-RHS)); + } + return this->udiv(RHS); + } + + APInt sadd_ov(const APInt& RHS, bool& Overflow) const + { + APInt Res = *this + RHS; + Overflow = (isNonNegative() == RHS.isNonNegative()) && (Res.isNonNegative() != isNonNegative()); + return Res; + } + APInt uadd_ov(const APInt& RHS, bool& Overflow) const + { + APInt Res = *this + RHS; + Overflow = Res.ult(RHS); + return Res; + } + APInt ssub_ov(const APInt& RHS, bool& Overflow) const + { + APInt Res = *this - RHS; + Overflow = (isNonNegative() != RHS.isNonNegative()) && (Res.isNonNegative() != isNonNegative()); + return Res; + } + APInt usub_ov(const APInt& RHS, bool& Overflow) const + { + APInt Res = *this - RHS; + Overflow = Res.ugt(*this); + return Res; + } + APInt umul_ov(const APInt& RHS, bool& Overflow) const + { + if ((countl_zero() + RHS.countl_zero() + 2) <= BitWidth) + { + Overflow = true; + return *this * RHS; + } + + APInt Res = lshr(1) * RHS; + Overflow = Res.isNegative(); + Res <<= 1; + if ((*this)[0]) + { + Res += RHS; + if (Res.ult(RHS)) + { + Overflow = true; + } + } + return Res; + } + APInt ushl_ov(unsigned ShAmt, bool& Overflow) const + { + Overflow = ShAmt >= getBitWidth(); + if (Overflow) + { + return APInt(BitWidth, 0); + } + + Overflow = ShAmt > countl_zero(); + + return *this << ShAmt; + } + APInt sadd_sat(const APInt& RHS) const + { + bool Overflow; + APInt Res = sadd_ov(RHS, Overflow); + if (!Overflow) + { + return Res; + } + + return isNegative() ? APInt::getSignedMinValue(BitWidth) : APInt::getSignedMaxValue(BitWidth); + } + APInt uadd_sat(const APInt& RHS) const + { + bool Overflow; + APInt Res = uadd_ov(RHS, Overflow); + if (!Overflow) + { + return Res; + } + + return APInt::getMaxValue(BitWidth); + } + APInt ssub_sat(const APInt& RHS) const + { + bool Overflow; + APInt Res = ssub_ov(RHS, Overflow); + if (!Overflow) + { + return Res; + } + + return isNegative() ? APInt::getSignedMinValue(BitWidth) : APInt::getSignedMaxValue(BitWidth); + } + APInt usub_sat(const APInt& RHS) const + { + bool Overflow; + APInt Res = usub_ov(RHS, Overflow); + if (!Overflow) + { + return Res; + } + + return APInt(BitWidth, 0); + } + + // APIntOps::umin + static const APInt& umin(const APInt& A, const APInt& B) + { + return A.ult(B) ? A : B; + } + + // APIntOps::umax + static const APInt& umax(const APInt& A, const APInt& B) + { + return A.ugt(B) ? A : B; + } + + // APIntOps::smin + static const APInt& smin(const APInt& A, const APInt& B) + { + return A.slt(B) ? A : B; + } + + // APIntOps::smax + static const APInt& smax(const APInt& A, const APInt& B) + { + return A.sgt(B) ? A : B; + } + + // APIntOps::GetMostSignificantDifferentBit. Returns false when A == B (std::nullopt in LLVM). + static bool GetMostSignificantDifferentBit(const APInt& A, const APInt& B, unsigned* DifferentBit) + { + assert(A.getBitWidth() == B.getBitWidth()); + if (A == B) + { + return false; + } + *DifferentBit = A.getBitWidth() - ((A ^ B).countl_zero() + 1); + return true; + } +}; + +// Stand-in for the std::optional results of llvm::KnownBits's comparisons. +struct KnownBool +{ + bool HasValue; + bool Value; + + KnownBool() + : HasValue(false) + , Value(false) + { + } + KnownBool(bool Value) + : HasValue(true) + , Value(Value) + { + } +}; + +// Struct for tracking the known zeros and ones of a value. +struct KnownBits +{ + APInt Zero; + APInt One; + + // Internal constructor for creating a KnownBits from two APInts. + KnownBits(APInt Zero, APInt One) + : Zero(Zero) + , One(One) + { + } + +private: + static KnownBits computeForAddCarry(const KnownBits& LHS, const KnownBits& RHS, bool CarryZero, bool CarryOne) + { + APInt PossibleSumZero = LHS.getMaxValue() + RHS.getMaxValue() + (uint64_t)!CarryZero; + APInt PossibleSumOne = LHS.getMinValue() + RHS.getMinValue() + (uint64_t)CarryOne; + + // Compute known bits of the carry. + APInt CarryKnownZero = ~(PossibleSumZero ^ LHS.Zero ^ RHS.Zero); + APInt CarryKnownOne = PossibleSumOne ^ LHS.One ^ RHS.One; + + // Compute set of known bits (where all three relevant bits are known). + APInt LHSKnownUnion = LHS.Zero | LHS.One; + APInt RHSKnownUnion = RHS.Zero | RHS.One; + APInt CarryKnownUnion = CarryKnownZero | CarryKnownOne; + APInt Known = LHSKnownUnion & RHSKnownUnion & CarryKnownUnion; + + // Compute known bits of the result. + KnownBits KnownOut; + KnownOut.Zero = ~PossibleSumZero & Known; + KnownOut.One = PossibleSumOne & Known; + return KnownOut; + } + + static unsigned getMaxShiftAmount(const APInt& MaxValue, unsigned BitWidth) + { + if ((BitWidth & (BitWidth - 1)) == 0) + { + // Clamp to the shift amount's width: a narrower amount is already + // < BitWidth, so this stays a valid upper bound. + unsigned Log2 = BitOperations::Log2((uint32_t)BitWidth); + return (unsigned)MaxValue.extractBitsAsZExtValue(std::min(Log2, MaxValue.getBitWidth()), 0); + } + // This is only an approximate upper bound. + return (unsigned)MaxValue.getLimitedValue(BitWidth - 1); + } + + // Internal helper for getting the initial KnownBits for an `srem` or `urem` + // operation with the low-bits set. + static KnownBits remGetLowBits(const KnownBits& LHS, const KnownBits& RHS) + { + unsigned BitWidth = LHS.getBitWidth(); + if (!RHS.isZero() && RHS.Zero[0]) + { + // rem X, Y where Y[0:N] is zero will preserve X[0:N] in the result. + unsigned RHSZeros = RHS.countMinTrailingZeros(); + APInt Mask = APInt::getLowBitsSet(BitWidth, RHSZeros); + APInt OnesMask = LHS.One & Mask; + APInt ZerosMask = LHS.Zero & Mask; + return KnownBits(ZerosMask, OnesMask); + } + return KnownBits(BitWidth); + } + +public: + // Default construct Zero and One. + KnownBits() = default; + + /// Create a known bits object of BitWidth bits initialized to unknown. + explicit KnownBits(unsigned BitWidth) + : Zero(BitWidth, 0) + , One(BitWidth, 0) + { + } + + /// Get the bit width of this value. + unsigned getBitWidth() const + { + assert(Zero.getBitWidth() == One.getBitWidth()); + return Zero.getBitWidth(); + } + + /// Returns true if there is conflicting information. + bool hasConflict() const + { + return Zero.intersects(One); + } + + /// Returns true if we know the value of all bits. + bool isConstant() const + { + return Zero.isInverseOf(One); + } + + /// Returns the value when all bits have a known value. This just returns One + /// with a protective assertion. + const APInt& getConstant() const + { + assert(isConstant()); + return One; + } + + /// Returns true if we don't know any bits. + bool isUnknown() const + { + return Zero.isZero() && One.isZero(); + } + + /// Resets the known state of all bits. + void resetAll() + { + Zero.clearAllBits(); + One.clearAllBits(); + } + + /// Returns true if value is all zero. + bool isZero() const + { + return Zero.isAllOnes(); + } + + /// Returns true if value is all one bits. + bool isAllOnes() const + { + return One.isAllOnes(); + } + + /// Make all bits known to be zero and discard any previous information. + void setAllZero() + { + Zero.setAllBits(); + One.clearAllBits(); + } + + /// Make all bits known to be both zero and one. Useful before a loop that + /// calls intersectWith. + void setAllConflict() + { + Zero.setAllBits(); + One.setAllBits(); + } + + /// Returns true if this value is known to be negative. + bool isNegative() const + { + return One.isSignBitSet(); + } + + /// Returns true if this value is known to be non-negative. + bool isNonNegative() const + { + return Zero.isSignBitSet(); + } + + /// Returns true if this value is known to be non-zero. + bool isNonZero() const + { + return !One.isZero(); + } + + /// Returns true if this value is known to be positive. + bool isStrictlyPositive() const + { + return Zero.isSignBitSet() && !One.isZero(); + } + + /// Make this value negative. + void makeNegative() + { + One.setSignBit(); + } + + /// Make this value non-negative. + void makeNonNegative() + { + Zero.setSignBit(); + } + + /// Return the minimal unsigned value possible given these KnownBits. + APInt getMinValue() const + { + // Assume that all bits that aren't known-ones are zeros. + return One; + } + + /// Return the minimal signed value possible given these KnownBits. + APInt getSignedMinValue() const + { + // Assume that all bits that aren't known-ones are zeros. + APInt Min = One; + // Sign bit is unknown. + if (Zero.isSignBitClear()) + { + Min.setSignBit(); + } + return Min; + } + + /// Return the maximal unsigned value possible given these KnownBits. + APInt getMaxValue() const + { + // Assume that all bits that aren't known-zeros are ones. + return ~Zero; + } + + /// Return the maximal signed value possible given these KnownBits. + APInt getSignedMaxValue() const + { + // Assume that all bits that aren't known-zeros are ones. + APInt Max = ~Zero; + // Sign bit is unknown. + if (One.isSignBitClear()) + { + Max.clearSignBit(); + } + return Max; + } + + /// Return known bits for a truncation of the value we're tracking. + KnownBits trunc(unsigned BitWidth) const + { + return KnownBits(Zero.trunc(BitWidth), One.trunc(BitWidth)); + } + + /// Return known bits for a zero extension of the value we're tracking. + KnownBits zext(unsigned BitWidth) const + { + unsigned OldBitWidth = getBitWidth(); + APInt NewZero = Zero.zext(BitWidth); + NewZero.setBitsFrom(OldBitWidth); + return KnownBits(NewZero, One.zext(BitWidth)); + } + + /// Return known bits for a sign extension of the value we're tracking. + KnownBits sext(unsigned BitWidth) const + { + return KnownBits(Zero.sext(BitWidth), One.sext(BitWidth)); + } + + /// Returns the minimum number of trailing zero bits. + unsigned countMinTrailingZeros() const + { + return Zero.countr_one(); + } + + /// Returns the minimum number of leading zero bits. + unsigned countMinLeadingZeros() const + { + return Zero.countl_one(); + } + + /// Returns the minimum number of leading one bits. + unsigned countMinLeadingOnes() const + { + return One.countl_one(); + } + + /// Returns the number of times the sign bit is replicated into the other + /// bits. + unsigned countMinSignBits() const + { + if (isNonNegative()) + { + return countMinLeadingZeros(); + } + if (isNegative()) + { + return countMinLeadingOnes(); + } + // Every value has at least 1 sign bit. + return 1; + } + + /// Create known bits from a known constant. + static KnownBits makeConstant(const APInt& C) + { + return KnownBits(~C, C); + } + + /// Returns KnownBits information that is known to be true for both this and + /// RHS. + /// + /// When an operation is known to return one of its operands, this can be used + /// to combine information about the known bits of the operands to get the + /// information that must be true about the result. + KnownBits intersectWith(const KnownBits& RHS) const + { + return KnownBits(Zero & RHS.Zero, One & RHS.One); + } + + /// Returns KnownBits information that is known to be true for either this or + /// RHS or both. + /// + /// This can be used to combine different sources of information about the + /// known bits of a single value, e.g. information about the low bits and the + /// high bits of the result of a multiplication. + KnownBits unionWith(const KnownBits& RHS) const + { + return KnownBits(Zero | RHS.Zero, One | RHS.One); + } + + /// Compute known bits resulting from adding LHS and RHS. + static KnownBits computeForAddSub(bool Add, bool NSW, bool NUW, const KnownBits& LHS, const KnownBits& RHS) + { + unsigned BitWidth = LHS.getBitWidth(); + KnownBits KnownOut(BitWidth); + // This can be a relatively expensive helper, so optimistically save some + // work. + if (LHS.isUnknown() && RHS.isUnknown()) + { + return KnownOut; + } + + if (!LHS.isUnknown() && !RHS.isUnknown()) + { + if (Add) + { + // Sum = LHS + RHS + 0 + KnownOut = computeForAddCarry(LHS, RHS, /*CarryZero=*/true, /*CarryOne=*/false); + } + else + { + // Sum = LHS + ~RHS + 1 + KnownBits NotRHS = RHS; + std::swap(NotRHS.Zero, NotRHS.One); + KnownOut = computeForAddCarry(LHS, NotRHS, /*CarryZero=*/false, /*CarryOne=*/true); + } + } + + // Handle add/sub given nsw and/or nuw. + if (NUW) + { + if (Add) + { + // (add nuw X, Y) + APInt MinVal = LHS.getMinValue().uadd_sat(RHS.getMinValue()); + // None of the adds can end up overflowing, so min consecutive highbits + // in minimum possible of X + Y must all remain set. + if (NSW) + { + unsigned NumBits = MinVal.trunc(BitWidth - 1).countl_one(); + // If we have NSW as well, we also know we can't overflow the signbit so + // can start counting from 1 bit back. + KnownOut.One.setBits(BitWidth - 1 - NumBits, BitWidth - 1); + } + KnownOut.One.setHighBits(MinVal.countl_one()); + } + else + { + // (sub nuw X, Y) + APInt MaxVal = LHS.getMaxValue().usub_sat(RHS.getMinValue()); + // None of the subs can overflow at any point, so any common high bits + // will subtract away and result in zeros. + if (NSW) + { + // If we have NSW as well, we also know we can't overflow the signbit so + // can start counting from 1 bit back. + unsigned NumBits = MaxVal.trunc(BitWidth - 1).countl_zero(); + KnownOut.Zero.setBits(BitWidth - 1 - NumBits, BitWidth - 1); + } + KnownOut.Zero.setHighBits(MaxVal.countl_zero()); + } + } + + if (NSW) + { + APInt MinVal; + APInt MaxVal; + if (Add) + { + // (add nsw X, Y) + MinVal = LHS.getSignedMinValue().sadd_sat(RHS.getSignedMinValue()); + MaxVal = LHS.getSignedMaxValue().sadd_sat(RHS.getSignedMaxValue()); + } + else + { + // (sub nsw X, Y) + MinVal = LHS.getSignedMinValue().ssub_sat(RHS.getSignedMaxValue()); + MaxVal = LHS.getSignedMaxValue().ssub_sat(RHS.getSignedMinValue()); + } + if (MinVal.isNonNegative()) + { + // If min is non-negative, result will always be non-neg (can't overflow + // around). + unsigned NumBits = MinVal.trunc(BitWidth - 1).countl_one(); + KnownOut.One.setBits(BitWidth - 1 - NumBits, BitWidth - 1); + KnownOut.Zero.setSignBit(); + } + if (MaxVal.isNegative()) + { + // If max is negative, result will always be neg (can't overflow around). + unsigned NumBits = MaxVal.trunc(BitWidth - 1).countl_zero(); + KnownOut.Zero.setBits(BitWidth - 1 - NumBits, BitWidth - 1); + KnownOut.One.setSignBit(); + } + } + + // Just return 0 if the nsw/nuw is violated and we have poison. + if (KnownOut.hasConflict()) + { + KnownOut.setAllZero(); + } + return KnownOut; + } + + /// Compute knownbits resulting from subtraction of LHS and RHS. + static KnownBits sub(const KnownBits& LHS, const KnownBits& RHS, bool NSW = false, bool NUW = false) + { + return computeForAddSub(/*Add=*/false, NSW, NUW, LHS, RHS); + } + + /// Compute known bits resulting from multiplying LHS and RHS. + static KnownBits mul(const KnownBits& LHS, const KnownBits& RHS, bool NoUndefSelfMultiply = false) + { + unsigned BitWidth = LHS.getBitWidth(); + assert(BitWidth == RHS.getBitWidth()); + assert(!NoUndefSelfMultiply || (LHS == RHS)); + + // Compute the high known-0 bits by multiplying the unsigned max of each side. + // Conservatively, M active bits * N active bits results in M + N bits in the + // result. But if we know a value is a power-of-2 for example, then this + // computes one more leading zero. + // TODO: This could be generalized to number of sign bits (negative numbers). + APInt UMaxLHS = LHS.getMaxValue(); + APInt UMaxRHS = RHS.getMaxValue(); + + // For leading zeros in the result to be valid, the unsigned max product must + // fit in the bitwidth (it must not overflow). + bool HasOverflow; + APInt UMaxResult = UMaxLHS.umul_ov(UMaxRHS, HasOverflow); + unsigned LeadZ = HasOverflow ? 0 : UMaxResult.countl_zero(); + + // The result of the bottom bits of an integer multiply can be + // inferred by looking at the bottom bits of both operands and + // multiplying them together. + // We can infer at least the minimum number of known trailing bits + // of both operands. Depending on number of trailing zeros, we can + // infer more bits, because (a*b) <=> ((a/m) * (b/n)) * (m*n) assuming + // a and b are divisible by m and n respectively. + // We then calculate how many of those bits are inferrable and set + // the output. For example, the i8 mul: + // a = XXXX1100 (12) + // b = XXXX1110 (14) + // We know the bottom 3 bits are zero since the first can be divided by + // 4 and the second by 2, thus having ((12/4) * (14/2)) * (2*4). + // Applying the multiplication to the trimmed arguments gets: + // XX11 (3) + // X111 (7) + // ------- + // XX11 + // XX11 + // XX11 + // XX11 + // ------- + // XXXXX01 + // Which allows us to infer the 2 LSBs. Since we're multiplying the result + // by 8, the bottom 3 bits will be 0, so we can infer a total of 5 bits. + + // How many times we'd be able to divide each argument by 2 (shr by 1). + // This gives us the number of trailing zeros on the multiplication result. + unsigned TrailBitsKnownLHS = (LHS.Zero | LHS.One).countr_one(); + unsigned TrailBitsKnownRHS = (RHS.Zero | RHS.One).countr_one(); + unsigned TrailZeroLHS = LHS.countMinTrailingZeros(); + unsigned TrailZeroRHS = RHS.countMinTrailingZeros(); + unsigned TrailZ = TrailZeroLHS + TrailZeroRHS; + + // Figure out the fewest known-bits operand. + unsigned SmallestOperand = std::min(TrailBitsKnownLHS - TrailZeroLHS, TrailBitsKnownRHS - TrailZeroRHS); + unsigned ResultBitsKnown = std::min(SmallestOperand + TrailZ, BitWidth); + + // The lower ResultBitsKnown bits of this are known. + APInt BottomKnown = LHS.One * RHS.One; + + KnownBits Res(BitWidth); + Res.Zero.setHighBits(LeadZ); + Res.Zero |= (~BottomKnown).getLoBits(ResultBitsKnown); + Res.One = BottomKnown.getLoBits(ResultBitsKnown); + + if (NoUndefSelfMultiply) + { + // If X has at least TZ trailing zeroes, then bit (2 * TZ + 1) must be zero. + unsigned TwoTZP1 = 2 * TrailZeroLHS + 1; + if (TwoTZP1 < BitWidth) + { + Res.Zero.setBit(TwoTZP1); + } + + // If X has exactly TZ trailing zeros, then bit (2 * TZ + 2) must also be + // zero. + if ((TrailZeroLHS < BitWidth) && LHS.One[TrailZeroLHS]) + { + unsigned TwoTZP2 = TwoTZP1 + 1; + if (TwoTZP2 < BitWidth) + { + Res.Zero.setBit(TwoTZP2); + } + } + } + + return Res; + } + + /// Compute known bits for sdiv(LHS, RHS). + static KnownBits sdiv(const KnownBits& LHS, const KnownBits& RHS) + { + // Equivalent of `udiv`. We must have caught this before it was folded. + if (LHS.isNonNegative() && RHS.isNonNegative()) + { + return udiv(LHS, RHS); + } + + unsigned BitWidth = LHS.getBitWidth(); + KnownBits Known(BitWidth); + + if (LHS.isZero() || RHS.isZero()) + { + // Result is either known Zero or UB. Return Zero either way. + // Checking this earlier saves us a lot of special cases later on. + Known.setAllZero(); + return Known; + } + + bool HasRes = false; + APInt Res; + if (LHS.isNegative() && RHS.isNegative()) + { + // Result non-negative. + APInt Denom = RHS.getSignedMaxValue(); + APInt Num = LHS.getSignedMinValue(); + // INT_MIN/-1 would be a poison result (impossible). Estimate the division + // as signed max (we will only set sign bit in the result). + Res = (Num.isMinSignedValue() && Denom.isAllOnes()) ? APInt::getSignedMaxValue(BitWidth) : Num.sdiv(Denom); + HasRes = true; + } + else if (LHS.isNegative() && RHS.isNonNegative()) + { + // Result is negative if -LHS u>= RHS. + if ((-LHS.getSignedMaxValue()).uge(RHS.getSignedMaxValue())) + { + APInt Denom = RHS.getSignedMinValue(); + APInt Num = LHS.getSignedMinValue(); + // If the denominator may be zero, use the lowest unknown bit as the + // minimum non-zero denominator, matching udiv. + if (Denom.isZero()) + { + Denom.setBit(RHS.countMinTrailingZeros()); + } + Res = Num.sdiv(Denom); + HasRes = true; + } + } + else if (LHS.isStrictlyPositive() && RHS.isNegative()) + { + // Result is negative if LHS u>= -RHS. + if (LHS.getSignedMinValue().uge(-RHS.getSignedMinValue())) + { + APInt Denom = RHS.getSignedMaxValue(); + APInt Num = LHS.getSignedMaxValue(); + Res = Num.sdiv(Denom); + HasRes = true; + } + } + + if (HasRes) + { + if (Res.isNonNegative()) + { + unsigned LeadZ = Res.countLeadingZeros(); + Known.Zero.setHighBits(LeadZ); + } + else + { + unsigned LeadO = Res.countLeadingOnes(); + Known.One.setHighBits(LeadO); + } + } + + return Known; + } + + /// Compute known bits for udiv(LHS, RHS). + static KnownBits udiv(const KnownBits& LHS, const KnownBits& RHS) + { + unsigned BitWidth = LHS.getBitWidth(); + KnownBits Known(BitWidth); + + if (LHS.isZero() || RHS.isZero()) + { + // Result is either known Zero or UB. Return Zero either way. + // Checking this earlier saves us a lot of special cases later on. + Known.setAllZero(); + return Known; + } + + // A zero denominator is UB, so the minimum attainable denominator is the + // smallest non-zero value consistent with the known bits. + APInt MinDenom = RHS.getMinValue(); + if (MinDenom.isZero()) + { + MinDenom.setBit(RHS.countMinTrailingZeros()); + } + + // The quotient grows when the numerator grows and shrinks when the + // denominator grows, and all four operand bounds are attainable, so the + // result is in [MinNum / MaxDenom, MaxNum / MinDenom]. Keep the common + // leading bits of the two bounds (as ConstantRange::toKnownBits does), + // which can include leading ones, not just leading zeros. + APInt MaxDenom = RHS.getMaxValue(); + APInt MaxRes = LHS.getMaxValue().udiv(MinDenom); + APInt MinRes = LHS.getMinValue().udiv(MaxDenom); + + Known = KnownBits::makeConstant(MinRes); + unsigned DifferentBit; + if (APInt::GetMostSignificantDifferentBit(MinRes, MaxRes, &DifferentBit)) + { + Known.Zero.clearLowBits(DifferentBit + 1); + Known.One.clearLowBits(DifferentBit + 1); + } + + return Known; + } + + /// Compute known bits for urem(LHS, RHS). + static KnownBits urem(const KnownBits& LHS, const KnownBits& RHS) + { + // L % R for L < R is L. (A zero divisor is UB, and if MinR is zero this + // condition cannot hold anyway.) + if (LHS.getMaxValue().ult(RHS.getMinValue())) + { + return LHS; + } + + KnownBits Known = remGetLowBits(LHS, RHS); + + // L % R is at most L and, since a zero divisor is UB, strictly less than + // R, so the result has at least as many leading zeros as + // umin(MaxL, MaxR - 1), as in ConstantRange::urem. For a power-of-two + // constant R this computes the exact L & (R - 1): remGetLowBits preserved + // the low bits and this clears the bits from log2(R) up. If R is known to + // be zero, MaxR - 1 wraps around, which is harmless: every input is UB. + APInt MaxRes = APInt::umin(LHS.getMaxValue(), RHS.getMaxValue() - 1); + Known.Zero.setHighBits(MaxRes.countLeadingZeros()); + return Known; + } + + /// Compute known bits for srem(LHS, RHS). + static KnownBits srem(const KnownBits& LHS, const KnownBits& RHS) + { + KnownBits Known = remGetLowBits(LHS, RHS); + if (RHS.isConstant() && RHS.getConstant().isPowerOf2()) + { + // NB: Low bits are set in `remGetLowBits`. + APInt LowBits = RHS.getConstant() - 1; + // If the first operand is non-negative or has all low bits zero, then + // the upper bits are all zero. + if (LHS.isNonNegative() || LowBits.isSubsetOf(LHS.Zero)) + { + Known.Zero |= ~LowBits; + } + + // If the first operand is negative and not all low bits are zero, then + // the upper bits are all one. + if (LHS.isNegative() && LowBits.intersects(LHS.One)) + { + Known.One |= ~LowBits; + } + return Known; + } + + // The sign bit is the LHS's sign bit, except when the result of the + // remainder is zero. The magnitude of the result should be less than or + // equal to the magnitude of either operand. + if (LHS.isNegative() && Known.isNonZero()) + { + Known.One.setHighBits(std::max(LHS.countMinLeadingOnes(), RHS.countMinSignBits())); + } + else if (LHS.isNonNegative()) + { + Known.Zero.setHighBits(std::max(LHS.countMinLeadingZeros(), RHS.countMinSignBits())); + } + return Known; + } + + /// Compute known bits for shl(LHS, RHS). + /// NOTE: RHS (shift amount) bitwidth doesn't need to be the same as LHS. + static KnownBits shl(const KnownBits& LHS, const KnownBits& RHS, bool ShAmtNonZero = false) + { + unsigned BitWidth = LHS.getBitWidth(); + auto ShiftByConst = [&](const KnownBits& LHS, unsigned ShiftAmt) { + KnownBits Known; + bool ShiftedOutZero, ShiftedOutOne; + Known.Zero = LHS.Zero.ushl_ov(ShiftAmt, ShiftedOutZero); + Known.Zero.setLowBits(ShiftAmt); + Known.One = LHS.One.ushl_ov(ShiftAmt, ShiftedOutOne); + return Known; + }; + + // Fast path for a common case when LHS is completely unknown. + KnownBits Known(BitWidth); + unsigned MinShiftAmount = (unsigned)RHS.getMinValue().getLimitedValue(BitWidth); + if ((MinShiftAmount == 0) && ShAmtNonZero) + { + MinShiftAmount = 1; + } + if (LHS.isUnknown()) + { + Known.Zero.setLowBits(MinShiftAmount); + return Known; + } + + // Determine maximum shift amount. + APInt MaxValue = RHS.getMaxValue(); + unsigned MaxShiftAmount = getMaxShiftAmount(MaxValue, BitWidth); + + // Fast path for common case where the shift amount is unknown. + if ((MinShiftAmount == 0) && (MaxShiftAmount == (BitWidth - 1)) && ((BitWidth & (BitWidth - 1)) == 0)) + { + Known.Zero.setLowBits(LHS.countMinTrailingZeros()); + if (LHS.isAllOnes()) + { + Known.One.setSignBit(); + } + return Known; + } + + // Find the common bits from all possible shifts. + unsigned ShiftAmtZeroMask = (unsigned)RHS.Zero.zextOrTrunc(32).getZExtValue(); + unsigned ShiftAmtOneMask = (unsigned)RHS.One.zextOrTrunc(32).getZExtValue(); + Known.setAllConflict(); + for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount; ++ShiftAmt) + { + // Skip if the shift amount is impossible. + if (((ShiftAmtZeroMask & ShiftAmt) != 0) || ((ShiftAmtOneMask | ShiftAmt) != ShiftAmt)) + { + continue; + } + Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt)); + if (Known.isUnknown()) + { + break; + } + } + + // All shift amounts may result in poison. + if (Known.hasConflict()) + { + Known.setAllZero(); + } + return Known; + } + + /// Compute known bits for lshr(LHS, RHS). + /// NOTE: RHS (shift amount) bitwidth doesn't need to be the same as LHS. + static KnownBits lshr(const KnownBits& LHS, const KnownBits& RHS, bool ShAmtNonZero = false) + { + unsigned BitWidth = LHS.getBitWidth(); + auto ShiftByConst = [&](const KnownBits& LHS, unsigned ShiftAmt) { + KnownBits Known = LHS; + Known >>= ShiftAmt; + // High bits are known zero. + Known.Zero.setHighBits(ShiftAmt); + return Known; + }; + + // Fast path for a common case when LHS is completely unknown. + KnownBits Known(BitWidth); + unsigned MinShiftAmount = (unsigned)RHS.getMinValue().getLimitedValue(BitWidth); + if ((MinShiftAmount == 0) && ShAmtNonZero) + { + MinShiftAmount = 1; + } + if (LHS.isUnknown()) + { + Known.Zero.setHighBits(MinShiftAmount); + return Known; + } + + // Find the common bits from all possible shifts. + APInt MaxValue = RHS.getMaxValue(); + unsigned MaxShiftAmount = getMaxShiftAmount(MaxValue, BitWidth); + + unsigned ShiftAmtZeroMask = (unsigned)RHS.Zero.zextOrTrunc(32).getZExtValue(); + unsigned ShiftAmtOneMask = (unsigned)RHS.One.zextOrTrunc(32).getZExtValue(); + Known.setAllConflict(); + for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount; ++ShiftAmt) + { + // Skip if the shift amount is impossible. + if (((ShiftAmtZeroMask & ShiftAmt) != 0) || ((ShiftAmtOneMask | ShiftAmt) != ShiftAmt)) + { + continue; + } + Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt)); + if (Known.isUnknown()) + { + break; + } + } + + // All shift amounts may result in poison. + if (Known.hasConflict()) + { + Known.setAllZero(); + } + return Known; + } + + /// Compute known bits for ashr(LHS, RHS). + /// NOTE: RHS (shift amount) bitwidth doesn't need to be the same as LHS. + static KnownBits ashr(const KnownBits& LHS, const KnownBits& RHS, bool ShAmtNonZero = false) + { + unsigned BitWidth = LHS.getBitWidth(); + auto ShiftByConst = [&](const KnownBits& LHS, unsigned ShiftAmt) { + KnownBits Known = LHS; + Known.Zero.ashrInPlace(ShiftAmt); + Known.One.ashrInPlace(ShiftAmt); + return Known; + }; + + // Fast path for a common case when LHS is completely unknown. + KnownBits Known(BitWidth); + unsigned MinShiftAmount = (unsigned)RHS.getMinValue().getLimitedValue(BitWidth); + if ((MinShiftAmount == 0) && ShAmtNonZero) + { + MinShiftAmount = 1; + } + if (LHS.isUnknown()) + { + if (MinShiftAmount == BitWidth) + { + // Always poison. Return zero because we don't like returning conflict. + Known.setAllZero(); + return Known; + } + return Known; + } + + // Find the common bits from all possible shifts. + APInt MaxValue = RHS.getMaxValue(); + unsigned MaxShiftAmount = getMaxShiftAmount(MaxValue, BitWidth); + + unsigned ShiftAmtZeroMask = (unsigned)RHS.Zero.zextOrTrunc(32).getZExtValue(); + unsigned ShiftAmtOneMask = (unsigned)RHS.One.zextOrTrunc(32).getZExtValue(); + Known.setAllConflict(); + for (unsigned ShiftAmt = MinShiftAmount; ShiftAmt <= MaxShiftAmount; ++ShiftAmt) + { + // Skip if the shift amount is impossible. + if (((ShiftAmtZeroMask & ShiftAmt) != 0) || ((ShiftAmtOneMask | ShiftAmt) != ShiftAmt)) + { + continue; + } + Known = Known.intersectWith(ShiftByConst(LHS, ShiftAmt)); + if (Known.isUnknown()) + { + break; + } + } + + // All shift amounts may result in poison. + if (Known.hasConflict()) + { + Known.setAllZero(); + } + return Known; + } + + /// Determine if these known bits always give the same ICMP_EQ result. + static KnownBool eq(const KnownBits& LHS, const KnownBits& RHS) + { + if (LHS.isConstant() && RHS.isConstant()) + { + return KnownBool(LHS.getConstant() == RHS.getConstant()); + } + if (LHS.One.intersects(RHS.Zero) || RHS.One.intersects(LHS.Zero)) + { + return KnownBool(false); + } + return KnownBool(); + } + + /// Determine if these known bits always give the same ICMP_SGT result. + static KnownBool sgt(const KnownBits& LHS, const KnownBits& RHS) + { + // LHS >s RHS -> false if smax(LHS) <= smax(RHS) + if (LHS.getSignedMaxValue().sle(RHS.getSignedMinValue())) + { + return KnownBool(false); + } + // LHS >s RHS -> true if smin(LHS) > smax(RHS) + if (LHS.getSignedMinValue().sgt(RHS.getSignedMaxValue())) + { + return KnownBool(true); + } + return KnownBool(); + } + + /// Update known bits based on ANDing with RHS. + KnownBits& operator&=(const KnownBits& RHS) + { + // Result bit is 0 if either operand bit is 0. + Zero |= RHS.Zero; + // Result bit is 1 if both operand bits are 1. + One &= RHS.One; + return *this; + } + + /// Update known bits based on ORing with RHS. + KnownBits& operator|=(const KnownBits& RHS) + { + // Result bit is 0 if both operand bits are 0. + Zero &= RHS.Zero; + // Result bit is 1 if either operand bit is 1. + One |= RHS.One; + return *this; + } + + /// Update known bits based on XORing with RHS. + KnownBits& operator^=(const KnownBits& RHS) + { + // Result bit is 0 if both operand bits are 0 or both are 1. + APInt Z = (Zero & RHS.Zero) | (One & RHS.One); + // Result bit is 1 if one operand bit is 0 and the other is 1. + One = (Zero & RHS.One) | (One & RHS.Zero); + Zero = Z; + return *this; + } + + /// Shift known bits right by ShAmt. Shifted in bits are unknown. + KnownBits& operator>>=(unsigned ShAmt) + { + Zero.lshrInPlace(ShAmt); + One.lshrInPlace(ShAmt); + return *this; + } + + bool operator==(const KnownBits& Other) const + { + return (Zero == Other.Zero) && (One == Other.One); + } +}; + +inline KnownBits operator&(KnownBits LHS, const KnownBits& RHS) +{ + LHS &= RHS; + return LHS; +} + +inline KnownBits operator|(KnownBits LHS, const KnownBits& RHS) +{ + LHS |= RHS; + return LHS; +} + +inline KnownBits operator^(KnownBits LHS, const KnownBits& RHS) +{ + LHS ^= RHS; + return LHS; +} + +// The KnownBits related parts of llvm::ConstantRange. +struct KnownBitsRange +{ + // ConstantRange::toKnownBits for the range of unsigned values [Min, Max] (both inclusive): + // we can only retain the top bits that are the same between min and max. + static KnownBits toKnownBits(const APInt& Min, const APInt& Max) + { + assert(Min.ule(Max)); + KnownBits Known = KnownBits::makeConstant(Min); + unsigned DifferentBit; + if (APInt::GetMostSignificantDifferentBit(Min, Max, &DifferentBit)) + { + Known.Zero.clearLowBits(DifferentBit + 1); + Known.One.clearLowBits(DifferentBit + 1); + } + return Known; + } +}; + +// The parts of llvm/lib/Analysis/ValueTracking.cpp that do not depend on the IR. +struct KnownBitsTracking +{ + // computeKnownBitsMul: the known bits of "mul Known2, Known" given its no-wrap flags. + static KnownBits computeKnownBitsMul( + const KnownBits& Known2, const KnownBits& Known, bool NSW, bool NUW, bool SelfMultiply) + { + bool isKnownNegative = false; + bool isKnownNonNegative = false; + // If the multiplication is known not to overflow, compute the sign bit. + if (NSW) + { + if (SelfMultiply) + { + // The product of a number with itself is non-negative. + isKnownNonNegative = true; + } + else + { + bool isKnownNonNegativeOp1 = Known.isNonNegative(); + bool isKnownNonNegativeOp0 = Known2.isNonNegative(); + bool isKnownNegativeOp1 = Known.isNegative(); + bool isKnownNegativeOp0 = Known2.isNegative(); + // The product of two numbers with the same sign is non-negative. + isKnownNonNegative = + (isKnownNegativeOp1 && isKnownNegativeOp0) || (isKnownNonNegativeOp1 && isKnownNonNegativeOp0); + if (!isKnownNonNegative && NUW) + { + // mul nuw nsw with a factor > 1 is non-negative. + KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1)); + KnownBool SGT1 = KnownBits::sgt(Known, One); + KnownBool SGT2 = KnownBits::sgt(Known2, One); + isKnownNonNegative = (SGT1.HasValue && SGT1.Value) || (SGT2.HasValue && SGT2.Value); + } + + // The product of a negative number and a non-negative number is either + // negative or zero. + if (!isKnownNonNegative) + { + isKnownNegative = (isKnownNegativeOp1 && isKnownNonNegativeOp0 && Known2.isNonZero()) || + (isKnownNegativeOp0 && isKnownNonNegativeOp1 && Known.isNonZero()); + } + } + } + + KnownBits Result = KnownBits::mul(Known, Known2, SelfMultiply); + + // Only make use of no-wrap flags if we failed to compute the sign bit + // directly. This matters if the multiplication always overflows, in + // which case we prefer to follow the result of the direct computation, + // though as the program is invoking undefined behaviour we can choose + // whatever we like here. + if (isKnownNonNegative && !Result.isNegative()) + { + Result.makeNonNegative(); + } + else if (isKnownNegative && !Result.isNonNegative()) + { + Result.makeNegative(); + } + return Result; + } +}; + +#endif // _KNOWNBITS_H_ diff --git a/src/coreclr/jit/knownbitsanalysis.cpp b/src/coreclr/jit/knownbitsanalysis.cpp new file mode 100644 index 00000000000000..8778b31c46877e --- /dev/null +++ b/src/coreclr/jit/knownbitsanalysis.cpp @@ -0,0 +1,655 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#include "jitpch.h" +#ifdef _MSC_VER +#pragma hdrstop +#endif + +#include "knownbitsanalysis.h" + +// The known bits of PHIs, see KnownBitsAnalysis::ComputeForPhi. +struct KnownBitsPhiCache : public JitHashTable, KnownBits> +{ + KnownBitsPhiCache(CompAllocator alloc) + : JitHashTable(alloc) + { + } +}; + +//------------------------------------------------------------------------ +// Bounds: Create the bounds that the known bits of a value imply. +// +// Arguments: +// known - the known bits +// +KnownBitsAnalysis::Bounds::Bounds(const KnownBits& known) + : UMin(known.getMinValue()) + , UMax(known.getMaxValue()) + , SMin(known.getSignedMinValue()) + , SMax(known.getSignedMaxValue()) +{ +} + +//------------------------------------------------------------------------ +// IsUnknown: Check if nothing is known about the value. +// +// Return Value: +// true if the bounds are those of the type. +// +bool KnownBitsAnalysis::Bounds::IsUnknown() const +{ + return UMin.isZero() && UMax.isAllOnes() && SMin.isMinSignedValue() && SMax.isMaxSignedValue(); +} + +//------------------------------------------------------------------------ +// ApplyRelop: Refine the bounds given that "this relop other" holds. +// +// Arguments: +// kind - the kind of the assertion, the relop +// other - the bounds of the other operand +// +// Notes: +// The relops that can never be true mean that the code is unreachable, these are ignored. +// +void KnownBitsAnalysis::Bounds::ApplyRelop(Compiler::optAssertionKind kind, const Bounds& other) +{ + switch (kind) + { + case Compiler::OAK_EQUAL: + UMin = APInt::umax(UMin, other.UMin); + UMax = APInt::umin(UMax, other.UMax); + SMin = APInt::smax(SMin, other.SMin); + SMax = APInt::smin(SMax, other.SMax); + break; + case Compiler::OAK_LT_UN: + if (!other.UMax.isZero()) + { + UMax = APInt::umin(UMax, other.UMax - 1); + } + break; + case Compiler::OAK_LE_UN: + UMax = APInt::umin(UMax, other.UMax); + break; + case Compiler::OAK_GT_UN: + if (!other.UMin.isAllOnes()) + { + UMin = APInt::umax(UMin, other.UMin + 1); + } + break; + case Compiler::OAK_GE_UN: + UMin = APInt::umax(UMin, other.UMin); + break; + case Compiler::OAK_LT: + if (!other.SMax.isMinSignedValue()) + { + SMax = APInt::smin(SMax, other.SMax - 1); + } + break; + case Compiler::OAK_LE: + SMax = APInt::smin(SMax, other.SMax); + break; + case Compiler::OAK_GT: + if (!other.SMin.isMaxSignedValue()) + { + SMin = APInt::smax(SMin, other.SMin + 1); + } + break; + case Compiler::OAK_GE: + SMin = APInt::smax(SMin, other.SMin); + break; + default: + break; + } +} + +//------------------------------------------------------------------------ +// Normalize: Share the signed and unsigned bounds when that is possible. +// +// Notes: +// A value that is known to be non-negative (or negative) is ordered the same way +// by the signed and unsigned comparisons. +// +void KnownBitsAnalysis::Bounds::Normalize() +{ + if (UMax.isNonNegative() || UMin.isNegative()) + { + SMin = APInt::smax(SMin, UMin); + SMax = APInt::smin(SMax, UMax); + } + if (SMin.isNonNegative() || SMax.isNegative()) + { + UMin = APInt::umax(UMin, SMin); + UMax = APInt::umin(UMax, SMax); + } +} + +//------------------------------------------------------------------------ +// KnownBitsAnalysis: Create an instance of the analysis, a query. +// +// Arguments: +// comp - the compiler instance +// phiDepth - how many PHIs deep we are (used internally) +// +KnownBitsAnalysis::KnownBitsAnalysis(Compiler* comp, int phiDepth) + : m_compiler(comp) + , m_vnStore(comp->vnStore) + , m_budget(Budget) + , m_phiDepth(phiDepth) + , m_followVNAssertions(true) +{ +} + +//------------------------------------------------------------------------ +// EvalRelop: Evaluate a relop using the known bits and the bounds of its operands. +// +// Arguments: +// relop - the relop +// assertions - the assertions that hold for the relop, can be uninit +// +// Return Value: +// The result of the relop if it's the same for all the values its operands can have. +// +KnownBool KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions) +{ + assert(relop->OperIsCompare()); + GenTree* const op1 = relop->gtGetOp1(); + GenTree* const op2 = relop->gtGetOp2(); + + // TODO-CQ: handle "op2" that is not a constant, that needs to be cheap: most of + // the time we know nothing about it. + const unsigned width = GetWidth(op1->TypeGet()); + if ((width == 0) || (GetWidth(op2->TypeGet()) != width) || !op2->IsIntegralConst() || op2->IsIconHandle()) + { + return KnownBool(); + } + + const ValueNum op1VN = m_compiler->optConservativeNormalVN(op1); + + // TP: equality tests are too common to analyze all of them, and we rarely fold + // anything but the tests of bit patterns (e.g. flag checks) and casts. + if (relop->OperIs(GT_EQ, GT_NE)) + { + VNFuncApp funcApp; + if (!m_vnStore->GetVNFunc(op1VN, &funcApp) || !funcApp.FuncIs(VNF_AND, VNF_OR, VNF_XOR, VNF_Cast, VNF_CastOvf)) + { + return KnownBool(); + } + } + + Bounds b1{KnownBits(width)}; + const KnownBits known1 = Compute(op1VN, width, assertions, &b1); + if (known1.isUnknown() && b1.IsUnknown()) + { + return KnownBool(); + } + + const APInt cns(width, (uint64_t)op2->AsIntConCommon()->IntegralValue()); + const KnownBits known2 = KnownBits::makeConstant(cns); + const Bounds b2(known2); + + if (relop->OperIs(GT_EQ, GT_NE)) + { + KnownBool isEqual = KnownBits::eq(known1, known2); + if (!isEqual.HasValue && (cns.ult(b1.UMin) || cns.ugt(b1.UMax) || cns.slt(b1.SMin) || cns.sgt(b1.SMax))) + { + isEqual = KnownBool(false); + } + return isEqual.HasValue ? KnownBool(isEqual.Value == relop->OperIs(GT_EQ)) : KnownBool(); + } + + // Normalize to "lo < hi" or "lo <= hi". + const bool swap = relop->OperIs(GT_GT, GT_GE); + const bool isStrict = relop->OperIs(GT_LT, GT_GT); + const Bounds& lo = swap ? b2 : b1; + const Bounds& hi = swap ? b1 : b2; + if (relop->IsUnsigned()) + { + if (isStrict ? lo.UMax.ult(hi.UMin) : lo.UMax.ule(hi.UMin)) + { + return KnownBool(true); + } + if (isStrict ? lo.UMin.uge(hi.UMax) : lo.UMin.ugt(hi.UMax)) + { + return KnownBool(false); + } + } + else + { + if (isStrict ? lo.SMax.slt(hi.SMin) : lo.SMax.sle(hi.SMin)) + { + return KnownBool(true); + } + if (isStrict ? lo.SMin.sge(hi.SMax) : lo.SMin.sgt(hi.SMax)) + { + return KnownBool(false); + } + } + return KnownBool(); +} + +//------------------------------------------------------------------------ +// GetWidth: Get the bit width of the values of the given type. +// +// Arguments: +// type - the type +// +// Return Value: +// 32 for TYP_INT (and the small types), 64 for TYP_LONG, 0 if the type is not supported. +// +unsigned KnownBitsAnalysis::GetWidth(var_types type) +{ + switch (genActualType(type)) + { + case TYP_INT: + return 32; + case TYP_LONG: + return 64; + default: + return 0; + } +} + +//------------------------------------------------------------------------ +// Compute: Compute the known bits of a value number. +// +// Arguments: +// vn - the value number +// width - the bit width of the value (32 or 64) +// assertions - the assertions that hold for "vn", can be uninit +// pBounds - [out, optional] the bounds of the value, these can be more +// precise than the ones the known bits imply +// +// Return Value: +// The known bits; "unknown" when nothing is known (including the case of "vn" not +// being an integer of the given width). +// +KnownBits KnownBitsAnalysis::Compute(ValueNum vn, unsigned width, ASSERT_VALARG_TP assertions, Bounds* pBounds) +{ + assert((width == 32) || (width == 64)); + KnownBits known(width); + + // A GC pointer, a floating point value, etc. + const var_types vnType = (vn == ValueNumStore::NoVN) ? TYP_UNDEF : m_vnStore->TypeOfVN(vn); + bool isDone = GetWidth(vnType) != width; + + if (!isDone && m_vnStore->IsVNConstant(vn)) + { + // Handles are not known at this point (relocs). + int64_t cns; + if (m_vnStore->IsVNIntegralConstant(vn, &cns)) + { + known = KnownBits::makeConstant(APInt(width, (uint64_t)cns)); + } + isDone = true; + } + + if (isDone || (m_budget <= 0)) + { + if (pBounds != nullptr) + { + *pBounds = Bounds(known); + } + return known; + } + m_budget--; + + // Small unsigned values (e.g. loads) are zero-extended. + if (varTypeIsSmall(vnType) && varTypeIsUnsigned(vnType)) + { + known.Zero.setBitsFrom(genTypeSize(vnType) * BITS_PER_BYTE); + } + + VNFuncApp funcApp; + if (m_vnStore->GetVNFunc(vn, &funcApp)) + { + known = known.unionWith(ComputeForFunc(funcApp, width, assertions)); + } + else if ((width == 64) && m_vnStore->IsPhiDef(vn)) + { + // TP: PHIs are expensive, and RangeCheck::GetRangeFromAssertions already looks through + // them for 32-bit values, so we only do it for the 64-bit ones. + // TODO-CQ: do it for the 32-bit PHIs too (for their bit patterns). + known = known.unionWith(ComputeForPhi(vn, width)); + } + + Bounds bounds(known); + MergeAssertions(vn, width, assertions, &known, &bounds); + + if (known.hasConflict()) + { + // Contradicting facts mean that the code is unreachable. + known.resetAll(); + bounds = Bounds(known); + } + + if (pBounds != nullptr) + { + *pBounds = bounds; + } + return known; +} + +//------------------------------------------------------------------------ +// ComputeForPhi: Compute the known bits of a PHI: the bits that all the values +// reaching it have in common. +// +// Arguments: +// vn - the value number of the PHI definition +// width - the bit width of the value (32 or 64) +// +// Return Value: +// The known bits. +// +// Notes: +// The result is computed once (with its own budget) and cached: it depends on the assertions +// that hold on the edges to the PHI, not on the ones that hold at the point of the query. +// It is conservative for the PHIs that depend on each other (a PHI that is being computed +// is "unknown" to the ones it depends on) or that are more than MaxPhiDepth PHIs deep, so +// the answer for these may depend on which of them is asked about first. +// In particular, nothing is known about the induction variables. +// +KnownBits KnownBitsAnalysis::ComputeForPhi(ValueNum vn, unsigned width) +{ + if (m_compiler->optKnownBitsPhiCache == nullptr) + { + m_compiler->optKnownBitsPhiCache = + new (m_compiler, CMK_AssertionProp) KnownBitsPhiCache(m_compiler->getAllocator(CMK_AssertionProp)); + } + KnownBitsPhiCache* const cache = m_compiler->optKnownBitsPhiCache; + + KnownBits result(width); + const KnownBits* cached = cache->LookupPointer(vn); + if (cached != nullptr) + { + // A conflict marks a PHI that is being computed: we have a cycle, nothing is known. + return cached->hasConflict() ? result : *cached; + } + + if (m_phiDepth >= MaxPhiDepth) + { + return result; + } + + result.setAllConflict(); + cache->Set(vn, result); + + KnownBitsAnalysis analysis(m_compiler, m_phiDepth + 1); + auto visitor = [&](ValueNum reachingVN, ASSERT_TP reachingAssertions) { + result = result.intersectWith(analysis.Compute(reachingVN, width, reachingAssertions)); + return result.isUnknown() ? Compiler::AssertVisit::Abort : Compiler::AssertVisit::Continue; + }; + + if ((m_compiler->optVisitReachingAssertions(vn, visitor) != Compiler::AssertVisit::Continue) || + result.hasConflict()) + { + result.resetAll(); + } + + cache->Set(vn, result, KnownBitsPhiCache::Overwrite); + return result; +} + +//------------------------------------------------------------------------ +// ComputeForFunc: Compute the known bits of a function application from its operands. +// +// Arguments: +// funcApp - the function application +// width - the bit width of its value (32 or 64) +// assertions - the assertions that hold for the operands, can be uninit +// +// Return Value: +// The known bits. +// +KnownBits KnownBitsAnalysis::ComputeForFunc(const VNFuncApp& funcApp, unsigned width, ASSERT_VALARG_TP assertions) +{ + KnownBits known(width); + const VNFunc func = funcApp.GetFunc(); + + if (ValueNumStore::VNFuncIsComparison(func)) + { + // 0 or 1 + known.Zero.setBitsFrom(1); + return known; + } + + switch (func) + { + case VNF_AND: + case VNF_OR: + case VNF_XOR: + { + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + KnownBits op2 = Compute(funcApp.GetArg(1), width, assertions); + return (func == VNF_AND) ? (op1 & op2) : ((func == VNF_OR) ? (op1 | op2) : (op1 ^ op2)); + } + + case VNF_NOT: + { + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + std::swap(op1.Zero, op1.One); + return op1; + } + + case VNF_NEG: + { + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + return KnownBits::sub(KnownBits::makeConstant(APInt(width, 0)), op1); + } + + case VNF_ADD: + case VNF_SUB: + { + // Nothing is known about the result if nothing is known about one of the operands. + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + if (!op1.isUnknown()) + { + KnownBits op2 = Compute(funcApp.GetArg(1), width, assertions); + return KnownBits::computeForAddSub(func == VNF_ADD, /* NSW */ false, /* NUW */ false, op1, op2); + } + break; + } + + case VNF_ADD_OVF: + case VNF_ADD_UN_OVF: + case VNF_SUB_OVF: + case VNF_SUB_UN_OVF: + { + // These produce a value only if they don't overflow. + const bool isAdd = (func == VNF_ADD_OVF) || (func == VNF_ADD_UN_OVF); + const bool isUnsigned = (func == VNF_ADD_UN_OVF) || (func == VNF_SUB_UN_OVF); + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + KnownBits op2 = Compute(funcApp.GetArg(1), width, assertions); + return KnownBits::computeForAddSub(isAdd, /* NSW */ !isUnsigned, /* NUW */ isUnsigned, op1, op2); + } + + case VNF_MUL: + case VNF_MUL_OVF: + case VNF_MUL_UN_OVF: + { + const bool isSelfMul = funcApp.GetArg(0) == funcApp.GetArg(1); + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + KnownBits op2 = isSelfMul ? op1 : Compute(funcApp.GetArg(1), width, assertions); + return KnownBitsTracking::computeKnownBitsMul(op1, op2, /* NSW */ func == VNF_MUL_OVF, + /* NUW */ func == VNF_MUL_UN_OVF, isSelfMul); + } + + case VNF_DIV: + case VNF_MOD: + case VNF_UDIV: + case VNF_UMOD: + { + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + KnownBits op2 = Compute(funcApp.GetArg(1), width, assertions); + switch (func) + { + case VNF_DIV: + return KnownBits::sdiv(op1, op2); + case VNF_MOD: + return KnownBits::srem(op1, op2); + case VNF_UDIV: + return KnownBits::udiv(op1, op2); + default: + return KnownBits::urem(op1, op2); + } + } + + case VNF_LSH: + case VNF_RSH: + case VNF_RSZ: + { + KnownBits amount = Compute(funcApp.GetArg(1), 32, assertions); +#ifdef TARGET_64BIT + // The shift amount is masked. + amount = amount & KnownBits::makeConstant(APInt(32, width - 1)); +#else + if (amount.getMaxValue().getZExtValue() >= width) + { + break; + } +#endif + KnownBits op1 = Compute(funcApp.GetArg(0), width, assertions); + switch (func) + { + case VNF_LSH: + return KnownBits::shl(op1, amount); + case VNF_RSH: + return KnownBits::ashr(op1, amount); + default: + return KnownBits::lshr(op1, amount); + } + } + + case VNF_Cast: + case VNF_CastOvf: + { + var_types castToType; + bool srcIsUnsigned; + m_vnStore->GetCastOperFromVN(funcApp.GetArg(1), &castToType, &srcIsUnsigned); + if (!varTypeIsIntegral(castToType)) + { + break; + } + + const unsigned castBits = genTypeSize(castToType) * BITS_PER_BYTE; + const unsigned srcWidth = GetWidth(m_vnStore->TypeOfVN(funcApp.GetArg(0))); + if (srcWidth == 0) + { + // A cast from a floating point or GC value, we only know that the result + // is extended from the target type. + if ((castBits < width) && varTypeIsUnsigned(castToType)) + { + known.Zero.setBitsFrom(castBits); + } + break; + } + + KnownBits src = Compute(funcApp.GetArg(0), srcWidth, assertions); + if (castBits < srcWidth) + { + // A truncation that is followed by an extension to the stack type (for small types). + src = src.trunc(castBits); + if (castBits < width) + { + src = varTypeIsUnsigned(castToType) ? src.zext(width) : src.sext(width); + } + } + else if (castBits > srcWidth) + { + src = srcIsUnsigned ? src.zext(width) : src.sext(width); + } + + if (src.getBitWidth() != width) + { + break; + } + known = src; + + if ((func == VNF_CastOvf) && (srcIsUnsigned || varTypeIsUnsigned(castToType))) + { + // The checked cast produces a value only if the source value, signed or unsigned + // depending on "srcIsUnsigned", fits into the target type. Here that is a + // non-negative value that is less than 2^castMaxBits and 2^srcMaxBits. + const unsigned castMaxBits = varTypeIsUnsigned(castToType) ? castBits : (castBits - 1); + const unsigned srcMaxBits = srcIsUnsigned ? srcWidth : (srcWidth - 1); + const unsigned maxBits = min(castMaxBits, srcMaxBits); + if (maxBits < width) + { + known.Zero.setBitsFrom(maxBits); + } + } + return known; + } + + default: + break; + } + + return known; +} + +//------------------------------------------------------------------------ +// MergeAssertions: Refine the known bits and the bounds of a value number using +// the "vn relop cns" and "vn relop otherVN" assertions. +// +// Arguments: +// vn - the value number +// width - the bit width of the value (32 or 64) +// assertions - the assertions that hold for "vn", can be uninit +// pKnown - [in, out] the known bits of "vn" +// pBounds - [in, out] the bounds of "vn" +// +void KnownBitsAnalysis::MergeAssertions( + ValueNum vn, unsigned width, ASSERT_VALARG_TP assertions, KnownBits* pKnown, Bounds* pBounds) +{ + if (BitVecOps::MayBeUninit(assertions) || !m_compiler->optAssertionHasAssertionsForVN(vn)) + { + return; + } + + BitVecOps::Iter iter(m_compiler->apTraits, assertions); + unsigned index = 0; + while (iter.NextElem(&index)) + { + const Compiler::AssertionDsc& assertion = m_compiler->optGetAssertion(GetAssertionIndex(index)); + if (!assertion.GetOp1().KindIs(Compiler::O1K_VN) || (assertion.GetOp1().GetVN() != vn) || + assertion.KindIs(Compiler::OAK_NOT_EQUAL)) + { + continue; + } + + const auto& op2 = assertion.GetOp2(); + if (op2.KindIs(Compiler::O2K_CONST_INT) && !op2.HasIconFlag()) + { + // "vn relop cns". Handles are not known at this point (relocs). + pBounds->ApplyRelop(assertion.GetKind(), + KnownBits::makeConstant(APInt(width, (uint64_t)op2.GetIntConstant()))); + } + else if (m_followVNAssertions && op2.KindIs(Compiler::O2K_VN_ADD_CNS) && (op2.GetCns() == 0)) + { + // "vn relop otherVN". Don't use such assertions for "otherVN" and its operands, + // that would send us in circles. + Bounds otherBounds{KnownBits(width)}; + m_followVNAssertions = false; + const KnownBits other = Compute(op2.GetVN(), width, assertions, &otherBounds); + m_followVNAssertions = true; + if (op2.IsVNNeverNegative()) + { + otherBounds.ApplyRelop(Compiler::OAK_GE, KnownBits::makeConstant(APInt(width, 0))); + otherBounds.Normalize(); + } + + pBounds->ApplyRelop(assertion.GetKind(), otherBounds); + if (assertion.KindIs(Compiler::OAK_EQUAL)) + { + *pKnown = pKnown->unionWith(other); + } + } + } + + pBounds->Normalize(); + if (pBounds->UMin.ule(pBounds->UMax)) + { + *pKnown = pKnown->unionWith(KnownBitsRange::toKnownBits(pBounds->UMin, pBounds->UMax)); + } +} diff --git a/src/coreclr/jit/knownbitsanalysis.h b/src/coreclr/jit/knownbitsanalysis.h new file mode 100644 index 00000000000000..57e1e85f544a89 --- /dev/null +++ b/src/coreclr/jit/knownbitsanalysis.h @@ -0,0 +1,66 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#pragma once + +#include "knownbits.h" + +//------------------------------------------------------------------------ +// KnownBitsAnalysis: Computes the known bits of a value number: the bits that are known to be +// zero or one given the shape of the value number, the PHIs and a set of assertions. +// It complements RangeCheck::GetRangeFromAssertions: ranges describe the magnitude of a value +// while known bits describe its bit pattern (alignment, masks, flags), and they work for +// 64-bit values too. +// +// The KnownBits type and its transfer functions are LLVM's, see knownbits.h. +// +// Notes: +// Besides the known bits, the analysis tracks the signed and unsigned bounds of a value: +// "x < 10" doesn't tell us anything about the bits of "x" unless "x" is known to be +// non-negative as well, which we may learn from another assertion. +// +// The analysis relies on the assertions and their data flow, so it can only be used +// during the global assertion propagation. +// +class KnownBitsAnalysis +{ + // The number of non-constant value numbers a query is allowed to look at. + static const int Budget = 16; + // How deep the PHIs of PHIs are followed. + static const int MaxPhiDepth = 3; + + Compiler* m_compiler; + ValueNumStore* m_vnStore; + int m_budget; + int m_phiDepth; + bool m_followVNAssertions; // whether to use "vn relop otherVN" assertions + + // Unsigned and signed bounds of a value. + struct Bounds + { + APInt UMin; + APInt UMax; + APInt SMin; + APInt SMax; + + Bounds(const KnownBits& known); + + bool IsUnknown() const; + void ApplyRelop(Compiler::optAssertionKind kind, const Bounds& other); + void Normalize(); + }; + + static unsigned GetWidth(var_types type); + + KnownBits Compute(ValueNum vn, unsigned width, ASSERT_VALARG_TP assertions, Bounds* pBounds = nullptr); + KnownBits ComputeForPhi(ValueNum vn, unsigned width); + KnownBits ComputeForFunc(const VNFuncApp& funcApp, unsigned width, ASSERT_VALARG_TP assertions); + void MergeAssertions(ValueNum vn, unsigned width, ASSERT_VALARG_TP assertions, KnownBits* pKnown, Bounds* pBounds); + +public: + KnownBitsAnalysis(Compiler* comp, int phiDepth = 0); + + // Not to be inlined (LTCG does that): this is called from a hot path of the assertion + // propagation where it rarely has anything to do, having it inlined there costs TP. + NOINLINE KnownBool EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions); +}; From 395723d2f8b4eeadc09856be5526107b4d6bd7ad Mon Sep 17 00:00:00 2001 From: Egor Bogatov Date: Wed, 25 Nov 2026 14:53:43 +0100 Subject: [PATCH 2/3] Address KnownBits review feedback - Use RelopEvaluationResult instead of KnownBool - Use a typedef for the PHI cache - Handle native int shift amounts, use TARGET_MASKS_SHIFTS - Use BitVecOps::VisitBits in MergeAssertions - Add STRESS_KNOWNBITS_BUDGET and STRESS_KNOWNBITS_RELOPS stress modes - Add GlobalAssertionCount/GlobalAssertionOverflow metrics Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: acaabbe4-a3ed-45ef-838d-d23718212f6e --- src/coreclr/jit/assertionprop.cpp | 10 ++- src/coreclr/jit/compiler.h | 9 ++- src/coreclr/jit/jitmetadatalist.h | 2 + src/coreclr/jit/knownbits.h | 46 +++++-------- src/coreclr/jit/knownbitsanalysis.cpp | 96 +++++++++++++++------------ src/coreclr/jit/knownbitsanalysis.h | 4 +- 6 files changed, 89 insertions(+), 78 deletions(-) diff --git a/src/coreclr/jit/assertionprop.cpp b/src/coreclr/jit/assertionprop.cpp index 066d690dbbffdc..005f38c0842dd5 100644 --- a/src/coreclr/jit/assertionprop.cpp +++ b/src/coreclr/jit/assertionprop.cpp @@ -4866,11 +4866,12 @@ GenTree* Compiler::optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, // anyway (e.g. checks for null or for a handle). if (op2->IsIntegralConst() && !op2->IsIconHandle() && varTypeIsIntegral(op1)) { - const KnownBool result = KnownBitsAnalysis(this).EvalRelop(tree->AsOp(), assertions); - if (result.HasValue) + const RelopEvaluationResult result = KnownBitsAnalysis(this).EvalRelop(tree->AsOp(), assertions); + if (result != RelopEvaluationResult::Unknown) { JITDUMP("Folding relop [%06u] based on known bits.\n", dspTreeID(tree)); - newTree = gtWrapWithSideEffects(result.Value ? gtNewTrue() : gtNewFalse(), tree, GTF_ALL_EFFECT); + newTree = gtWrapWithSideEffects((result == RelopEvaluationResult::True) ? gtNewTrue() : gtNewFalse(), tree, + GTF_ALL_EFFECT); return optAssertionProp_Update(newTree, tree, stmt); } } @@ -6887,6 +6888,9 @@ PhaseStatus Compiler::optAssertionPropMain() // All assertions are created, size the bit vectors accordingly. optAssertionTraitsInit(max(optAssertionCount, (AssertionIndex)1)); + Metrics.GlobalAssertionCount = optAssertionCount; + Metrics.GlobalAssertionOverflow = optAssertionOverflow; + if (optAssertionCount == 0) { // Zero out the bbAssertionIn values, as these can be referenced in RangeCheck::MergeAssertion diff --git a/src/coreclr/jit/compiler.h b/src/coreclr/jit/compiler.h index 96b29dc5ac75f1..30391a03b43ec8 100644 --- a/src/coreclr/jit/compiler.h +++ b/src/coreclr/jit/compiler.h @@ -89,6 +89,7 @@ struct JumpThreadInfo; // defined in redundantbranchopts.cpp class ProfileSynthesis; // defined in profilesynthesis.h class PerLoopInfo; // defined in inductionvariableopts.cpp class RangeCheck; // defined in rangecheck.h +struct KnownBits; // defined in knownbits.h #ifdef TARGET_WASM class WasmInterval; // defined in fgwasm.h enum class WasmValueType : unsigned; @@ -9398,8 +9399,10 @@ class Compiler { return optAssertionCount; } - struct KnownBitsPhiCache* optKnownBitsPhiCache = nullptr; // the known bits of PHIs, see KnownBitsAnalysis - ASSERT_TP* bbJtrueAssertionOut; + // The known bits of PHIs, see KnownBitsAnalysis::ComputeForPhi. + typedef JitHashTable, KnownBits> KnownBitsPhiCache; + KnownBitsPhiCache* optKnownBitsPhiCache = nullptr; + ASSERT_TP* bbJtrueAssertionOut; // Assertion prop helpers. ASSERT_TP& GetAssertionDep(unsigned lclNum, bool mustExist = false); @@ -11937,6 +11940,8 @@ class Compiler STRESS_MODE(POISON_IMPLICIT_BYREFS) \ STRESS_MODE(THREE_OPT_LAYOUT) \ STRESS_MODE(GET_RANGE) /* Force slow SSA-based range walk in GetRange */ \ + STRESS_MODE(KNOWNBITS_BUDGET) /* Use larger budgets in KnownBitsAnalysis */ \ + STRESS_MODE(KNOWNBITS_RELOPS) /* Let KnownBitsAnalysis try to fold all EQ/NE relops */ \ STRESS_MODE(COUNT) enum compStressArea diff --git a/src/coreclr/jit/jitmetadatalist.h b/src/coreclr/jit/jitmetadatalist.h index 3ca15c2a54eb84..731d8e679bc3c1 100644 --- a/src/coreclr/jit/jitmetadatalist.h +++ b/src/coreclr/jit/jitmetadatalist.h @@ -94,6 +94,8 @@ JITMETADATAMETRIC(NewArrayHelperCalls, int, 0) JITMETADATAMETRIC(StackAllocatedArrays, int, 0) JITMETADATAMETRIC(LocalAssertionCount, int, 0) JITMETADATAMETRIC(LocalAssertionOverflow, int, 0) +JITMETADATAMETRIC(GlobalAssertionCount, int, 0) +JITMETADATAMETRIC(GlobalAssertionOverflow, int, 0) JITMETADATAMETRIC(MorphTrackedLocals, int, 0) JITMETADATAMETRIC(MorphLocals, int, 0) JITMETADATAMETRIC(EnumeratorGDVProvisionalNoEscape, int, 0) diff --git a/src/coreclr/jit/knownbits.h b/src/coreclr/jit/knownbits.h index 5c80dc2d1e9143..1c0a09fe874d93 100644 --- a/src/coreclr/jit/knownbits.h +++ b/src/coreclr/jit/knownbits.h @@ -27,7 +27,8 @@ // // Differences from LLVM: // * Only the functions that the JIT uses (directly or indirectly) are here. -// * APInt is limited to 64 bits, std::optional is replaced with KnownBool. +// * APInt is limited to 64 bits, std::optional is replaced with the JIT's +// RelopEvaluationResult. // * Functionality that has no JIT counterpart is omitted: nuw/nsw flags on shifts, exact // divisions and shifts, saturating arithmetic, funnel shifts, min/max, pext/pdep, etc. // @@ -589,24 +590,6 @@ class APInt } }; -// Stand-in for the std::optional results of llvm::KnownBits's comparisons. -struct KnownBool -{ - bool HasValue; - bool Value; - - KnownBool() - : HasValue(false) - , Value(false) - { - } - KnownBool(bool Value) - : HasValue(true) - , Value(Value) - { - } -}; - // Struct for tracking the known zeros and ones of a value. struct KnownBits { @@ -1475,33 +1458,34 @@ struct KnownBits } /// Determine if these known bits always give the same ICMP_EQ result. - static KnownBool eq(const KnownBits& LHS, const KnownBits& RHS) + static RelopEvaluationResult eq(const KnownBits& LHS, const KnownBits& RHS) { if (LHS.isConstant() && RHS.isConstant()) { - return KnownBool(LHS.getConstant() == RHS.getConstant()); + return (LHS.getConstant() == RHS.getConstant()) ? RelopEvaluationResult::True + : RelopEvaluationResult::False; } if (LHS.One.intersects(RHS.Zero) || RHS.One.intersects(LHS.Zero)) { - return KnownBool(false); + return RelopEvaluationResult::False; } - return KnownBool(); + return RelopEvaluationResult::Unknown; } /// Determine if these known bits always give the same ICMP_SGT result. - static KnownBool sgt(const KnownBits& LHS, const KnownBits& RHS) + static RelopEvaluationResult sgt(const KnownBits& LHS, const KnownBits& RHS) { // LHS >s RHS -> false if smax(LHS) <= smax(RHS) if (LHS.getSignedMaxValue().sle(RHS.getSignedMinValue())) { - return KnownBool(false); + return RelopEvaluationResult::False; } // LHS >s RHS -> true if smin(LHS) > smax(RHS) if (LHS.getSignedMinValue().sgt(RHS.getSignedMaxValue())) { - return KnownBool(true); + return RelopEvaluationResult::True; } - return KnownBool(); + return RelopEvaluationResult::Unknown; } /// Update known bits based on ANDing with RHS. @@ -1615,10 +1599,10 @@ struct KnownBitsTracking if (!isKnownNonNegative && NUW) { // mul nuw nsw with a factor > 1 is non-negative. - KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1)); - KnownBool SGT1 = KnownBits::sgt(Known, One); - KnownBool SGT2 = KnownBits::sgt(Known2, One); - isKnownNonNegative = (SGT1.HasValue && SGT1.Value) || (SGT2.HasValue && SGT2.Value); + KnownBits One = KnownBits::makeConstant(APInt(Known.getBitWidth(), 1)); + RelopEvaluationResult SGT1 = KnownBits::sgt(Known, One); + RelopEvaluationResult SGT2 = KnownBits::sgt(Known2, One); + isKnownNonNegative = (SGT1 == RelopEvaluationResult::True) || (SGT2 == RelopEvaluationResult::True); } // The product of a negative number and a non-negative number is either diff --git a/src/coreclr/jit/knownbitsanalysis.cpp b/src/coreclr/jit/knownbitsanalysis.cpp index 8778b31c46877e..7267f5953ba2cf 100644 --- a/src/coreclr/jit/knownbitsanalysis.cpp +++ b/src/coreclr/jit/knownbitsanalysis.cpp @@ -8,15 +8,6 @@ #include "knownbitsanalysis.h" -// The known bits of PHIs, see KnownBitsAnalysis::ComputeForPhi. -struct KnownBitsPhiCache : public JitHashTable, KnownBits> -{ - KnownBitsPhiCache(CompAllocator alloc) - : JitHashTable(alloc) - { - } -}; - //------------------------------------------------------------------------ // Bounds: Create the bounds that the known bits of a value imply. // @@ -136,8 +127,19 @@ KnownBitsAnalysis::KnownBitsAnalysis(Compiler* comp, int phiDepth) , m_vnStore(comp->vnStore) , m_budget(Budget) , m_phiDepth(phiDepth) + , m_maxPhiDepth(MaxPhiDepth) , m_followVNAssertions(true) + , m_followIntPhis(false) { +#ifdef DEBUG + // JIT stress: look deeper (and through 32-bit PHIs) to get more coverage of the analysis. + if (comp->compStressCompile(Compiler::STRESS_KNOWNBITS_BUDGET, 50)) + { + m_budget *= 16; + m_maxPhiDepth *= 4; + m_followIntPhis = true; + } +#endif } //------------------------------------------------------------------------ @@ -150,7 +152,7 @@ KnownBitsAnalysis::KnownBitsAnalysis(Compiler* comp, int phiDepth) // Return Value: // The result of the relop if it's the same for all the values its operands can have. // -KnownBool KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions) +RelopEvaluationResult KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions) { assert(relop->OperIsCompare()); GenTree* const op1 = relop->gtGetOp1(); @@ -161,19 +163,19 @@ KnownBool KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assert const unsigned width = GetWidth(op1->TypeGet()); if ((width == 0) || (GetWidth(op2->TypeGet()) != width) || !op2->IsIntegralConst() || op2->IsIconHandle()) { - return KnownBool(); + return RelopEvaluationResult::Unknown; } const ValueNum op1VN = m_compiler->optConservativeNormalVN(op1); // TP: equality tests are too common to analyze all of them, and we rarely fold // anything but the tests of bit patterns (e.g. flag checks) and casts. - if (relop->OperIs(GT_EQ, GT_NE)) + if (relop->OperIs(GT_EQ, GT_NE) INDEBUG(&&!m_compiler->compStressCompile(Compiler::STRESS_KNOWNBITS_RELOPS, 50))) { VNFuncApp funcApp; if (!m_vnStore->GetVNFunc(op1VN, &funcApp) || !funcApp.FuncIs(VNF_AND, VNF_OR, VNF_XOR, VNF_Cast, VNF_CastOvf)) { - return KnownBool(); + return RelopEvaluationResult::Unknown; } } @@ -181,7 +183,7 @@ KnownBool KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assert const KnownBits known1 = Compute(op1VN, width, assertions, &b1); if (known1.isUnknown() && b1.IsUnknown()) { - return KnownBool(); + return RelopEvaluationResult::Unknown; } const APInt cns(width, (uint64_t)op2->AsIntConCommon()->IntegralValue()); @@ -190,12 +192,17 @@ KnownBool KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assert if (relop->OperIs(GT_EQ, GT_NE)) { - KnownBool isEqual = KnownBits::eq(known1, known2); - if (!isEqual.HasValue && (cns.ult(b1.UMin) || cns.ugt(b1.UMax) || cns.slt(b1.SMin) || cns.sgt(b1.SMax))) + RelopEvaluationResult isEqual = KnownBits::eq(known1, known2); + if ((isEqual == RelopEvaluationResult::Unknown) && + (cns.ult(b1.UMin) || cns.ugt(b1.UMax) || cns.slt(b1.SMin) || cns.sgt(b1.SMax))) { - isEqual = KnownBool(false); + isEqual = RelopEvaluationResult::False; } - return isEqual.HasValue ? KnownBool(isEqual.Value == relop->OperIs(GT_EQ)) : KnownBool(); + if ((isEqual == RelopEvaluationResult::Unknown) || relop->OperIs(GT_EQ)) + { + return isEqual; + } + return (isEqual == RelopEvaluationResult::True) ? RelopEvaluationResult::False : RelopEvaluationResult::True; } // Normalize to "lo < hi" or "lo <= hi". @@ -207,25 +214,25 @@ KnownBool KnownBitsAnalysis::EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assert { if (isStrict ? lo.UMax.ult(hi.UMin) : lo.UMax.ule(hi.UMin)) { - return KnownBool(true); + return RelopEvaluationResult::True; } if (isStrict ? lo.UMin.uge(hi.UMax) : lo.UMin.ugt(hi.UMax)) { - return KnownBool(false); + return RelopEvaluationResult::False; } } else { if (isStrict ? lo.SMax.slt(hi.SMin) : lo.SMax.sle(hi.SMin)) { - return KnownBool(true); + return RelopEvaluationResult::True; } if (isStrict ? lo.SMin.sge(hi.SMax) : lo.SMin.sgt(hi.SMax)) { - return KnownBool(false); + return RelopEvaluationResult::False; } } - return KnownBool(); + return RelopEvaluationResult::Unknown; } //------------------------------------------------------------------------ @@ -305,7 +312,7 @@ KnownBits KnownBitsAnalysis::Compute(ValueNum vn, unsigned width, ASSERT_VALARG_ { known = known.unionWith(ComputeForFunc(funcApp, width, assertions)); } - else if ((width == 64) && m_vnStore->IsPhiDef(vn)) + else if (((width == 64) || m_followIntPhis) && m_vnStore->IsPhiDef(vn)) { // TP: PHIs are expensive, and RangeCheck::GetRangeFromAssertions already looks through // them for 32-bit values, so we only do it for the 64-bit ones. @@ -353,10 +360,10 @@ KnownBits KnownBitsAnalysis::ComputeForPhi(ValueNum vn, unsigned width) { if (m_compiler->optKnownBitsPhiCache == nullptr) { - m_compiler->optKnownBitsPhiCache = - new (m_compiler, CMK_AssertionProp) KnownBitsPhiCache(m_compiler->getAllocator(CMK_AssertionProp)); + m_compiler->optKnownBitsPhiCache = new (m_compiler, CMK_AssertionProp) + Compiler::KnownBitsPhiCache(m_compiler->getAllocator(CMK_AssertionProp)); } - KnownBitsPhiCache* const cache = m_compiler->optKnownBitsPhiCache; + Compiler::KnownBitsPhiCache* const cache = m_compiler->optKnownBitsPhiCache; KnownBits result(width); const KnownBits* cached = cache->LookupPointer(vn); @@ -366,7 +373,7 @@ KnownBits KnownBitsAnalysis::ComputeForPhi(ValueNum vn, unsigned width) return cached->hasConflict() ? result : *cached; } - if (m_phiDepth >= MaxPhiDepth) + if (m_phiDepth >= m_maxPhiDepth) { return result; } @@ -386,7 +393,8 @@ KnownBits KnownBitsAnalysis::ComputeForPhi(ValueNum vn, unsigned width) result.resetAll(); } - cache->Set(vn, result, KnownBitsPhiCache::Overwrite); + // Replace the "being computed" marker set above. + cache->Set(vn, result, Compiler::KnownBitsPhiCache::Overwrite); return result; } @@ -498,10 +506,17 @@ KnownBits KnownBitsAnalysis::ComputeForFunc(const VNFuncApp& funcApp, unsigned w case VNF_RSH: case VNF_RSZ: { - KnownBits amount = Compute(funcApp.GetArg(1), 32, assertions); -#ifdef TARGET_64BIT - // The shift amount is masked. - amount = amount & KnownBits::makeConstant(APInt(32, width - 1)); + // The shift amount can be a native int. + const ValueNum amountVN = funcApp.GetArg(1); + const unsigned amountWidth = GetWidth(m_vnStore->TypeOfVN(amountVN)); + if (amountWidth == 0) + { + break; + } + KnownBits amount = Compute(amountVN, amountWidth, assertions); +#if TARGET_MASKS_SHIFTS + // The shift amount is masked, only its low bits matter. + amount = amount.trunc(32) & KnownBits::makeConstant(APInt(32, width - 1)); #else if (amount.getMaxValue().getZExtValue() >= width) { @@ -589,8 +604,9 @@ KnownBits KnownBitsAnalysis::ComputeForFunc(const VNFuncApp& funcApp, unsigned w } //------------------------------------------------------------------------ -// MergeAssertions: Refine the known bits and the bounds of a value number using -// the "vn relop cns" and "vn relop otherVN" assertions. +// MergeAssertions: Refine the known bits and the bounds of a value number using the +// "vn relop cns" and "vn relop otherVN" assertions. For the latter, the facts about +// "otherVN" come from its shape and its own "otherVN relop cns" assertions. // // Arguments: // vn - the value number @@ -607,15 +623,12 @@ void KnownBitsAnalysis::MergeAssertions( return; } - BitVecOps::Iter iter(m_compiler->apTraits, assertions); - unsigned index = 0; - while (iter.NextElem(&index)) - { + BitVecOps::VisitBits(m_compiler->apTraits, assertions, [&](unsigned index) { const Compiler::AssertionDsc& assertion = m_compiler->optGetAssertion(GetAssertionIndex(index)); if (!assertion.GetOp1().KindIs(Compiler::O1K_VN) || (assertion.GetOp1().GetVN() != vn) || assertion.KindIs(Compiler::OAK_NOT_EQUAL)) { - continue; + return true; } const auto& op2 = assertion.GetOp2(); @@ -645,7 +658,8 @@ void KnownBitsAnalysis::MergeAssertions( *pKnown = pKnown->unionWith(other); } } - } + return true; + }); pBounds->Normalize(); if (pBounds->UMin.ule(pBounds->UMax)) diff --git a/src/coreclr/jit/knownbitsanalysis.h b/src/coreclr/jit/knownbitsanalysis.h index 57e1e85f544a89..b83f8731087643 100644 --- a/src/coreclr/jit/knownbitsanalysis.h +++ b/src/coreclr/jit/knownbitsanalysis.h @@ -33,7 +33,9 @@ class KnownBitsAnalysis ValueNumStore* m_vnStore; int m_budget; int m_phiDepth; + int m_maxPhiDepth; bool m_followVNAssertions; // whether to use "vn relop otherVN" assertions + bool m_followIntPhis; // whether to look through 32-bit PHIs // Unsigned and signed bounds of a value. struct Bounds @@ -62,5 +64,5 @@ class KnownBitsAnalysis // Not to be inlined (LTCG does that): this is called from a hot path of the assertion // propagation where it rarely has anything to do, having it inlined there costs TP. - NOINLINE KnownBool EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions); + NOINLINE RelopEvaluationResult EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions); }; From 03a5fa3abaf2788785cc3df8617474614012f0a3 Mon Sep 17 00:00:00 2001 From: Egor Bogatov Date: Wed, 25 Nov 2026 17:35:20 +0100 Subject: [PATCH 3/3] Remove NOINLINE from KnownBitsAnalysis::EvalRelop Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: acaabbe4-a3ed-45ef-838d-d23718212f6e --- src/coreclr/jit/knownbitsanalysis.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/coreclr/jit/knownbitsanalysis.h b/src/coreclr/jit/knownbitsanalysis.h index b83f8731087643..2028c269565a70 100644 --- a/src/coreclr/jit/knownbitsanalysis.h +++ b/src/coreclr/jit/knownbitsanalysis.h @@ -62,7 +62,5 @@ class KnownBitsAnalysis public: KnownBitsAnalysis(Compiler* comp, int phiDepth = 0); - // Not to be inlined (LTCG does that): this is called from a hot path of the assertion - // propagation where it rarely has anything to do, having it inlined there costs TP. - NOINLINE RelopEvaluationResult EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions); + RelopEvaluationResult EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions); };