Skip to content

Commit f5cc0bf

Browse files
committed
[APInt] Assert correct values in APInt constructor
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.
1 parent 7f09aa9 commit f5cc0bf

37 files changed

+388
-348
lines changed

llvm/include/llvm/ADT/APFixedPoint.h

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,9 @@ class APFixedPoint {
160160
}
161161

162162
APFixedPoint(uint64_t Val, const FixedPointSemantics &Sema)
163-
: APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned()), Sema) {}
163+
: APFixedPoint(APInt(Sema.getWidth(), Val, Sema.isSigned(),
164+
/*implicitTrunc*/ true),
165+
Sema) {}
164166

165167
// Zero initialization.
166168
APFixedPoint(const FixedPointSemantics &Sema) : APFixedPoint(0, Sema) {}

llvm/include/llvm/ADT/APInt.h

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,11 +107,26 @@ class [[nodiscard]] APInt {
107107
/// \param numBits the bit width of the constructed APInt
108108
/// \param val the initial value of the APInt
109109
/// \param isSigned how to treat signedness of val
110-
APInt(unsigned numBits, uint64_t val, bool isSigned = false)
110+
/// \param implicitTrunc allow implicit truncation of non-zero/sign bits of
111+
/// val beyond the range of numBits
112+
APInt(unsigned numBits, uint64_t val, bool isSigned = false,
113+
bool implicitTrunc = false)
111114
: BitWidth(numBits) {
115+
if (!implicitTrunc) {
116+
if (BitWidth == 0) {
117+
assert(val == 0 && "Value must be zero for 0-bit APInt");
118+
} else if (isSigned) {
119+
assert(llvm::isIntN(BitWidth, val) &&
120+
"Value is not an N-bit signed value");
121+
} else {
122+
assert(llvm::isUIntN(BitWidth, val) &&
123+
"Value is not an N-bit unsigned value");
124+
}
125+
}
112126
if (isSingleWord()) {
113127
U.VAL = val;
114-
clearUnusedBits();
128+
if (implicitTrunc || isSigned)
129+
clearUnusedBits();
115130
} else {
116131
initSlowCase(val, isSigned);
117132
}

llvm/lib/Analysis/ConstantFolding.cpp

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -889,7 +889,8 @@ Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
889889
APInt Offset = APInt(
890890
BitWidth,
891891
DL.getIndexedOffsetInType(
892-
SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)));
892+
SrcElemTy, ArrayRef((Value *const *)Ops.data() + 1, Ops.size() - 1)),
893+
/*isSigned*/ true, /*implicitTrunc*/ true);
893894

894895
std::optional<ConstantRange> InRange = GEP->getInRange();
895896
if (InRange)
@@ -3401,8 +3402,9 @@ ConstantFoldScalarFrexpCall(Constant *Op, Type *IntTy) {
34013402

34023403
// The exponent is an "unspecified value" for inf/nan. We use zero to avoid
34033404
// using undef.
3404-
Constant *Result1 = FrexpMant.isFinite() ? ConstantInt::get(IntTy, FrexpExp)
3405-
: ConstantInt::getNullValue(IntTy);
3405+
Constant *Result1 = FrexpMant.isFinite()
3406+
? ConstantInt::getSigned(IntTy, FrexpExp)
3407+
: ConstantInt::getNullValue(IntTy);
34063408
return {Result0, Result1};
34073409
}
34083410

llvm/lib/Analysis/MemoryBuiltins.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -675,7 +675,7 @@ Value *llvm::lowerObjectSizeCall(
675675
if (!MustSucceed)
676676
return nullptr;
677677

678-
return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0);
678+
return ConstantInt::get(ResultType, MaxVal ? -1ULL : 0, true);
679679
}
680680

