Skip to content

Commit

Permalink
[APInt] Assert correct values in APInt constructor
Browse files Browse the repository at this point in the history
If the uint64_t constructor is used, assert that the value is
actuall a signed or unsigned N-bit integer depending on whether
the isSigned flag is set.

Currently, we allow values to be silently truncated, which is
a constant source of subtle bugs -- a particularly common mistake
is to create -1 values without setting the isSigned flag, which
will work fine for all common bit widths (<= 64-bit) and miscompile
for larger integers.
  • Loading branch information
nikic committed Feb 2, 2024
1 parent 62ae7d9 commit 506aaa1
Show file tree
Hide file tree
Showing 22 changed files with 346 additions and 313 deletions.
4 changes: 3 additions & 1 deletion llvm/include/llvm/ADT/APFixedPoint.h
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,9 @@ class APFixedPoint {
}

APFixedPoint(uint64_t Val, const FixedPointSemantics &Sema)
: APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned()), Sema) {}
: APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned(),
/*implicitTrunc*/ true),
Sema) {}

// Zero initialization.
APFixedPoint(const FixedPointSemantics &Sema) : APFixedPoint(0, Sema) {}
Expand Down
19 changes: 17 additions & 2 deletions llvm/include/llvm/ADT/APInt.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,26 @@ class [[nodiscard]] APInt {
/// \param numBits the bit width of the constructed APInt
/// \param val the initial value of the APInt
/// \param isSigned how to treat signedness of val
APInt(unsigned numBits, uint64_t val, bool isSigned = false)
/// \param implicitTrunc allow implicit truncation of non-zero/sign bits of
/// val beyond the range of numBits
APInt(unsigned numBits, uint64_t val, bool isSigned = false,
bool implicitTrunc = false)
: BitWidth(numBits) {
if (!implicitTrunc) {
if (BitWidth == 0) {
assert(val == 0 && "Value must be zero for 0-bit APInt");
} else if (isSigned) {
assert(llvm::isIntN(BitWidth, val) &&
"Value is not an N-bit signed value");
} else {
assert(llvm::isUIntN(BitWidth, val) &&
"Value is not an N-bit unsigned value");
}
}
if (isSingleWord()) {
U.VAL = val;
clearUnusedBits();
if (implicitTrunc || isSigned)
clearUnusedBits();
} else {
initSlowCase(val, isSigned);
}
Expand Down
8 changes: 5 additions & 3 deletions llvm/lib/Analysis/ConstantFolding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -889,7 +889,8 @@ Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
APInt Offset = APInt(
BitWidth,
DL.getIndexedOffsetInType(
SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)));
SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)),
/*isSigned*/ true, /*implicitTrunc*/ true);

