diff --git a/clang/lib/AST/Interp/Integral.h b/clang/lib/AST/Interp/Integral.h index 932caca29b9f0e..cc7c7a9d2430ee 100644 --- a/clang/lib/AST/Interp/Integral.h +++ b/clang/lib/AST/Interp/Integral.h @@ -223,6 +223,9 @@ template class Integral final { } static bool neg(Integral A, Integral *R) { + if (Signed && A.isMin()) + return true; + *R = -A; return false; } diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h index 152a876a429645..7b80bb96499163 100644 --- a/clang/lib/AST/Interp/Interp.h +++ b/clang/lib/AST/Interp/Interp.h @@ -413,12 +413,32 @@ bool Inv(InterpState &S, CodePtr OpPC) { template ::T> bool Neg(InterpState &S, CodePtr OpPC) { - const T &Val = S.Stk.pop(); + const T &Value = S.Stk.pop(); T Result; - T::neg(Val, &Result); + if (!T::neg(Value, &Result)) { + S.Stk.push(Result); + return true; + } + + assert(isIntegralType(Name) && + "don't expect other types to fail at constexpr negation"); S.Stk.push(Result); - return true; + + APSInt NegatedValue = -Value.toAPSInt(Value.bitWidth() + 1); + const Expr *E = S.Current->getExpr(OpPC); + QualType Type = E->getType(); + + if (S.checkingForUndefinedBehavior()) { + SmallString<32> Trunc; + NegatedValue.trunc(Result.bitWidth()).toString(Trunc, 10); + auto Loc = E->getExprLoc(); + S.report(Loc, diag::warn_integer_constant_overflow) << Trunc << Type; + return true; + } + + S.CCEDiag(E, diag::note_constexpr_overflow) << NegatedValue << Type; + return S.noteUndefinedBehavior(); } enum class PushVal : bool { diff --git a/clang/lib/AST/Interp/PrimType.h b/clang/lib/AST/Interp/PrimType.h index 30bec3f2a17cfe..693e57210608d9 100644 --- a/clang/lib/AST/Interp/PrimType.h +++ b/clang/lib/AST/Interp/PrimType.h @@ -42,6 +42,8 @@ enum PrimType : unsigned { PT_FnPtr, }; +constexpr bool isIntegralType(PrimType T) { return T <= PT_Uint64; } + /// Mapping from primitive types to their representation. template struct PrimConv; template <> struct PrimConv { using T = Integral<8, true>; }; diff --git a/clang/test/AST/Interp/literals.cpp b/clang/test/AST/Interp/literals.cpp index 598d748c266b48..acad760bc43ee9 100644 --- a/clang/test/AST/Interp/literals.cpp +++ b/clang/test/AST/Interp/literals.cpp @@ -80,6 +80,12 @@ static_assert(~255 == -256, ""); static_assert(~INT_MIN == INT_MAX, ""); static_assert(~INT_MAX == INT_MIN, ""); +static_assert(-(1 << 31), ""); // expected-error {{not an integral constant expression}} \ + // expected-note {{outside the range of representable values}} \ + // ref-error {{not an integral constant expression}} \ + // ref-note {{outside the range of representable values}} \ + + enum E {}; constexpr E e = static_cast(0); static_assert(~e == -1, "");