681681
STATISTIC(ObjectVisitorArgument,

llvm/lib/Analysis/ScalarEvolution.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1460,7 +1460,7 @@ bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
14601460

14611461
APInt StartAI = StartC->getAPInt();
14621462

1463-
for (unsigned Delta : {-2, -1, 1, 2}) {
1463+
for (int Delta : {-2, -1, 1, 2}) {
14641464
const SCEV *PreStart = getConstant(StartAI - Delta);
14651465

14661466
FoldingSetNodeID ID;
@@ -1475,7 +1475,7 @@ bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
14751475
// Give up if we don't already have the add recurrence we need because
14761476
// actually constructing an add recurrence is relatively expensive.
14771477
if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1478-
const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1478+
const SCEV *DeltaS = getConstant(StartC->getType(), Delta, true);
14791479
ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
14801480
const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
14811481
DeltaS, &Pred, this);

llvm/lib/Analysis/ValueTracking.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9303,7 +9303,7 @@ static ConstantRange getRangeForIntrinsic(const IntrinsicInst &II) {
93039303
case Intrinsic::cttz:
93049304
// Maximum of set/clear bits is the bit width.
93059305
return ConstantRange::getNonEmpty(APInt::getZero(Width),
9306-
APInt(Width, Width + 1));
9306+
APInt(Width, Width) + 1);
93079307
case Intrinsic::uadd_sat:
93089308
// uadd.sat(x, C) produces [C, UINT_MAX].
93099309
if (match(II.getOperand(0), m_APInt(C)) ||
@@ -9454,7 +9454,7 @@ static void setLimitForFPToI(const Instruction *I, APInt &Lower, APInt &Upper) {
94549454
if (!I->getOperand(0)->getType()->getScalarType()->isHalfTy())
94559455
return;
94569456
if (isa<FPToSIInst>(I) && BitWidth >= 17) {
9457-
Lower = APInt(BitWidth, -65504);
9457+
Lower = APInt(BitWidth, -65504, true);
94589458
Upper = APInt(BitWidth, 65505);
94599459
}
94609460

llvm/lib/Bitcode/Reader/BitcodeReader.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3147,7 +3147,7 @@ Error BitcodeReader::parseConstants() {
31473147
case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
31483148
if (!CurTy->isIntOrIntVectorTy() || Record.empty())
31493149
return error("Invalid integer const record");
3150-
V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
3150+
V = ConstantInt::getSigned(CurTy, decodeSignRotatedValue(Record[0]));
31513151
break;
31523152
case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
31533153
if (!CurTy->isIntOrIntVectorTy() || Record.empty())

llvm/lib/CodeGen/CodeGenPrepare.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1643,7 +1643,7 @@ static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
16431643
if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
16441644
B = ConstantInt::get(B->getType(), 1);
16451645
else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
1646-
B = ConstantInt::get(B->getType(), -1);
1646+
B = Constant::getAllOnesValue(B->getType());
16471647
else
16481648
return false;
16491649

llvm/lib/CodeGen/ExpandMemCmp.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -590,7 +590,7 @@ void MemCmpExpansion::emitMemCmpResultBlock() {
590590
ResBlock.PhiSrc2);
591591

592592
Value *Res =
593-
Builder.CreateSelect(Cmp, ConstantInt::get(Builder.getInt32Ty(), -1),
593+
Builder.CreateSelect(Cmp, Constant::getAllOnesValue(Builder.getInt32Ty()),
594594
ConstantInt::get(Builder.getInt32Ty(), 1));
595595

596596
PhiRes->addIncoming(Res, ResBlock.BB);

llvm/lib/CodeGen/SelectionDAG/SelectionDAG.cpp

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1625,7 +1625,10 @@ SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
16251625
assert((EltVT.getSizeInBits() >= 64 ||
16261626
(uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
16271627
"getConstant with a uint64_t value that doesn't fit in the type!");
1628-
return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1628+
// TODO: Avoid implicit trunc?
1629+
return getConstant(
1630+
APInt(EltVT.getSizeInBits(), Val, false, /*implicitTrunc*/ true), DL, VT,
1631+
isT, isO);
16291632
}
16301633

16311634
SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,

0 commit comments

Comments
 (0)