[clang] [Clang] Introduce malloc_span attribute (PR #167010)

Marco Elver via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 10 02:56:21 PST 2025


================
@@ -1839,6 +1839,39 @@ static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
                  RestrictAttr(S.Context, AL, DeallocE, DeallocPtrIdx));
 }
 
+static bool isSpanLikeType(const QualType &Ty) {
+  // Check that the type is a plain record with the first field being a pointer
+  // type and the second field being an integer.
+  // This matches the common implementation of std::span or sized_allocation_t
+  // in P0901R11.
+  // Note that there may also be numerous cases of pointer+integer structures
+  // not actually exhibiting a std::span-like semantics, so sometimes
+  // this heuristic expectedly leads to false positive results.
+  const RecordDecl *RD = Ty->getAsRecordDecl();
+  if (!RD || RD->isUnion())
+    return false;
+  const RecordDecl *Def = RD->getDefinition();
+  if (!Def)
+    return false; // This is an incomplete type.
+  auto FieldsBegin = Def->field_begin();
+  if (std::distance(FieldsBegin, Def->field_end()) != 2)
+    return false;
+  const FieldDecl *FirstField = *FieldsBegin;
+  const FieldDecl *SecondField = *std::next(FieldsBegin);
+  return FirstField->getType()->isAnyPointerType() &&
----------------
melver wrote:

That on the other hand will cause more complexity, because then you have to potentially walk a large struct and find those fields. Also later where you may want to use this to improve codegen, it would have to go and find the pointer - what if there are 2 pointers?

I think if we talk about "span-like struct" it's exactly that: a struct with a pointer + size. Nothing more or less. But I think order of these members does not invalidate span semantics. On the other hand if you have a large struct with many members, is it a span? I can't tell.

https://github.com/llvm/llvm-project/pull/167010


More information about the cfe-commits mailing list