From 6a46c6c865270ceb01bcaef4a2e4c8df56a8800a Mon Sep 17 00:00:00 2001 From: LU-JOHN Date: Wed, 2 Apr 2025 22:17:14 -0500 Subject: [PATCH] Ensure KnownBits passed when calculating from range md has right size (#132985) KnownBits passed to computeKnownBitsFromRangeMetadata must have the same bit width as the range metadata bit width. Otherwise the calculated results will be incorrect. --------- Signed-off-by: John Lu --- llvm/lib/Analysis/ValueTracking.cpp | 4 ++++ llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp index fc0c74942c6d..3b0249f91d6d 100644 --- a/llvm/lib/Analysis/ValueTracking.cpp +++ b/llvm/lib/Analysis/ValueTracking.cpp @@ -430,6 +430,10 @@ void llvm::computeKnownBitsFromRangeMetadata(const MDNode &Ranges, ConstantInt *Upper = mdconst::extract(Ranges.getOperand(2 * i + 1)); ConstantRange Range(Lower->getValue(), Upper->getValue()); + // BitWidth must equal the Ranges BitWidth for the correct number of high + // bits to be set. + assert(BitWidth == Range.getBitWidth() && + "Known bit width must match range bit width!"); // The first CommonPrefixBits of all values in Range are equal. unsigned CommonPrefixBits = diff --git a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp index 3526beeb312c..69548d046231 100644 --- a/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp +++ b/llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp @@ -9176,6 +9176,12 @@ SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType, "Cannot use an ext load to change the number of vector elements!"); } + assert((!MMO->getRanges() || + (mdconst::extract(MMO->getRanges()->getOperand(0)) + ->getBitWidth() == MemVT.getScalarSizeInBits() && + MemVT.isInteger())) && + "Range metadata and load type must match!"); + bool Indexed = AM != ISD::UNINDEXED; assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");