Author: Matt Arsenault Date: 2026-11-13T11:57:52-08:00 New Revision: 3731fb66d4603c8f51e4984ff958a571b9393364
URL: https://github.com/llvm/llvm-project/commit/3731fb66d4603c8f51e4984ff958a571b9393364 DIFF: https://github.com/llvm/llvm-project/commit/3731fb66d4603c8f51e4984ff958a571b9393364.diff LOG: clang: Add ArgRange builtin attribute for constant argument ranges (#241583) Many target builtins take constant arguments that must be in a specific range. These usually correspond directly to the Range annotation on the IR intrinsic, which the verifier enforces. Today this requires manual verification with a large builtin ID switch in Sema, and missed cases will emit code that fails the IR verifier. Add an ArgRange<Index, Lo, Hi> builtin attribute declaring that a _Constant argument must be in the half-open range [Lo, Hi), the same as the IR declaration. Co-authored-by: Claude Opus 5.5 <[email protected]> Added: clang/test/TableGen/builtin-arg-range.td Modified: clang/include/clang/Basic/Builtins.def clang/include/clang/Basic/Builtins.h clang/include/clang/Basic/BuiltinsBase.td clang/lib/Basic/Builtins.cpp clang/lib/Sema/SemaChecking.cpp clang/utils/TableGen/ClangBuiltinsEmitter.cpp Removed: ################################################################################ diff --git a/clang/include/clang/Basic/Builtins.def b/clang/include/clang/Basic/Builtins.def index 77fca0a7ad8c1..dca024ebd2804 100644 --- a/clang/include/clang/Basic/Builtins.def +++ b/clang/include/clang/Basic/Builtins.def @@ -104,6 +104,8 @@ // V:{num}: -> requires vectors of at least {num} bits to be legal // C<{num},M_0,...,M_k> -> callback behavior: argument {num} is called with // argument M_0, ..., M_k as payload +// R<{num}:{lo}:{hi},...> -> constant argument {num} must be in [{lo}, {hi}) +// (half-open, matching the IR range attribute) // z -> this is a function in (possibly-versioned) namespace std // E -> this function can be constant evaluated by Clang frontend // G -> this is a C++20 consteval function diff --git a/clang/include/clang/Basic/Builtins.h b/clang/include/clang/Basic/Builtins.h index f6e279ad829c8..0420b5547a568 100644 --- a/clang/include/clang/Basic/Builtins.h +++ b/clang/include/clang/Basic/Builtins.h @@ -402,6 +402,16 @@ class Context { bool performsCallback(unsigned ID, llvm::SmallVectorImpl<int> &Encoding) const; + /// A constant argument that must be in the half-open range [Lower, Upper). + struct ArgRange { + unsigned Index; + int Lower; + int Upper; + }; + + /// Append the constant argument ranges of this builtin into \p Ranges. + void getArgRanges(unsigned ID, llvm::SmallVectorImpl<ArgRange> &Ranges) const; + /// Return true if this builtin has parameters that must be non-null. /// The parameter indices are appended into 'Indxs'. bool isNonNull(unsigned ID, llvm::SmallVectorImpl<int> &Indxs, diff --git a/clang/include/clang/Basic/BuiltinsBase.td b/clang/include/clang/Basic/BuiltinsBase.td index 1f34374148363..86ead09e99aba 100644 --- a/clang/include/clang/Basic/BuiltinsBase.td +++ b/clang/include/clang/Basic/BuiltinsBase.td @@ -100,6 +100,14 @@ def Consteval : Attribute<"EG">; // indicated by the remaining indices. class Callback<list<int> ArgIndices> : MultiIndexAttribute<"C", ArgIndices>; +// The _Constant argument at index I must be in the half-open range [Lo, Hi), +// matching the IR intrinsic range attribute. +class ArgRange<int I, int Lo, int Hi> : Attribute<"R"> { + int Index = I; + int Lower = Lo; + int Upper = Hi; +} + // Prefixes // ======== diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp index b854f47a6b26b..7ea55b268cf8f 100644 --- a/clang/lib/Basic/Builtins.cpp +++ b/clang/lib/Basic/Builtins.cpp @@ -451,6 +451,29 @@ bool Builtin::Context::isNonNull(unsigned ID, llvm::SmallVectorImpl<int> &Indxs, return true; } +void Builtin::Context::getArgRanges( + unsigned ID, llvm::SmallVectorImpl<ArgRange> &Ranges) const { + StringRef Attrs = getAttributesString(ID); + size_t Pos = Attrs.find('R'); + if (Pos == StringRef::npos) + return; + + StringRef Str = Attrs.drop_front(Pos + 1); + if (!Str.consume_front("<")) + llvm_unreachable("Expected '<' to start range list"); + + do { + ArgRange Range; + if (Str.consumeInteger(10, Range.Index) || !Str.consume_front(":") || + Str.consumeInteger(10, Range.Lower) || !Str.consume_front(":") || + Str.consumeInteger(10, Range.Upper)) + llvm_unreachable("Malformed argument range"); + Ranges.push_back(Range); + } while (Str.consume_front(",")); + + assert(Str.starts_with('>') && "Range list must end with '>'"); +} + bool Builtin::Context::performsCallback(unsigned ID, SmallVectorImpl<int> &Encoding) const { const char *CalleePos = ::strchr(getAttributesString(ID), 'C'); diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp index 65470a2bb3717..5ac9d8420218c 100644 --- a/clang/lib/Sema/SemaChecking.cpp +++ b/clang/lib/Sema/SemaChecking.cpp @@ -3168,6 +3168,35 @@ static QualType getVectorElementType(ASTContext &Context, QualType VecTy) { return QualType(); } +static bool checkConstantArgValueRange(Sema &S, CallExpr *TheCall, + unsigned ArgNum, + const llvm::APSInt &Result, int Low, + int High, bool RangeIsError) { + if (S.isConstantEvaluatedContext()) + return false; + + // We can't check the value of a dependent argument. + Expr *Arg = TheCall->getArg(ArgNum); + if (Arg->isTypeDependent() || Arg->isValueDependent()) + return false; + + if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { + if (RangeIsError) { + return S.Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) + << toString(Result, 10) << Low << High << Arg->getSourceRange(); + } + + // Defer the warning until we know if the code will be emitted so that + // dead code can ignore this. + S.DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, + S.PDiag(diag::warn_argument_invalid_range) + << toString(Result, 10) << Low << High + << Arg->getSourceRange()); + } + + return false; +} + ExprResult Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall) { @@ -3177,21 +3206,35 @@ Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, unsigned ICEArguments = 0; ASTContext::GetBuiltinTypeError Error; Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); + SmallVector<Builtin::Context::ArgRange, 2> ArgRanges; if (Error != ASTContext::GE_None) ICEArguments = 0; // Don't diagnose previously diagnosed errors. + else if (ICEArguments) + Context.BuiltinInfo.getArgRanges(BuiltinID, ArgRanges); // If any arguments are required to be ICE's, check and diagnose. for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { // Skip arguments not required to be ICE's. if ((ICEArguments & (1 << ArgNo)) == 0) continue; - llvm::APSInt Result; + ICEArguments &= ~(1 << ArgNo); + // If we don't have enough arguments, continue so we can issue better // diagnostic in checkArgCount(...) - if (ArgNo < TheCall->getNumArgs() && - BuiltinConstantArg(TheCall, ArgNo, Result)) + if (ArgNo >= TheCall->getNumArgs()) + continue; + + llvm::APSInt Result; + if (BuiltinConstantArg(TheCall, ArgNo, Result)) return true; - ICEArguments &= ~(1 << ArgNo); + + for (const Builtin::Context::ArgRange &Range : ArgRanges) { + if (Range.Index == ArgNo && + checkConstantArgValueRange(*this, TheCall, ArgNo, Result, Range.Lower, + Range.Upper - 1, + /*RangeIsError=*/true)) + return true; + } } FPOptions FPO; @@ -7063,31 +7106,14 @@ bool Sema::BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError) { if (isConstantEvaluatedContext()) return false; - llvm::APSInt Result; - - // We can't check the value of a dependent argument. - Expr *Arg = TheCall->getArg(ArgNum); - if (Arg->isTypeDependent() || Arg->isValueDependent()) - return false; // Check constant-ness first. + llvm::APSInt Result; if (BuiltinConstantArg(TheCall, ArgNum, Result)) return true; - if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { - if (RangeIsError) - return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) - << toString(Result, 10) << Low << High << Arg->getSourceRange(); - else - // Defer the warning until we know if the code will be emitted so that - // dead code can ignore this. - DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, - PDiag(diag::warn_argument_invalid_range) - << toString(Result, 10) << Low << High - << Arg->getSourceRange()); - } - - return false; + return checkConstantArgValueRange(*this, TheCall, ArgNum, Result, Low, High, + RangeIsError); } bool Sema::BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, diff --git a/clang/test/TableGen/builtin-arg-range.td b/clang/test/TableGen/builtin-arg-range.td new file mode 100644 index 0000000000000..57e54c4113493 --- /dev/null +++ b/clang/test/TableGen/builtin-arg-range.td @@ -0,0 +1,98 @@ +// RUN: clang-tblgen -I %p/../../include/ %s --gen-clang-builtins | FileCheck %s +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_INDEX 2>&1 | FileCheck %s --check-prefix=ERROR_INDEX +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_NEGATIVE_INDEX 2>&1 | FileCheck %s --check-prefix=ERROR_NEGATIVE_INDEX +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_NOT_CONSTANT 2>&1 | FileCheck %s --check-prefix=ERROR_NOT_CONSTANT +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_EMPTY 2>&1 | FileCheck %s --check-prefix=ERROR_EMPTY +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_DUPLICATE 2>&1 | FileCheck %s --check-prefix=ERROR_DUPLICATE +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_UPPER_OVERFLOW 2>&1 | FileCheck %s --check-prefix=ERROR_UPPER_OVERFLOW +// RUN: not clang-tblgen -I %p/../../include/ %s --gen-clang-builtins -DERROR_LOWER_OVERFLOW 2>&1 | FileCheck %s --check-prefix=ERROR_LOWER_OVERFLOW + +include "clang/Basic/BuiltinsBase.td" + +// CHECK-LABEL: static constexpr char BuiltinStringsStorage[] = +// CHECK-NEXT: "\0" +// CHECK-NEXT: "__builtin_one_range\0" +// CHECK-NEXT: "iiIi\0" +// CHECK-NEXT: "nR<1:0:4>\0" +// CHECK-NEXT: "__builtin_two_ranges\0" +// CHECK-NEXT: "vIiE4iIUi\0" +// CHECK-NEXT: "cR<0:-8:8,2:1:65>\0" +// CHECK-NEXT: ; + +def : Builtin { +// CHECK-LABEL: #ifdef GET_BUILTIN_INFOS +// CHECK-NEXT: Builtin::Info{Builtin::Info::StrOffsets{1 /* __builtin_one_range */, 21 /* iiIi */, 26 /* nR<1:0:4> */, 0}, HeaderDesc::NO_HEADER, ALL_LANGUAGES}, + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_one_range"]; + let Attributes = [NoThrow, ArgRange<1, 0, 4>]; +} + +def : Builtin { +// CHECK-NEXT: Builtin::Info{Builtin::Info::StrOffsets{36 /* __builtin_two_ranges */, 57 /* vIiE4iIUi */, 67 /* cR<0:-8:8,2:1:65> */, 0}, HeaderDesc::NO_HEADER, ALL_LANGUAGES}, + let Prototype = "void(_Constant int, _ExtVector<4, int>, _Constant unsigned int)"; + let Spellings = ["__builtin_two_ranges"]; + let Attributes = [Const, ArgRange<0, -8, 8>, ArgRange<2, 1, 65>]; +} + +#ifdef ERROR_INDEX +def : Builtin { +// ERROR_INDEX: :[[# @LINE - 1]]:1: error: ArgRange index 2 out of bounds + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_error_index"]; + let Attributes = [ArgRange<2, 0, 4>]; +} +#endif + +#ifdef ERROR_NEGATIVE_INDEX +def : Builtin { +// ERROR_NEGATIVE_INDEX: :[[# @LINE - 1]]:1: error: ArgRange index -1 out of bounds + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_error_negative_index"]; + let Attributes = [ArgRange<-1, 0, 4>]; +} +#endif + +#ifdef ERROR_NOT_CONSTANT +def : Builtin { +// ERROR_NOT_CONSTANT: :[[# @LINE - 1]]:1: error: ArgRange argument 0 must be _Constant + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_error_not_constant"]; + let Attributes = [ArgRange<0, 0, 4>]; +} +#endif + +#ifdef ERROR_EMPTY +def : Builtin { +// ERROR_EMPTY: :[[# @LINE - 1]]:1: error: ArgRange range is empty + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_error_empty"]; + let Attributes = [ArgRange<1, 4, 4>]; +} +#endif + +#ifdef ERROR_DUPLICATE +def : Builtin { +// ERROR_DUPLICATE: :[[# @LINE - 1]]:1: error: duplicate ArgRange for argument 1 + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_error_duplicate"]; + let Attributes = [ArgRange<1, 0, 4>, ArgRange<1, 0, 8>]; +} +#endif + +#ifdef ERROR_UPPER_OVERFLOW +def : Builtin { +// ERROR_UPPER_OVERFLOW: :[[# @LINE - 1]]:1: error: ArgRange bounds must fit in a 32-bit int + let Prototype = "int(int, _Constant unsigned int)"; + let Spellings = ["__builtin_error_upper_overflow"]; + let Attributes = [ArgRange<1, 0, 4294967296>]; +} +#endif + +#ifdef ERROR_LOWER_OVERFLOW +def : Builtin { +// ERROR_LOWER_OVERFLOW: :[[# @LINE - 1]]:1: error: ArgRange bounds must fit in a 32-bit int + let Prototype = "int(int, _Constant int)"; + let Spellings = ["__builtin_error_lower_overflow"]; + let Attributes = [ArgRange<1, -2147483649, 0>]; +} +#endif diff --git a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp index 0233f91da6076..dcfd4ba5bb853 100644 --- a/clang/utils/TableGen/ClangBuiltinsEmitter.cpp +++ b/clang/utils/TableGen/ClangBuiltinsEmitter.cpp @@ -11,10 +11,12 @@ //===----------------------------------------------------------------------===// #include "TableGenBackends.h" +#include "llvm/ADT/DenseSet.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/MathExtras.h" #include "llvm/TableGen/Error.h" #include "llvm/TableGen/Record.h" #include "llvm/TableGen/StringToOffsetTable.h" @@ -443,7 +445,13 @@ std::string renderAttributes(const Record *Builtin, BuiltinType BT) { OS << "z"; } + SmallVector<const Record *> ArgRanges; for (const auto *Attr : Builtin->getValueAsListOfDefs("Attributes")) { + if (Attr->isSubClassOf("ArgRange")) { + ArgRanges.push_back(Attr); + continue; + } + OS << Attr->getValueAsString("Mangling"); if (Attr->isSubClassOf("IndexedAttribute")) { OS << ':' << Attr->getValueAsInt("Index") << ':'; @@ -455,6 +463,46 @@ std::string renderAttributes(const Record *Builtin, BuiltinType BT) { OS << '>'; } } + + // All argument ranges are encoded together as R<Index:Lower:Upper,...>. + if (!ArgRanges.empty()) { + StringRef Prototype = Builtin->getValueAsString("Prototype").trim(); + SmallVector<StringRef> Params; + if (size_t Open = Prototype.find('('); Open != StringRef::npos) + Params = splitParams(Prototype.drop_front(Open + 1).drop_back()); + + OS << "R<"; + llvm::ListSeparator Sep(","); + SmallDenseSet<int64_t> SeenIndices; + for (const Record *Range : ArgRanges) { + int64_t Index = Range->getValueAsInt("Index"); + int64_t Lower = Range->getValueAsInt("Lower"); + int64_t Upper = Range->getValueAsInt("Upper"); + if (Index < 0 || Index >= static_cast<int64_t>(Params.size())) + PrintFatalError(Builtin->getLoc(), + "ArgRange index " + Twine(Index) + " out of bounds"); + + if (!Params[Index].starts_with("_Constant")) + PrintFatalError(Builtin->getLoc(), "ArgRange argument " + Twine(Index) + + " must be _Constant"); + + if (!isInt<32>(Lower) || !isInt<32>(Upper)) + PrintFatalError(Builtin->getLoc(), + "ArgRange bounds must fit in a 32-bit int"); + + if (!SeenIndices.insert(Index).second) + PrintFatalError(Builtin->getLoc(), + "duplicate ArgRange for argument " + Twine(Index)); + + if (Lower >= Upper) + PrintFatalError(Builtin->getLoc(), "ArgRange range is empty"); + + OS << Sep << Index << ':' << Lower << ':' << Upper; + } + + OS << '>'; + } + return Attributes; } _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