// If this is a GEP of a GEP, fold it all into a single GEP.
while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Expand Down Expand Up @@ -3322,8 +3323,9 @@ ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {

// The exponent is an "unspecified value" for inf/nan. We use zero to avoid
// using undef.
Constant *Result1 = FrexpMant.isFinite() ? ConstantInt::get(IntTy, FrexpExp)
: ConstantInt::getNullValue(IntTy);
Constant *Result1 = FrexpMant.isFinite()
? ConstantInt::getSigned(IntTy, FrexpExp)
: ConstantInt::getNullValue(IntTy);
return {Result0, Result1};
}

Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4542,7 +4542,7 @@ OpenMPIRBuilder::createTargetInit(const LocationDescription &Loc, bool IsSPMD,
Builder.CreateCall(Fn, {KernelEnvironment, KernelLaunchEnvironment});

Value *ExecUserCode = Builder.CreateICmpEQ(
ThreadKind, ConstantInt::get(ThreadKind->getType(), -1),
ThreadKind, Constant::getAllOnesValue(ThreadKind->getType()),
"exec_user_code");

// ThreadKind = __kmpc_target_init(...)
Expand Down
3 changes: 2 additions & 1 deletion llvm/lib/FuzzMutate/OpDescriptor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ void fuzzerop::makeConstantsWithType(Type *T, std::vector<Constant *> &Cs) {
uint64_t W = IntTy->getBitWidth();
Cs.push_back(ConstantInt::get(IntTy, 0));
Cs.push_back(ConstantInt::get(IntTy, 1));
Cs.push_back(ConstantInt::get(IntTy, 42));
Cs.push_back(ConstantInt::get(
IntTy, APInt(W, 42, /*isSigned*/ false, /*implicitTrunc*/ true)));
Cs.push_back(ConstantInt::get(IntTy, APInt::getMaxValue(W)));
Cs.push_back(ConstantInt::get(IntTy, APInt::getMinValue(W)));
Cs.push_back(ConstantInt::get(IntTy, APInt::getSignedMaxValue(W)));
Expand Down
6 changes: 3 additions & 3 deletions llvm/lib/IR/ConstantRange.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1743,7 +1743,7 @@ ConstantRange ConstantRange::ctlz(bool ZeroIsPoison) const {
// Zero is either safe or not in the range. The output range is composed by
// the result of countLeadingZero of the two extremes.
return getNonEmpty(APInt(getBitWidth(), getUnsignedMax().countl_zero()),
APInt(getBitWidth(), getUnsignedMin().countl_zero() + 1));
APInt(getBitWidth(), getUnsignedMin().countl_zero()) + 1);
}

static ConstantRange getUnsignedCountTrailingZerosRange(const APInt &Lower,
Expand Down Expand Up @@ -1802,7 +1802,7 @@ ConstantRange ConstantRange::cttz(bool ZeroIsPoison) const {
}

if (isFullSet())
return getNonEmpty(Zero, APInt(BitWidth, BitWidth + 1));
return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
if (!isWrappedSet())
return getUnsignedCountTrailingZerosRange(Lower, Upper);
// The range is wrapped. We decompose it into two ranges, [0, Upper) and
Expand Down Expand Up @@ -1847,7 +1847,7 @@ ConstantRange ConstantRange::ctpop() const {
unsigned BitWidth = getBitWidth();
APInt Zero = APInt::getZero(BitWidth);
if (isFullSet())
return getNonEmpty(Zero, APInt(BitWidth, BitWidth + 1));
return getNonEmpty(Zero, APInt(BitWidth, BitWidth) + 1);
if (!isWrappedSet())
return getUnsignedPopCountRange(Lower, Upper);
// The range is wrapped. We decompose it into two ranges, [0, Upper) and
Expand Down
14 changes: 9 additions & 5 deletions llvm/lib/Support/APInt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,8 @@ APInt& APInt::operator-=(uint64_t RHS) {
APInt APInt::operator*(const APInt& RHS) const {
assert(BitWidth == RHS.BitWidth && "Bit widths must be the same");
if (isSingleWord())
return APInt(BitWidth, U.VAL * RHS.U.VAL);
return APInt(BitWidth, U.VAL * RHS.U.VAL, /*isSigned*/ false,
/*implicitTrunc*/ true);

APInt Result(getMemory(getNumWords()), getBitWidth());
tcMultiply(Result.U.pVal, U.pVal, RHS.U.pVal, getNumWords());
Expand Down Expand Up @@ -455,15 +456,17 @@ APInt APInt::extractBits(unsigned numBits, unsigned bitPosition) const {
"Illegal bit extraction");

if (isSingleWord())
return APInt(numBits, U.VAL >> bitPosition);
return APInt(numBits, U.VAL >> bitPosition, /*isSigned*/ false,
/*implicitTrunc*/ true);

unsigned loBit = whichBit(bitPosition);
unsigned loWord = whichWord(bitPosition);
unsigned hiWord = whichWord(bitPosition + numBits - 1);

// Single word result extracting bits from a single word source.
if (loWord == hiWord)
return APInt(numBits, U.pVal[loWord] >> loBit);
return APInt(numBits, U.pVal[loWord] >> loBit, /*isSigned*/ false,
/*implicitTrunc*/ true);

// Extracting bits that start on a source word boundary can be done
// as a fast memory copy.
Expand Down Expand Up @@ -907,7 +910,8 @@ APInt APInt::trunc(unsigned width) const {
assert(width <= BitWidth && "Invalid APInt Truncate request");

if (width <= APINT_BITS_PER_WORD)
return APInt(width, getRawData()[0]);
return APInt(width, getRawData()[0], /*isSigned*/ false,
/*implicitTrunc*/ true);

if (width == BitWidth)
return *this;
Expand Down Expand Up @@ -955,7 +959,7 @@ APInt APInt::sext(unsigned Width) const {
assert(Width >= BitWidth && "Invalid APInt SignExtend request");

if (Width <= APINT_BITS_PER_WORD)
return APInt(Width, SignExtend64(U.VAL, BitWidth));
return APInt(Width, SignExtend64(U.VAL, BitWidth), /*isSigned*/ true);

if (Width == BitWidth)
return *this;
Expand Down
2 changes: 1 addition & 1 deletion llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
DL.getTypeAllocSize(Init->getType()->getArrayElementType());
auto MaskIdx = [&](Value *Idx) {
if (!GEP->isInBounds() && llvm::countr_zero(ElementSize) != 0) {
Value *Mask = ConstantInt::get(Idx->getType(), -1);
Value *Mask = Constant::getAllOnesValue(Idx->getType());
Mask = Builder.CreateLShr(Mask, llvm::countr_zero(ElementSize));
Idx = Builder.CreateAnd(Idx, Mask);
}
Expand Down
8 changes: 4 additions & 4 deletions llvm/lib/Transforms/InstCombine/InstCombineSelect.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -665,11 +665,11 @@ static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal,
Value *X, *Y;
unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits();
if ((Pred != ICmpInst::ICMP_SGT ||
!match(CmpRHS,
m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) &&
!match(CmpRHS, m_SpecificInt_ICMP(ICmpInst::ICMP_SGE,
APInt::getAllOnes(Bitwidth)))) &&
(Pred != ICmpInst::ICMP_SLT ||
!match(CmpRHS,
m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0)))))
!match(CmpRHS, m_SpecificInt_ICMP(ICmpInst::ICMP_SGE,
APInt::getZero(Bitwidth)))))
return nullptr;

// Canonicalize so that ashr is in FalseVal.
Expand Down
10 changes: 6 additions & 4 deletions llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ static Value *convertStrToInt(CallInst *CI, StringRef &Str, Value *EndPtr,
// Unsigned negation doesn't overflow.
Result = -Result;

return ConstantInt::get(RetTy, Result);
return ConstantInt::get(RetTy, Result, AsSigned);
}

static bool isOnlyUsedInComparisonWithZero(Value *V) {
Expand Down Expand Up @@ -553,7 +553,8 @@ Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilderBase &B) {
// strcmp(x, y) -> cnst (if both x and y are constant strings)
if (HasStr1 && HasStr2)
return ConstantInt::get(CI->getType(),
std::clamp(Str1.compare(Str2), -1, 1));
std::clamp(Str1.compare(Str2), -1, 1),
/*isSigned*/ true);

if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
return B.CreateNeg(B.CreateZExt(
Expand Down Expand Up @@ -638,7 +639,8 @@ Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilderBase &B) {
StringRef SubStr1 = substr(Str1, Length);
StringRef SubStr2 = substr(Str2, Length);
return ConstantInt::get(CI->getType(),
std::clamp(SubStr1.compare(SubStr2), -1, 1));
std::clamp(SubStr1.compare(SubStr2), -1, 1),
/*isSigned*/ true);
}

if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
Expand Down Expand Up @@ -1518,7 +1520,7 @@ static Value *optimizeMemCmpVarSize(CallInst *CI, Value *LHS, Value *RHS,
int IRes = UChar(LStr[Pos]) < UChar(RStr[Pos]) ? -1 : 1;
Value *MaxSize = ConstantInt::get(Size->getType(), Pos);
Value *Cmp = B.CreateICmp(ICmpInst::ICMP_ULE, Size, MaxSize);
Value *Res = ConstantInt::get(CI->getType(), IRes);
Value *Res = ConstantInt::get(CI->getType(), IRes, /*isSigned*/ true);
return B.CreateSelect(Cmp, Zero, Res);
}

Expand Down
9 changes: 5 additions & 4 deletions llvm/unittests/ADT/APFixedPointTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -240,27 +240,28 @@ void CheckIntPart(const FixedPointSemantics &Sema, int64_t IntPart) {
APFixedPoint ValWithFract(
APInt(Sema.getWidth(),
relativeShr(IntPart, Sema.getLsbWeight()) + FullFactPart,
Sema.isSigned()),
Sema.isSigned(), /*implicitTrunc*/ true),
Sema);
ASSERT_EQ(ValWithFract.getIntPart(), IntPart);

// Just fraction
APFixedPoint JustFract(APInt(Sema.getWidth(), FullFactPart, Sema.isSigned()),
APFixedPoint JustFract(APInt(Sema.getWidth(), FullFactPart, Sema.isSigned(),
/*implicitTrunc*/ true),
Sema);
ASSERT_EQ(JustFract.getIntPart(), 0);

// Whole number
APFixedPoint WholeNum(APInt(Sema.getWidth(),
relativeShr(IntPart, Sema.getLsbWeight()),
Sema.isSigned()),
Sema.isSigned(), /*implicitTrunc*/ true),
Sema);
ASSERT_EQ(WholeNum.getIntPart(), IntPart);

// Negative
if (Sema.isSigned()) {
APFixedPoint Negative(APInt(Sema.getWidth(),
relativeShr(IntPart, Sema.getLsbWeight()),
Sema.isSigned()),
Sema.isSigned(), /*implicitTrunc*/ true),
Sema);
ASSERT_EQ(Negative.getIntPart(), IntPart);
}
Expand Down
Loading

0 comments on commit 506aaa1

Please sign in to comment.