[clang] [clang] Extend __builtin_constant_p to constant structs and classes (PR #238279)

via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 3 22:58:13 PST 2026


https://github.com/Cons-Cat updated https://github.com/llvm/llvm-project/pull/238279

>From 66d427f06ed3bdf7c9bdbcc816e54ec418b8cc69 Mon Sep 17 00:00:00 2001
From: Lilian Gooch <omg.lily2000 at gmail.com>
Date: Tue, 3 Nov 2026 03:49:20 -0800
Subject: [PATCH] [clang] Extend __builtin_constant_p to constant structs and
 classes

This diverges from GCC, but the behavior is strictly more useful and
Clang's `__builtin_constant_p` already diverged in multiple ways. Record
types that fold to a constant hold true, just like scalars, so
arithmetic wrapper types such as `std::quantity` can be used.

Assisted-by: Cursor (Grok 4.7 by SpaceXAI)
---
 clang/lib/AST/ByteCode/ByteCodeEmitter.cpp    |   2 +-
 clang/lib/AST/ByteCode/EvalEmitter.cpp        |   3 +-
 clang/lib/AST/ByteCode/Interp.cpp             |  78 ++++++++++-
 clang/lib/AST/ByteCode/Interp.h               |   3 +-
 clang/lib/AST/ByteCode/Opcodes.td             |   2 +-
 clang/lib/AST/ExprConstant.cpp                |  11 +-
 .../test/AST/ByteCode/builtin-constant-p.cpp  |  48 +++++++
 clang/test/Sema/builtins.c                    |   4 +-
 clang/test/SemaCXX/builtin-constant-p.cpp     | 122 ++++++++++++++++++
 9 files changed, 257 insertions(+), 16 deletions(-)

diff --git a/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp b/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
index fb7b6919c85289..10a11f3e2fdfca 100644
--- a/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
+++ b/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
@@ -229,7 +229,7 @@ bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {
 bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
   const Expr *Arg = E->getArg(0);
   PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
-  if (!this->emitBCP(getOffset(EndLabel), T, E))
+  if (!this->emitBCP(getOffset(EndLabel), T, Arg->getType()->isRecordType(), E))
     return false;
   if (!this->visit(Arg))
     return false;
diff --git a/clang/lib/AST/ByteCode/EvalEmitter.cpp b/clang/lib/AST/ByteCode/EvalEmitter.cpp
index d3d0b9677bc96c..6d748a5d146413 100644
--- a/clang/lib/AST/ByteCode/EvalEmitter.cpp
+++ b/clang/lib/AST/ByteCode/EvalEmitter.cpp
@@ -220,7 +220,8 @@ bool EvalEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
   PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
   if (T == PT_Ptr) {
     const auto &Ptr = S.Stk.pop<Pointer>();
-    return this->emitBool(CheckBCPResult(S, Ptr), E);
+    return this->emitBool(
+        CheckBCPResult(S, CodePtr(), Ptr, Arg->getType()->isRecordType()), E);
   }
 
   // Otherwise, this is fine!
diff --git a/clang/lib/AST/ByteCode/Interp.cpp b/clang/lib/AST/ByteCode/Interp.cpp
index 5caede7d1a149d..22c2555e59ea44 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -275,7 +275,7 @@ static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
 }
 
 PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
-                              PrimType PT);
+                              PrimType PT, bool IsRecord);
 
 bool diagnoseShiftFailure(InterpState &S, CodePtr OpPC, ShiftFailure Failure,
                           const APSInt *Value, unsigned Bits) {
@@ -339,7 +339,67 @@ void cleanupAfterFunctionCall(InterpState &S, const Function *Func) {
     S.Stk.discard<Pointer>();
 }
 
-bool CheckBCPResult(InterpState &S, const Pointer &Ptr) {
+static bool CheckBCPRecord(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
+
+static bool CheckBCPArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  if (!CheckLoad(S, OpPC, Ptr))
+    return false;
+
+  for (unsigned I = 0, N = Ptr.getNumElems(); I != N; ++I) {
+    Pointer Elem = Ptr.atIndex(I).narrow();
+    const Descriptor *Desc = Elem.getFieldDesc();
+    if (Desc->isRecord()) {
+      if (!CheckBCPRecord(S, OpPC, Elem))
+        return false;
+    } else if (Desc->isArray()) {
+      if (!CheckBCPArray(S, OpPC, Elem))
+        return false;
+    } else if (!CheckLoad(S, OpPC, Elem)) {
+      return false;
+    }
+  }
+  return true;
+}
+
+static bool CheckBCPRecord(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
+  if (!CheckLoad(S, OpPC, Ptr))
+    return false;
+
+  const Record *R = Ptr.getRecord();
+  if (!R)
+    return false;
+
+  for (const Record::Field &F : R->fields()) {
+    Pointer Field = Ptr.atField(F.Offset);
+    if (R->isUnion() && !Field.isActive())
+      continue;
+
+    const Descriptor *Desc = Field.getFieldDesc();
+    if (Desc->isRecord()) {
+      if (!CheckBCPRecord(S, OpPC, Field))
+        return false;
+    } else if (Desc->isArray()) {
+      if (!CheckBCPArray(S, OpPC, Field))
+        return false;
+    } else if (!CheckLoad(S, OpPC, Field)) {
+      return false;
+    }
+  }
+
+  for (const Record::Base &B : R->bases())
+    if (!CheckBCPRecord(S, OpPC, Ptr.atField(B.Offset)))
+      return false;
+
+  if (!Ptr.isBaseClass())
+    for (const Record::Base &B : R->virtual_bases())
+      if (!CheckBCPRecord(S, OpPC, Ptr.atField(B.Offset)))
+        return false;
+
+  return true;
+}
+
+bool CheckBCPResult(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
+                    bool IsRecord) {
   if (Ptr.isDummy())
     return false;
   if (Ptr.isZero())
@@ -351,6 +411,12 @@ bool CheckBCPResult(InterpState &S, const Pointer &Ptr) {
   if (Ptr.isTypeidPointer())
     return true;
 
+  if (IsRecord) {
+    PushIgnoreDiags(S);
+    auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
+    return CheckBCPRecord(S, OpPC, Ptr);
+  }
+
   if (Ptr.getType()->isAnyComplexType())
     return true;
 
@@ -3843,8 +3909,8 @@ bool Interpret(InterpState &S) {
 /// OR (of course), when we encounter an error and one of the opcodes
 /// returns false.
 PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
-                              PrimType PT) {
-  // PC after reading the BCP opcode and both Offset/PT arguments.
+                              PrimType PT, bool IsRecord) {
+  // PC after reading the BCP opcode and its Offset/PT/IsRecord arguments.
   [[maybe_unused]] CodePtr PCBefore = S.PC;
   size_t StackSizeBefore = S.Stk.size();
 
@@ -3885,7 +3951,7 @@ PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
       const auto &Ptr = S.Stk.pop<Pointer>();
       assert(S.Stk.size() == StackSizeBefore);
       S.Stk.push<Integral<32, true>>(
-          Integral<32, true>::from(CheckBCPResult(S, Ptr)));
+          Integral<32, true>::from(CheckBCPResult(S, OpPC, Ptr, IsRecord)));
     } else {
       // Pop the result from the stack and return success.
       TYPE_SWITCH(PT, S.Stk.discard<T>(););
@@ -3895,7 +3961,7 @@ PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
   } else {
     // Jump to the end of the speculation, just after the actual EndSpeculation
     // op.
-    S.PC = PCBefore + Offset - align(sizeof(Opcode));
+    S.PC = PCBefore + Offset - align(sizeof(PrimType)) - align(sizeof(bool));
 
     // End the speculation manually since we didn't call EndSpeculation
     // naturally.
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index b96b50fe9e69f3..43db9e765d0f1a 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -121,7 +121,8 @@ bool CheckLiteralType(InterpState &S, CodePtr OpPC, const Type *T);
 bool InvalidShuffleVectorIndex(InterpState &S, CodePtr OpPC, uint32_t Index);
 bool CheckBitCast(InterpState &S, CodePtr OpPC, bool HasIndeterminateBits,
                   bool TargetIsUCharOrByte);
-bool CheckBCPResult(InterpState &S, const Pointer &Ptr);
+bool CheckBCPResult(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
+                    bool IsRecord);
 bool checkDestructor(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
 bool CheckFunctionDecl(InterpState &S, CodePtr OpPC, const FunctionDecl *FD);
 bool CheckBitCast(InterpState &S, CodePtr OpPC, const Type *TargetType,
diff --git a/clang/lib/AST/ByteCode/Opcodes.td b/clang/lib/AST/ByteCode/Opcodes.td
index 23aa5abeb0a881..19e5c707a4a6d2 100644
--- a/clang/lib/AST/ByteCode/Opcodes.td
+++ b/clang/lib/AST/ByteCode/Opcodes.td
@@ -202,7 +202,7 @@ def StartSpeculation : SuccessOpcode;
 def EndSpeculation : SuccessOpcode;
 def BCP : Opcode {
   let HasCustomEval = 1;
-  let Args = [ArgSint32, ArgPrimType];
+  let Args = [ArgSint32, ArgPrimType, ArgBool];
 }
 
 //===----------------------------------------------------------------------===//
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 57d5bb475d0f9b..1e47118ae6f13c 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -16729,20 +16729,21 @@ static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
   // __builtin_constant_p always has one operand. The rules which gcc follows
   // are not precisely documented, but are as follows:
   //
-  //  - If the operand is of integral, floating, complex or enumeration type,
-  //    and can be folded to a known value of that type, it returns 1.
+  //  - If the operand is of integral, floating, complex, enumeration, or
+  //    record type, and can be folded to a known value of that type, it
+  //    returns 1.
   //  - If the operand can be folded to a pointer to the first character
   //    of a string literal (or such a pointer cast to an integral type)
   //    or to a null pointer or an integer cast to a pointer, it returns 1.
   //
   // Otherwise, it returns 0.
   //
-  // FIXME: GCC also intends to return 1 for literals of aggregate types, but
+  // FIXME: GCC also intends to return 1 for literals of arrays, but
   // its support for this did not work prior to GCC 9 and is not yet well
   // understood.
   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
-      ArgType->isAnyComplexType() || ArgType->isPointerType() ||
-      ArgType->isNullPtrType()) {
+      ArgType->isAnyComplexType() || ArgType->isRecordType() ||
+      ArgType->isPointerType() || ArgType->isNullPtrType()) {
     APValue V;
     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
       Fold.keepDiagnostics();
diff --git a/clang/test/AST/ByteCode/builtin-constant-p.cpp b/clang/test/AST/ByteCode/builtin-constant-p.cpp
index 1738ed1e9328dc..f00399d1d1189b 100644
--- a/clang/test/AST/ByteCode/builtin-constant-p.cpp
+++ b/clang/test/AST/ByteCode/builtin-constant-p.cpp
@@ -159,3 +159,51 @@ namespace Inactive {
   }
 
 }
+
+namespace Record {
+  struct S {
+    int n;
+  };
+
+  S NonConstexprGlobal{1};
+  constexpr S ConstexprGlobal{2};
+
+  static_assert(!__builtin_constant_p(NonConstexprGlobal));
+  static_assert(__builtin_constant_p(ConstexprGlobal));
+  static_assert(!__builtin_constant_p(&ConstexprGlobal));
+
+  constexpr bool Uninitialized() {
+    S s;
+    return __builtin_constant_p(s);
+  }
+  static_assert(!Uninitialized());
+
+  struct NonTrivial {
+    int n;
+    constexpr NonTrivial(int n) : n(n) {}
+    constexpr NonTrivial(const NonTrivial &other) : n(other.n) {}
+  };
+
+  constexpr NonTrivial NonTrivialValue{3};
+  static_assert(__builtin_constant_p(NonTrivialValue));
+
+  constexpr int NonTrivialIf(NonTrivial V) {
+    if (__builtin_constant_p(V))
+      return V.n;
+    return 0;
+  }
+  static_assert(NonTrivialIf(NonTrivialValue) == 3);
+}
+
+namespace Union {
+  union U {
+    int n;
+    char c;
+  };
+
+  U NonConstexprGlobal{1};
+  constexpr U ConstexprGlobal{2};
+
+  static_assert(!__builtin_constant_p(NonConstexprGlobal));
+  static_assert(__builtin_constant_p(ConstexprGlobal));
+}
diff --git a/clang/test/Sema/builtins.c b/clang/test/Sema/builtins.c
index e7bf5a43b6b0ac..90ff501a897966 100644
--- a/clang/test/Sema/builtins.c
+++ b/clang/test/Sema/builtins.c
@@ -150,6 +150,9 @@ void test17(void) {
   T(EnumValue1);
   T((enum Enum)(int)EnumValue2);
 
+  //  - a record that folds to a known value
+  T((struct Aggregate){0, 1});
+
   //  - the address of the first character of a string literal, losslessly cast
   //    to any type
   T("string literal");
@@ -163,7 +166,6 @@ void test17(void) {
   F(test17_c);
   F(&test17_c);
   F(&test17_d);
-  F((struct Aggregate){0, 1});
   F((IntVector){0, 1, 2, 3});
   F(test17);
 
diff --git a/clang/test/SemaCXX/builtin-constant-p.cpp b/clang/test/SemaCXX/builtin-constant-p.cpp
index 71c38c5c63c710..77fd51b3b198a0 100644
--- a/clang/test/SemaCXX/builtin-constant-p.cpp
+++ b/clang/test/SemaCXX/builtin-constant-p.cpp
@@ -61,6 +61,128 @@ static_assert(bcp(int_to_ptr(123)));      // GCC rejects these due to not recogn
 static_assert(bcp_fold(int_to_ptr(123))); // the bcp conditional in 'int_to_ptr' ...
 static_assert(__builtin_constant_p((int*)123)); // ... but GCC accepts this
 
+struct Aggregate {
+  int Value;
+  constexpr Aggregate(int Value) : Value(Value) {}
+};
+
+constexpr Aggregate ConstantAggregate(42);
+Aggregate NonConstantAggregate(42);
+static_assert(bcp(ConstantAggregate));
+
+void require_constant_aggregate(Aggregate Value) // expected-note {{candidate disabled: argument is not constant}}
+    __attribute__((enable_if(__builtin_constant_p(Value),
+                             "argument is not constant")));
+
+void test_constant_aggregate() {
+  require_constant_aggregate(ConstantAggregate);
+  require_constant_aggregate(NonConstantAggregate); // expected-error {{no matching function for call to 'require_constant_aggregate'}}
+}
+
+constexpr int constant_aggregate_if() {
+  constexpr Aggregate Value(42);
+  if (__builtin_constant_p(Value))
+    return Value.Value;
+  return 0;
+}
+static_assert(constant_aggregate_if() == 42);
+
+struct NonTrivial {
+  int Value;
+  constexpr NonTrivial(int Value) : Value(Value) {}
+  constexpr NonTrivial(const NonTrivial &Other) : Value(Other.Value) {}
+};
+
+constexpr NonTrivial ConstantNonTrivial(42);
+NonTrivial NonConstantNonTrivial(42);
+
+constexpr int non_trivial_if(NonTrivial Value) {
+  if (__builtin_constant_p(Value))
+    return Value.Value;
+  return 0;
+}
+static_assert(non_trivial_if(ConstantNonTrivial) == 42);
+
+void require_constant_non_trivial(NonTrivial Value) // expected-note {{candidate disabled: argument is not constant}}
+    __attribute__((enable_if(__builtin_constant_p(Value),
+                             "argument is not constant")));
+
+void test_constant_non_trivial() {
+  require_constant_non_trivial(ConstantNonTrivial);
+  require_constant_non_trivial(NonConstantNonTrivial); // expected-error {{no matching function for call to 'require_constant_non_trivial'}}
+}
+
+// Unions are record types, so a constant-evaluable union value is constant.
+union ValueUnion {
+  int Value;
+  constexpr ValueUnion(int Value) : Value(Value) {}
+  constexpr ValueUnion(const ValueUnion &Other) : Value(Other.Value) {}
+};
+
+constexpr ValueUnion ConstantUnion(42);
+ValueUnion NonConstantUnion(42);
+static_assert(bcp(ConstantUnion));
+static_assert(!__builtin_constant_p(NonConstantUnion));
+
+constexpr int constant_union_if() {
+  constexpr ValueUnion Value(42);
+  if (__builtin_constant_p(Value))
+    return Value.Value;
+  return 0;
+}
+static_assert(constant_union_if() == 42);
+
+void require_constant_union(ValueUnion Value) // expected-note {{candidate disabled: argument is not constant}}
+    __attribute__((enable_if(__builtin_constant_p(Value),
+                             "argument is not constant")));
+
+void test_constant_union() {
+  require_constant_union(ConstantUnion);
+  require_constant_union(NonConstantUnion); // expected-error {{no matching function for call to 'require_constant_union'}}
+}
+
+// `*this` is the class object. `this` passed into a callee is checked there.
+struct ThisValue {
+  int Value;
+  constexpr ThisValue(int Value) : Value(Value) {}
+
+  constexpr bool object_is_constant() const {
+    return __builtin_constant_p(*this);
+  }
+
+  constexpr int value_if_constant() const {
+    if (__builtin_constant_p(*this))
+      return Value;
+    return 0;
+  }
+
+  constexpr bool pass_this() const;
+};
+
+constexpr bool check_this_pointer(const ThisValue *Object) {
+  return __builtin_constant_p(*Object);
+}
+
+constexpr bool ThisValue::pass_this() const {
+  return check_this_pointer(this);
+}
+
+constexpr ThisValue ConstantThis(42);
+ThisValue NonConstantThis(7);
+
+static_assert(ConstantThis.object_is_constant());
+static_assert(ConstantThis.value_if_constant() == 42);
+static_assert(ConstantThis.pass_this());
+
+constexpr bool check_this_object(const ThisValue &Object) {
+  return Object.object_is_constant();
+}
+constexpr bool check_passed_this(const ThisValue &Object) {
+  return Object.pass_this();
+}
+static_assert(!check_this_object(NonConstantThis));
+static_assert(!check_passed_this(NonConstantThis));
+
 // State mutations in the operand are not permitted.
 //
 // The rule GCC uses for this is not entirely understood, but seems to depend



More information about the cfe-commits mailing list