[clang] [llvm] [AllocToken] Propagate !alloc_token through inlined malloc_span wrappers (PR #244314)
David Li via cfe-commits
cfe-commits at lists.llvm.org
Sun Nov 22 20:20:03 PST 2026
https://github.com/david-xl updated https://github.com/llvm/llvm-project/pull/244314
>From 8cae2f2c16f3ad373a02dba370ca8838334b7454 Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 18 Nov 2026 09:38:16 -0800
Subject: [PATCH 1/4] [AllocToken] Infer the allocated type from placement new
into the result (#241548)
-fsanitize=alloc-token infers the type of an untyped allocation (malloc,
size-returning new, alloc_size functions) from a sizeof in the size
argument or a cast of the result. The common "allocate raw storage, then
construct in place" idiom has neither:
void *mem = alloc(size);
T *obj = new (mem) T();
and so gets the fallback token, which misplaces the object under a
pointer-split token mode. Add placement new as a third source. The order
is sizeof, then placement new, then cast: a sizeof states what the
allocation was sized for (it may be a header plus elements placed by
pointer arithmetic), while a cast to a raw storage pointer carries less
information than the construction. Only the reserved global placement
form is considered; the storage is matched through parentheses, casts,
and the non-static fields of a by-value result (res.p of a
size-returning allocation). A local variable is used only if it is
initialized by the allocation call and is otherwise only read (every
other reference is consumed by an lvalue-to-rvalue conversion), so its
value does not depend on control flow; assignment, taking its address or
binding it to a reference disqualify it, and parameters are not used. If
different types are constructed into the same storage, nothing is
inferred. The placement news of a function body are
collected lazily, once, on the first allocation call without a sizeof.
Assisted-by: Gemini
---
clang/docs/AllocToken.md | 13 ++
clang/docs/ReleaseNotes.md | 3 +
clang/include/clang/AST/InferAlloc.h | 21 +-
clang/lib/AST/InferAlloc.cpp | 131 ++++++++++-
clang/lib/CodeGen/CGBuiltin.cpp | 6 +-
clang/lib/CodeGen/CGExpr.cpp | 12 +-
clang/lib/CodeGen/CodeGenFunction.h | 6 +
clang/test/CodeGenCXX/alloc-token.cpp | 322 ++++++++++++++++++++++++++
8 files changed, 504 insertions(+), 10 deletions(-)
diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index cca7136b652abd..092e4eb56f0679 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -56,6 +56,19 @@ The following command-line options affect generated token IDs:
is of the form `2^k-1` (e.g. the default `SIZE_MAX`), all `k` bits are
used and token IDs are in `[0, N]`, i.e. a token ID may be equal to `N`.
+## Allocated Type Inference
+
+For `new` expressions the allocated type is known syntactically. For untyped
+allocation functions such as `malloc`, the type is inferred heuristically from
+the allocation call and its context, in this order: a `sizeof` in the size
+argument, a placement `new` into the result, and a cast of the result. The
+heuristics are syntactic: `sizeof` expressions and casts ignore control flow
+and reassignments, and a placement `new` through a variable is only used if
+the variable is initialized by the allocation call and otherwise only read
+(variables that are reassigned, or whose address or reference is taken, are
+not used for inference). If no type can be inferred, the allocation receives
+the fallback token.
+
## Querying Token IDs with `__builtin_infer_alloc_token`
For use cases where the token ID must be known at compile time, Clang provides
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 4f4cfaf7af73a5..7809f7bb036949 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1679,6 +1679,9 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
normalize `cfi-icall` and `kcfi` function type metadata, leaving C++ class
vtable, member-pointer, and `-fexperimental-call-graph-section` metadata
canonical so whole-program devirtualization works reliably. (#GH242466)
+- `-fsanitize=alloc-token` now also infers the allocated type from a placement
+ `new` into the result of an untyped allocation call, e.g. `new (malloc(n)) T`
+ or `void *p = malloc(n); new (p) T;`.
### Python Binding Changes
diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index c3dc30204feafe..79c65889d410d6 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -15,15 +15,30 @@
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/Support/AllocToken.h"
#include <optional>
namespace clang {
namespace infer_alloc {
-/// Infer the possible allocated type from an allocation call expression.
-QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
- const CastExpr *CastE);
+/// Infer the possible allocated type from an allocation call expression, in
+/// this order: a sizeof in a size argument, a placement new into the result
+/// (\p PlacementNewType, if given, maps the call to the type constructed into
+/// its result, see collectPlacementNewTypes()), and finally a cast of the
+/// result (\p CastE is the cast the call result is immediately used in, if
+/// any).
+QualType inferPossibleType(
+ const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE,
+ llvm::function_ref<QualType(const CallExpr *)> PlacementNewType = nullptr);
+
+/// Maps the allocation calls in \p Body whose result is used as placement-new
+/// storage to the constructed type (null if different types are constructed
+/// into it), e.g. `void *mem = alloc(n); new (mem) T();`. A local variable is
+/// only used if it is initialized by the call and otherwise only read.
+llvm::DenseMap<const CallExpr *, QualType>
+collectPlacementNewTypes(const Stmt *Body);
/// Get the information required for construction of an allocation token ID.
std::optional<llvm::AllocTokenMetadata>
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 6c99a81d739f1e..6767b3bf4dd308 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -14,10 +14,13 @@
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
+#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
#include "clang/AST/Type.h"
#include "clang/Basic/IdentifierTable.h"
#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
using namespace clang;
using namespace infer_alloc;
@@ -167,11 +170,11 @@ static QualType inferPossibleTypeFromCastExpr(const CallExpr *CallE,
return QualType();
}
-QualType infer_alloc::inferPossibleType(const CallExpr *E,
- const ASTContext &Ctx,
- const CastExpr *CastE) {
+QualType infer_alloc::inferPossibleType(
+ const CallExpr *E, const ASTContext &Ctx, const CastExpr *CastE,
+ llvm::function_ref<QualType(const CallExpr *)> PlacementNewType) {
QualType AllocType;
- // First check arguments.
+ // First check arguments: a sizeof states what the allocation was sized for.
for (const Expr *Arg : E->arguments()) {
AllocType = inferPossibleTypeFromArithSizeofExpr(Arg);
if (AllocType.isNull())
@@ -179,12 +182,132 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
if (!AllocType.isNull())
break;
}
+ // Then check for a placement new into the result, which names the object
+ // constructed there and is stronger evidence than a cast of the result.
+ if (AllocType.isNull() && PlacementNewType)
+ AllocType = PlacementNewType(E);
// Then check later casts.
if (AllocType.isNull())
AllocType = inferPossibleTypeFromCastExpr(E, CastE);
return AllocType;
}
+/// Strips parentheses and non-static field accesses of a by-value object
+/// (e.g. the pointer member of a size-returning allocation result) from an
+/// lvalue, down to the expression naming the object. Indirect member accesses
+/// (`->`) name other storage and stop the walk.
+static const Expr *stripFields(const Expr *E) {
+ E = E->IgnoreParens();
+ while (const auto *ME = dyn_cast<MemberExpr>(E)) {
+ if (ME->isArrow() || !isa<FieldDecl>(ME->getMemberDecl()))
+ break;
+ // The base of a member of a temporary is a MaterializeTemporaryExpr.
+ E = ME->getBase()->IgnoreParenImpCasts();
+ }
+ return E;
+}
+
+/// Finds the allocation call an initializer consists of, looking through
+/// parentheses, casts, temporaries, and the trivial copy or move a class-typed
+/// value may carry.
+static const CallExpr *initializingCall(const Expr *Init) {
+ while (Init) {
+ Init = Init->IgnoreImplicit()->IgnoreParenCasts();
+ const auto *CE = dyn_cast<CXXConstructExpr>(Init);
+ // A non-trivial copy or move may not be elided (-fno-elide-constructors)
+ // and could replace the pointer.
+ if (!CE || CE->getNumArgs() != 1 ||
+ !CE->getConstructor()->isCopyOrMoveConstructor() ||
+ !CE->getConstructor()->isTrivial())
+ break;
+ Init = CE->getArg(0);
+ }
+ return dyn_cast_or_null<CallExpr>(Init);
+}
+
+namespace {
+/// Implements collectPlacementNewTypes(). A variable qualifies if every
+/// reference to it other than its initializer is an lvalue-to-rvalue read.
+class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
+public:
+ // Resolved after the traversal: a use that is not a read may follow the
+ // placement new and still disqualify the variable.
+ llvm::DenseMap<const CallExpr *, QualType> finish() && {
+ for (const auto &[VD, T] : Uses)
+ if (const CallExpr *CE = Defs.lookup(VD))
+ record(CE, T);
+ return std::move(CallTypes);
+ }
+
+ bool VisitVarDecl(const VarDecl *VD) override {
+ if (VD->hasLocalStorage() && !isa<ParmVarDecl>(VD))
+ if (const CallExpr *CE = initializingCall(VD->getInit()))
+ Defs.try_emplace(VD, CE);
+ return true;
+ }
+
+ // A read of the variable or of one of its fields. Traversal is pre-order,
+ // so the conversion is seen before the DeclRefExpr below it.
+ bool VisitImplicitCastExpr(const ImplicitCastExpr *ICE) override {
+ if (ICE->getCastKind() == CK_LValueToRValue)
+ if (const auto *DRE =
+ dyn_cast<DeclRefExpr>(stripFields(ICE->getSubExpr())))
+ Reads.insert(DRE);
+ return true;
+ }
+
+ // Any other reference may modify the variable.
+ bool VisitDeclRefExpr(const DeclRefExpr *DRE) override {
+ if (!Reads.contains(DRE))
+ if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
+ Defs.erase(VD);
+ return true;
+ }
+
+ bool VisitCXXNewExpr(const CXXNewExpr *NE) override {
+ // Only the reserved placement form is known to construct into its
+ // argument; dependent new-expressions have no operator new yet.
+ const FunctionDecl *OperatorNew = NE->getOperatorNew();
+ if (NE->getNumPlacementArgs() != 1 || !OperatorNew ||
+ !OperatorNew->isReservedGlobalPlacementOperator())
+ return true;
+ const Expr *Source =
+ stripFields(NE->getPlacementArg(0)->IgnoreParenCasts());
+ QualType T = NE->getAllocatedType();
+ if (const auto *CE = dyn_cast<CallExpr>(Source))
+ record(CE, T);
+ else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
+ if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
+ Uses.emplace_back(VD, T);
+ return true;
+ }
+
+private:
+ void record(const CallExpr *CE, QualType T) {
+ auto [It, Inserted] = CallTypes.try_emplace(CE, T);
+ // Different types constructed into the same storage: ambiguous.
+ if (!Inserted && !It->second.isNull() &&
+ It->second.getCanonicalType() != T.getCanonicalType())
+ It->second = QualType();
+ }
+
+ llvm::DenseMap<const CallExpr *, QualType> CallTypes;
+ // Variable -> the allocation call initializing it; erased on any use that
+ // is not a read.
+ llvm::DenseMap<const VarDecl *, const CallExpr *> Defs;
+ llvm::SmallPtrSet<const DeclRefExpr *, 16> Reads;
+ llvm::SmallVector<std::pair<const VarDecl *, QualType>> Uses;
+};
+} // namespace
+
+llvm::DenseMap<const CallExpr *, QualType>
+infer_alloc::collectPlacementNewTypes(const Stmt *Body) {
+ PlacementNewCollector Collector;
+ if (Body)
+ Collector.TraverseStmt(Body);
+ return std::move(Collector).finish();
+}
+
std::optional<llvm::AllocTokenMetadata>
infer_alloc::getAllocTokenMetadata(QualType T, const ASTContext &Ctx) {
llvm::AllocTokenMetadata ATMD;
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index bdcd9ee43ce1c7..7b78abdb71c390 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -24,6 +24,7 @@
#include "ConstantEmitter.h"
#include "PatternInit.h"
#include "TargetInfo.h"
+#include "clang/AST/InferAlloc.h"
#include "clang/AST/OSLog.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/DiagnosticFrontend.h"
@@ -4892,7 +4893,10 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl GD, unsigned BuiltinID,
}
case Builtin::BI__builtin_infer_alloc_token: {
- llvm::MDNode *MDN = buildAllocToken(E);
+ // The builtin has no enclosing allocation whose placement-new uses could
+ // be inspected, so only the call-based inference applies.
+ llvm::MDNode *MDN = buildAllocToken(
+ infer_alloc::inferPossibleType(E, getContext(), CurCast));
llvm::Value *MDV = MetadataAsValue::get(getLLVMContext(), MDN);
llvm::Function *F =
CGM.getIntrinsic(llvm::Intrinsic::alloc_token_id, {IntPtrTy});
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ae4b40b32d05c8..844b5e4c28be92 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,8 +1407,16 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
}
llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
- return buildAllocToken(
- infer_alloc::inferPossibleType(E, getContext(), CurCast));
+ // The placement news of the enclosing function body are collected once, on
+ // the first allocation call that is not already typed by a sizeof.
+ auto PlacementNewType = [this](const CallExpr *E) -> QualType {
+ if (!AllocTokenPlacementTypes)
+ AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
+ CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
+ return AllocTokenPlacementTypes->lookup(E);
+ };
+ return buildAllocToken(infer_alloc::inferPossibleType(
+ E, getContext(), CurCast, PlacementNewType));
}
void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index c46c33a19cce28..5cd26898890f84 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -375,6 +375,12 @@ class CodeGenFunction : public CodeGenTypeCache {
/// expression.
const CastExpr *CurCast = nullptr;
+ /// Allocation calls of the current function body whose result is used as
+ /// placement-new storage, mapped to the constructed type; collected lazily
+ /// for -fsanitize=alloc-token type inference.
+ std::optional<llvm::DenseMap<const CallExpr *, QualType>>
+ AllocTokenPlacementTypes;
+
/// Save Parameter Decl for coroutine.
llvm::SmallVector<const ParmVarDecl *, 4> FnArgs;
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 057ca668c9dd3a..387d5ae83b79f8 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -4,6 +4,7 @@
extern "C" {
void *aligned_alloc(size_t alignment, size_t size) __attribute__((malloc));
void *malloc(size_t size) __attribute__((malloc));
+void free(void *);
void *calloc(size_t num, size_t size) __attribute__((malloc));
void *realloc(void *ptr, size_t size) __attribute__((malloc));
void *reallocarray(void *ptr, size_t nmemb, size_t size) __attribute__((malloc));
@@ -150,6 +151,327 @@ TestClass *test_new_class_array() {
return arr;
}
+struct PlacedNoPtr {
+ long len;
+ unsigned char tag;
+ char data[1];
+};
+
+struct PlacedWithPtr {
+ void *next;
+ long len;
+};
+
+// Allocation calls whose result is only named by a later placement new. The
+// inference order is sizeof, then placement new, then cast.
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z25test_placement_new_directv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR:![0-9]+]]
+PlacedNoPtr *test_placement_new_direct() {
+ return new (malloc(64)) PlacedNoPtr();
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z24test_placement_new_arrayv(
+// CHECK: call noalias ptr @malloc(i64 noundef 640){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_array() {
+ void *mem = malloc(640);
+ return new (mem) PlacedNoPtr[10];
+}
+
+// A sizeof in the size argument states what the allocation was sized for and
+// takes precedence: the placement new may construct only a header, with the
+// elements placed by pointer arithmetic.
+// CHECK-LABEL: define dso_local noundef ptr @_Z34test_placement_new_sizeof_prevailsv(
+// CHECK: call noalias ptr @malloc(i64 noundef 40){{.*}} !alloc_token [[META_PLACEDWITHPTR:![0-9]+]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR:![0-9]+]]
+long *test_placement_new_sizeof_prevails() {
+ void *mem = malloc(2 * sizeof(PlacedWithPtr) + sizeof(long));
+ long *count = new (mem) long(2);
+ // The same holds for a sizeof of a character type.
+ void *bytes = malloc(sizeof(char) * 64);
+ sink = new (bytes) PlacedWithPtr();
+ return count;
+}
+
+// A cast of the result is weaker evidence than the placement new, whether the
+// cast is to a raw storage pointer (char *, void *) or to a base class.
+struct DerivedWithPtr : PlacedNoPtr {
+ void *next;
+};
+// CHECK-LABEL: define dso_local void @_Z28test_placement_new_over_castv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 32){{.*}} !alloc_token [[META_DERIVEDWITHPTR:![0-9]+]]
+void test_placement_new_over_cast() {
+ char *p1 = static_cast<char *>(malloc(64));
+ sink = new (p1) PlacedWithPtr();
+ // The member access is an implicit lvalue-to-rvalue cast to void *.
+ sink = new (__size_returning_new(64).p) PlacedWithPtr();
+ auto *base = static_cast<PlacedNoPtr *>(malloc(32));
+ sink = new (base) DerivedWithPtr();
+}
+
+// Storage constructed into with different types: no type is inferred.
+// CHECK-LABEL: define dso_local void @_Z28test_placement_new_ambiguousi(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_ambiguous(int which) {
+ void *mem = malloc(64);
+ if (which)
+ sink = new (mem) PlacedNoPtr();
+ else
+ sink = new (mem) PlacedWithPtr();
+}
+
+// A user-provided placement operator new may use its argument as allocator
+// state rather than as the storage, so the allocation feeding it stays untyped
+// (the custom operator new call itself is typed).
+struct Arena {};
+void *operator new(size_t, Arena *);
+Arena *alloc_arena(size_t) __attribute__((malloc));
+// CHECK-LABEL: define dso_local void @_Z24test_placement_new_arenav(
+// CHECK: call noalias noundef ptr @_Z11alloc_arenam(i64 noundef 64)
+// CHECK-NOT: @_Z11alloc_arenam{{.*}}!alloc_token
+// CHECK: call noundef ptr @_ZnwmP5Arena(i64 noundef 16, {{.*}} !alloc_token [[META_PLACEDNOPTR]]
+void test_placement_new_arena() {
+ Arena *arena = alloc_arena(64);
+ sink = new (arena) PlacedNoPtr();
+}
+
+// Same for a class-specific operator new(size_t, void *).
+struct ClassPlacement {
+ void *next;
+ static void *operator new(size_t, void *ctx);
+};
+// CHECK-LABEL: define dso_local void @_Z33test_placement_new_class_specificv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+// CHECK: call noundef ptr @_ZN14ClassPlacementnwEmPv(i64 noundef 8, {{.*}} !alloc_token [[META_CLASSPLACEMENT:![0-9]+]]
+void test_placement_new_class_specific() {
+ void *ctx = malloc(64);
+ sink = new (ctx) ClassPlacement;
+}
+
+// Indirect member accesses, address-of, and static members name storage other
+// than the allocation itself.
+struct Holder {
+ void *p;
+};
+Holder *alloc_holder(size_t) __attribute__((malloc));
+struct SpanWithStatic {
+ void *p;
+ size_t n;
+ static void *storage;
+};
+SpanWithStatic alloc_span_with_static(size_t) __attribute__((malloc_span));
+// CHECK-LABEL: define dso_local void @_Z27test_placement_new_indirectv(
+// CHECK: call noalias noundef ptr @_Z12alloc_holderm(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call { ptr, i64 } @_Z22alloc_span_with_staticm(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_indirect() {
+ Holder *h = alloc_holder(64);
+ sink = new (h->p) PlacedNoPtr();
+ void *mem = malloc(64);
+ sink = new (&mem) unsigned char(0);
+ SpanWithStatic span = alloc_span_with_static(64);
+ sink = new (span.storage) PlacedNoPtr();
+}
+
+// A variable is used only if it is initialized by the allocation call and is
+// otherwise only read, so that its value does not depend on control flow.
+struct Storage {
+ void *p;
+ size_t n;
+};
+Storage alloc_storage(size_t) __attribute__((malloc_span));
+// CHECK-LABEL: define dso_local void @_Z32test_placement_new_read_only_varb(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+void test_placement_new_read_only_var(bool c) {
+ // Used inside a branch and a loop, and read elsewhere.
+ void *p = malloc(64);
+ if (c)
+ sink = new (p) PlacedNoPtr();
+ sink = p;
+ void *q = malloc(64);
+ for (int i = 0; i < 2; ++i)
+ sink = new (q) PlacedWithPtr();
+ // Fields of a by-value result are reads of the variable.
+ Storage s = alloc_storage(64);
+ sink = new (s.p) PlacedNoPtr();
+ sink = reinterpret_cast<void *>(s.n);
+}
+
+// Any use of the variable other than a read may change its value and
+// disqualifies it: assignment (so the storage the placement new ends up in
+// would depend on control flow, and the sizeof or cast of the other
+// allocation would be overridden), compound assignment, increment,
+// address-of, a write to one of its fields, a member call, binding to a
+// reference directly or as a call argument, and a by-reference capture.
+// Nothing is inferred for any of these allocations; with the variable
+// disqualified, the cast of the result still applies.
+void rebind(void *&p);
+void peek(void *const &p);
+struct Rebinder {
+ Rebinder(void *&p);
+};
+// CHECK-LABEL: define dso_local void @_Z26test_placement_new_writtenb(
+// CHECK: call noalias ptr @malloc(i64 noundef 8)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 8)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 32)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 32)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_written(bool c) {
+ // Freed and reassigned before the placement new.
+ void *p1 = malloc(8);
+ free(p1);
+ p1 = malloc(8);
+ sink = new (p1) long(10);
+ // Redefined in one branch of an if, used in the other.
+ void *p2 = malloc(64);
+ if (c)
+ p2 = malloc(32);
+ else
+ sink = new (p2) PlacedNoPtr();
+ // Captured by reference and reassigned before the lambda runs.
+ void *p3 = malloc(64);
+ auto construct = [&] { sink = new (p3) PlacedNoPtr(); };
+ p3 = malloc(32);
+ construct();
+ // The assignment of the placement new's result.
+ void *p4 = malloc(64);
+ p4 = new (p4) PlacedNoPtr();
+ char *p5 = static_cast<char *>(malloc(64));
+ p5 += 8;
+ sink = new (p5) PlacedNoPtr();
+ char *p6 = static_cast<char *>(malloc(64));
+ ++p6;
+ sink = new (p6) PlacedNoPtr();
+ void *p7 = malloc(64);
+ sink = &p7;
+ sink = new (p7) PlacedNoPtr();
+ Storage s = alloc_storage(64);
+ s.p = sink;
+ sink = new (s.p) PlacedNoPtr();
+ void *p8 = malloc(64);
+ void *&p8ref = p8;
+ p8ref = sink;
+ sink = new (p8) PlacedNoPtr();
+ void *p9 = malloc(64);
+ rebind(p9);
+ sink = new (p9) PlacedNoPtr();
+ void *p10 = malloc(64);
+ Rebinder rebinder(p10);
+ sink = new (p10) PlacedNoPtr();
+ // Binding to a const reference is not a read either.
+ void *p11 = malloc(64);
+ peek(p11);
+ sink = new (p11) PlacedNoPtr();
+}
+
+// A parameter's incoming value is unknown, and a variable assigned after its
+// declaration is not initialized by the allocation call.
+// CHECK-LABEL: define dso_local void @_Z34test_placement_new_not_initializedPvb(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_not_initialized(void *p, bool c) {
+ if (c)
+ p = malloc(64);
+ sink = new (p) PlacedNoPtr();
+ void *q = nullptr;
+ if (c)
+ q = malloc(64);
+ if (q)
+ sink = new (q) PlacedNoPtr();
+}
+
+// Variables without local storage may be written by any call in between.
+void *global_storage;
+// CHECK-LABEL: define dso_local void @_Z28test_placement_new_non_localv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: invoke noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: ret void
+void test_placement_new_non_local() {
+ global_storage = malloc(64);
+ sink = new (global_storage) PlacedNoPtr();
+ static void *static_storage = malloc(64);
+ sink = new (static_storage) PlacedNoPtr();
+}
+
+// Non-generic lambdas use the captured variable; a generic lambda's dependent
+// new-expression has no resolved operator new and is skipped.
+// CHECK-LABEL: define dso_local void @_Z25test_placement_new_lambdav(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+void test_placement_new_lambda() {
+ void *mem = malloc(64);
+ auto construct = [mem] { sink = new (mem) PlacedNoPtr(); };
+ construct();
+ void *mem2 = malloc(64);
+ auto construct2 = [mem2](auto x) { sink = new (mem2) decltype(x)(); };
+ construct2(PlacedNoPtr{});
+}
+
+template <typename T>
+T *placement_construct(size_t size) {
+ __sized_ptr_t res = __size_returning_new(size);
+ return new (res.p) T();
+}
+
+// CHECK-LABEL: define dso_local void @_Z27test_placement_new_templatev(
+// CHECK: call noundef ptr @_Z19placement_constructI11PlacedNoPtrEPT_m(
+// CHECK: call noundef ptr @_Z19placement_constructI13PlacedWithPtrEPT_m(
+void test_placement_new_template() {
+ sink = placement_construct<PlacedNoPtr>(64);
+ sink = placement_construct<PlacedWithPtr>(64);
+}
+
+// CHECK-LABEL: define linkonce_odr noundef ptr @_Z19placement_constructI11PlacedNoPtrEPT_m(
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef {{.*}}){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+// CHECK-LABEL: define linkonce_odr noundef ptr @_Z19placement_constructI13PlacedWithPtrEPT_m(
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef {{.*}}){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+
// CHECK: [[META_INT]] = !{!"int", i1 false}
// CHECK: [[META_LONG]] = !{!"long", i1 false}
// CHECK: [[META_TESTCLASS]] = !{!"TestClass", i1 true}
+// CHECK: [[META_PLACEDNOPTR]] = !{!"PlacedNoPtr", i1 false}
+// CHECK: [[META_PLACEDWITHPTR]] = !{!"PlacedWithPtr", i1 true}
+// CHECK: [[META_CHAR]] = !{!"char", i1 false}
+// CHECK: [[META_DERIVEDWITHPTR]] = !{!"DerivedWithPtr", i1 true}
+// CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}
>From 60662addcc4e1af697adff89295063ba2876ff76 Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Thu, 19 Nov 2026 09:45:33 -0800
Subject: [PATCH 2/4] [Clang][AllocToken] Address post-merge review of
placement-new inference (#243991)
Follow-up to #241548:
- Skip collecting placement news in C, which has none. Otherwise every
function with an untyped allocation call (`malloc(n)`) had its body
traversed for nothing.
- Drop the look-through of trivial copy/move constructors in a
variable's initializer. With guaranteed copy elision the initializer is
the call itself, so this only affected class-typed results before C++17,
and it was not tested.
- Test reassignment of a class-typed variable (an operator call), and
drop the compound assignment, increment and constructor-argument cases,
which add no coverage.
---
clang/lib/AST/InferAlloc.cpp | 24 ++++-----------------
clang/lib/CodeGen/CGExpr.cpp | 8 +++++--
clang/test/CodeGenCXX/alloc-token.cpp | 31 ++++++++++-----------------
3 files changed, 21 insertions(+), 42 deletions(-)
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 6767b3bf4dd308..782ab2499a26db 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -207,24 +207,6 @@ static const Expr *stripFields(const Expr *E) {
return E;
}
-/// Finds the allocation call an initializer consists of, looking through
-/// parentheses, casts, temporaries, and the trivial copy or move a class-typed
-/// value may carry.
-static const CallExpr *initializingCall(const Expr *Init) {
- while (Init) {
- Init = Init->IgnoreImplicit()->IgnoreParenCasts();
- const auto *CE = dyn_cast<CXXConstructExpr>(Init);
- // A non-trivial copy or move may not be elided (-fno-elide-constructors)
- // and could replace the pointer.
- if (!CE || CE->getNumArgs() != 1 ||
- !CE->getConstructor()->isCopyOrMoveConstructor() ||
- !CE->getConstructor()->isTrivial())
- break;
- Init = CE->getArg(0);
- }
- return dyn_cast_or_null<CallExpr>(Init);
-}
-
namespace {
/// Implements collectPlacementNewTypes(). A variable qualifies if every
/// reference to it other than its initializer is an lvalue-to-rvalue read.
@@ -240,8 +222,10 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
}
bool VisitVarDecl(const VarDecl *VD) override {
- if (VD->hasLocalStorage() && !isa<ParmVarDecl>(VD))
- if (const CallExpr *CE = initializingCall(VD->getInit()))
+ const Expr *Init = VD->getInit();
+ if (Init && VD->hasLocalStorage() && !isa<ParmVarDecl>(VD))
+ if (const auto *CE =
+ dyn_cast<CallExpr>(Init->IgnoreImplicit()->IgnoreParenCasts()))
Defs.try_emplace(VD, CE);
return true;
}
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 844b5e4c28be92..7432f614039d61 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,13 +1407,17 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
}
llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
+ // C has no placement new, so there is nothing to collect.
+ if (!getLangOpts().CPlusPlus)
+ return buildAllocToken(
+ infer_alloc::inferPossibleType(E, getContext(), CurCast));
// The placement news of the enclosing function body are collected once, on
// the first allocation call that is not already typed by a sizeof.
- auto PlacementNewType = [this](const CallExpr *E) -> QualType {
+ auto PlacementNewType = [this](const CallExpr *Call) -> QualType {
if (!AllocTokenPlacementTypes)
AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
- return AllocTokenPlacementTypes->lookup(E);
+ return AllocTokenPlacementTypes->lookup(Call);
};
return buildAllocToken(infer_alloc::inferPossibleType(
E, getContext(), CurCast, PlacementNewType));
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 387d5ae83b79f8..7a38245c38ec3d 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -311,16 +311,12 @@ void test_placement_new_read_only_var(bool c) {
// Any use of the variable other than a read may change its value and
// disqualifies it: assignment (so the storage the placement new ends up in
// would depend on control flow, and the sizeof or cast of the other
-// allocation would be overridden), compound assignment, increment,
-// address-of, a write to one of its fields, a member call, binding to a
-// reference directly or as a call argument, and a by-reference capture.
-// Nothing is inferred for any of these allocations; with the variable
-// disqualified, the cast of the result still applies.
+// allocation would be overridden), including assignment of a class-typed
+// variable, address-of, a write to one of its fields, binding to a reference
+// directly or as a call argument, and a by-reference capture.
+// Nothing is inferred for any of these allocations.
void rebind(void *&p);
void peek(void *const &p);
-struct Rebinder {
- Rebinder(void *&p);
-};
// CHECK-LABEL: define dso_local void @_Z26test_placement_new_writtenb(
// CHECK: call noalias ptr @malloc(i64 noundef 8)
// CHECK-NOT: !alloc_token
@@ -336,13 +332,13 @@ struct Rebinder {
// CHECK-NOT: !alloc_token
// CHECK: call noalias ptr @malloc(i64 noundef 64)
// CHECK-NOT: !alloc_token
-// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR]]
-// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR]]
// CHECK: call noalias ptr @malloc(i64 noundef 64)
// CHECK-NOT: !alloc_token
// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
// CHECK-NOT: !alloc_token
-// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 32)
// CHECK-NOT: !alloc_token
// CHECK: call noalias ptr @malloc(i64 noundef 64)
// CHECK-NOT: !alloc_token
@@ -371,18 +367,16 @@ void test_placement_new_written(bool c) {
// The assignment of the placement new's result.
void *p4 = malloc(64);
p4 = new (p4) PlacedNoPtr();
- char *p5 = static_cast<char *>(malloc(64));
- p5 += 8;
- sink = new (p5) PlacedNoPtr();
- char *p6 = static_cast<char *>(malloc(64));
- ++p6;
- sink = new (p6) PlacedNoPtr();
void *p7 = malloc(64);
sink = &p7;
sink = new (p7) PlacedNoPtr();
Storage s = alloc_storage(64);
s.p = sink;
sink = new (s.p) PlacedNoPtr();
+ // A class-typed assignment is an operator call, not a BinaryOperator.
+ Storage s2 = alloc_storage(64);
+ s2 = alloc_storage(32);
+ sink = new (s2.p) PlacedNoPtr();
void *p8 = malloc(64);
void *&p8ref = p8;
p8ref = sink;
@@ -390,9 +384,6 @@ void test_placement_new_written(bool c) {
void *p9 = malloc(64);
rebind(p9);
sink = new (p9) PlacedNoPtr();
- void *p10 = malloc(64);
- Rebinder rebinder(p10);
- sink = new (p10) PlacedNoPtr();
// Binding to a const reference is not a read either.
void *p11 = malloc(64);
peek(p11);
>From f6c5cf969697b86f90697d62e6dc0cc4d4287951 Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Fri, 20 Nov 2026 18:43:07 -0800
Subject: [PATCH 3/4] [AllocToken] Use a pointer-free placement-new type only
if it covers the allocation
A placement new may construct only a header at the start of the
allocation, with other data, possibly pointers, after it:
void *ptr = malloc(size + kPrefix);
new (ptr) size_t(size); // pointers follow the header
new (::operator new(n)) Header(...); // pointerful entries follow
Such allocations got the pointer-free token, which is why #241548 and
#243991 were reverted in #244677. A pointer-free type from a placement new
is now used only if the allocation size is a constant equal to the type's
size, for an array new, or if the type ends in a flexible array member (or
an array treated as one under -fstrict-flex-arrays), whose elements are
assumed to fill the rest; e.g. absl's CordRepFlat, whose base ends in
`uint8_t storage[3]`. Otherwise the cast heuristic and the fallback token
apply, as before #241548. A type with pointers is always used.
Assisted-by: Gemini
---
clang/docs/AllocToken.md | 6 +-
clang/include/clang/AST/InferAlloc.h | 7 +-
clang/lib/AST/InferAlloc.cpp | 96 ++++++++++++++++++++++++---
clang/lib/CodeGen/CGExpr.cpp | 2 +-
clang/test/CodeGenCXX/alloc-token.cpp | 46 +++++++++++++
5 files changed, 142 insertions(+), 15 deletions(-)
diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index 092e4eb56f0679..c7a016e2fd9e79 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -66,7 +66,11 @@ heuristics are syntactic: `sizeof` expressions and casts ignore control flow
and reassignments, and a placement `new` through a variable is only used if
the variable is initialized by the allocation call and otherwise only read
(variables that are reassigned, or whose address or reference is taken, are
-not used for inference). If no type can be inferred, the allocation receives
+not used for inference). Since a placement `new` may construct only a header
+of the allocation, a pointer-free type from it is only used if the allocation
+size is a constant equal to the type's size, for an array `new`, or if the type
+ends in a flexible array member (or an array treated as one under
+`-fstrict-flex-arrays`). If no type can be inferred, the allocation receives
the fallback token.
## Querying Token IDs with `__builtin_infer_alloc_token`
diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index 79c65889d410d6..b9f86deec5a6c5 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -35,10 +35,11 @@ QualType inferPossibleType(
/// Maps the allocation calls in \p Body whose result is used as placement-new
/// storage to the constructed type (null if different types are constructed
-/// into it), e.g. `void *mem = alloc(n); new (mem) T();`. A local variable is
-/// only used if it is initialized by the call and otherwise only read.
+/// into it, or if a pointer-free type may not cover the whole allocation),
+/// e.g. `void *mem = alloc(n); new (mem) T();`. A local variable is only used
+/// if it is initialized by the call and otherwise only read.
llvm::DenseMap<const CallExpr *, QualType>
-collectPlacementNewTypes(const Stmt *Body);
+collectPlacementNewTypes(const Stmt *Body, const ASTContext &Ctx);
/// Get the information required for construction of an allocation token ID.
std::optional<llvm::AllocTokenMetadata>
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 782ab2499a26db..ff00eae209de70 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -12,6 +12,7 @@
#include "clang/AST/InferAlloc.h"
#include "clang/AST/ASTContext.h"
+#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
@@ -207,17 +208,89 @@ static const Expr *stripFields(const Expr *E) {
return E;
}
+/// The size allocated by \p CE if it is a constant: the arguments named by
+/// alloc_size, or the only argument.
+static std::optional<uint64_t> getConstantAllocSize(const CallExpr *CE,
+ const ASTContext &Ctx) {
+ SmallVector<const Expr *, 2> Args;
+ const FunctionDecl *FD = CE->getDirectCallee();
+ if (const auto *A = FD ? FD->getAttr<AllocSizeAttr>() : nullptr) {
+ Args.push_back(CE->getArg(A->getElemSizeParam().getASTIndex()));
+ if (A->getNumElemsParam().isValid())
+ Args.push_back(CE->getArg(A->getNumElemsParam().getASTIndex()));
+ } else if (CE->getNumArgs() == 1) {
+ Args.push_back(CE->getArg(0));
+ }
+ if (Args.empty())
+ return std::nullopt;
+ uint64_t Size = 1;
+ for (const Expr *Arg : Args) {
+ Expr::EvalResult R;
+ if (Arg->isValueDependent() || !Arg->EvaluateAsInt(R, Ctx))
+ return std::nullopt;
+ Size *= R.Val.getInt().getZExtValue();
+ }
+ return Size;
+}
+
+/// Whether \p T ends in a flexible array member, or an array treated as one
+/// under -fstrict-flex-arrays, possibly in its last field or only base.
+static bool endsInFlexibleArray(QualType T, const ASTContext &Ctx) {
+ const RecordDecl *RD = T->getAsRecordDecl();
+ while (RD && RD->isCompleteDefinition() && !RD->isUnion()) {
+ const FieldDecl *Last = nullptr;
+ for (const FieldDecl *FD : RD->fields())
+ Last = FD;
+ if (!Last) {
+ const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
+ if (!CXXRD || CXXRD->getNumBases() != 1)
+ return false;
+ RD = CXXRD->bases_begin()->getType()->getAsRecordDecl();
+ continue;
+ }
+ if (Last->getType()->isArrayType())
+ return Decl::isFlexibleArrayMemberLike(
+ Ctx, Last, Last->getType(),
+ Ctx.getLangOpts().getStrictFlexArraysLevel(),
+ /*IgnoreTemplateOrMacroSubstitution=*/true);
+ RD = Last->getType()->getAsRecordDecl();
+ }
+ return false;
+}
+
+/// Whether the object \p NE constructs into the storage allocated by \p CE
+/// describes all of it. It may construct only a header, with other data
+/// (possibly pointers) after it, e.g. `new (malloc(n + 8)) size_t(n)`. A
+/// pointer-free type is used only for a constant allocation of its size, an
+/// array new, or a type ending in a flexible array, whose elements are assumed
+/// to fill the rest.
+static bool coversAllocation(const CallExpr *CE, const CXXNewExpr *NE,
+ const ASTContext &Ctx) {
+ QualType T = NE->getAllocatedType();
+ llvm::SmallPtrSet<const RecordDecl *, 4> VisitedRD;
+ bool IncompleteType = false;
+ if (NE->isArray() || typeContainsPointer(T, VisitedRD, IncompleteType) ||
+ IncompleteType)
+ return true;
+ std::optional<uint64_t> Size = getConstantAllocSize(CE, Ctx);
+ if (Size && *Size == uint64_t(Ctx.getTypeSizeInChars(T).getQuantity()))
+ return true;
+ return endsInFlexibleArray(T, Ctx);
+}
+
namespace {
/// Implements collectPlacementNewTypes(). A variable qualifies if every
/// reference to it other than its initializer is an lvalue-to-rvalue read.
class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
public:
+ explicit PlacementNewCollector(const ASTContext &Ctx) : Ctx(Ctx) {}
+
// Resolved after the traversal: a use that is not a read may follow the
// placement new and still disqualify the variable.
llvm::DenseMap<const CallExpr *, QualType> finish() && {
- for (const auto &[VD, T] : Uses)
+ for (const auto &[VD, NE] : Uses)
if (const CallExpr *CE = Defs.lookup(VD))
- record(CE, T);
+ record(CE, NE);
return std::move(CallTypes);
}
@@ -257,36 +330,39 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
return true;
const Expr *Source =
stripFields(NE->getPlacementArg(0)->IgnoreParenCasts());
- QualType T = NE->getAllocatedType();
if (const auto *CE = dyn_cast<CallExpr>(Source))
- record(CE, T);
+ record(CE, NE);
else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
- Uses.emplace_back(VD, T);
+ Uses.emplace_back(VD, NE);
return true;
}
private:
- void record(const CallExpr *CE, QualType T) {
+ void record(const CallExpr *CE, const CXXNewExpr *NE) {
+ QualType T =
+ coversAllocation(CE, NE, Ctx) ? NE->getAllocatedType() : QualType();
auto [It, Inserted] = CallTypes.try_emplace(CE, T);
// Different types constructed into the same storage: ambiguous.
if (!Inserted && !It->second.isNull() &&
- It->second.getCanonicalType() != T.getCanonicalType())
+ (T.isNull() || It->second.getCanonicalType() != T.getCanonicalType()))
It->second = QualType();
}
+ const ASTContext &Ctx;
+
llvm::DenseMap<const CallExpr *, QualType> CallTypes;
// Variable -> the allocation call initializing it; erased on any use that
// is not a read.
llvm::DenseMap<const VarDecl *, const CallExpr *> Defs;
llvm::SmallPtrSet<const DeclRefExpr *, 16> Reads;
- llvm::SmallVector<std::pair<const VarDecl *, QualType>> Uses;
+ llvm::SmallVector<std::pair<const VarDecl *, const CXXNewExpr *>> Uses;
};
} // namespace
llvm::DenseMap<const CallExpr *, QualType>
-infer_alloc::collectPlacementNewTypes(const Stmt *Body) {
- PlacementNewCollector Collector;
+infer_alloc::collectPlacementNewTypes(const Stmt *Body, const ASTContext &Ctx) {
+ PlacementNewCollector Collector(Ctx);
if (Body)
Collector.TraverseStmt(Body);
return std::move(Collector).finish();
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 7432f614039d61..3cbff3223cf7fe 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1416,7 +1416,7 @@ llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
auto PlacementNewType = [this](const CallExpr *Call) -> QualType {
if (!AllocTokenPlacementTypes)
AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
- CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
+ CurCodeDecl ? CurCodeDecl->getBody() : nullptr, getContext());
return AllocTokenPlacementTypes->lookup(Call);
};
return buildAllocToken(infer_alloc::inferPossibleType(
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 7a38245c38ec3d..edffd6a6c4143a 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -439,6 +439,49 @@ void test_placement_new_lambda() {
construct2(PlacedNoPtr{});
}
+// The placed object may be only a header, with other data (possibly pointers)
+// after it. A pointer-free type is used only for a constant allocation of its
+// size, an array new, or a type ending in a flexible array (possibly in its
+// last field or only base).
+struct PlacedHeader {
+ long len;
+ int n;
+};
+struct FlatBase {
+ long len;
+ int refcount;
+ unsigned char tag;
+ unsigned char storage[3];
+};
+struct Flat : FlatBase {};
+struct NestedFlat {
+ int n;
+ PlacedNoPtr tail;
+};
+// CHECK-LABEL: define dso_local void @_Z24test_placement_new_coverm(
+// CHECK: call noalias ptr @malloc(i64 noundef %{{.*}})
+// CHECK-NOT: !alloc_token
+// CHECK: call {{.*}}@_Znwm(i64 noundef %{{.*}})
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: !alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDHEADER:![0-9]+]]
+// CHECK: call noalias ptr @malloc(i64 noundef %{{.*}}){{.*}} !alloc_token [[META_PLACEDHEADER]]
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef %{{.*}}){{.*}} !alloc_token [[META_FLAT:![0-9]+]]
+// CHECK: call noalias ptr @malloc(i64 noundef %{{.*}}){{.*}} !alloc_token [[META_NESTEDFLAT:![0-9]+]]
+// CHECK: call noalias ptr @malloc(i64 noundef %{{.*}}){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+void test_placement_new_cover(size_t n) {
+ void *ptr = malloc(n + 8);
+ size_t *count = new (ptr) size_t(n);
+ PlacedHeader *h1 = new (::operator new(n)) PlacedHeader();
+ PlacedHeader *h2 = new (malloc(64)) PlacedHeader();
+ PlacedHeader *h3 = new (malloc(16)) PlacedHeader();
+ PlacedHeader *h4 = new (malloc(n)) PlacedHeader[4];
+ Flat *f = new (__size_returning_new(n).p) Flat();
+ NestedFlat *nf = new (malloc(n)) NestedFlat();
+ PlacedWithPtr *wp = new (malloc(n)) PlacedWithPtr();
+}
+
template <typename T>
T *placement_construct(size_t size) {
__sized_ptr_t res = __size_returning_new(size);
@@ -466,3 +509,6 @@ void test_placement_new_template() {
// CHECK: [[META_CHAR]] = !{!"char", i1 false}
// CHECK: [[META_DERIVEDWITHPTR]] = !{!"DerivedWithPtr", i1 true}
// CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}
+// CHECK: [[META_PLACEDHEADER]] = !{!"PlacedHeader", i1 false}
+// CHECK: [[META_FLAT]] = !{!"Flat", i1 false}
+// CHECK: [[META_NESTEDFLAT]] = !{!"NestedFlat", i1 false}
>From 5f6c00da85fd1688fc8a6f367874cc095fe7ca95 Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Sun, 22 Nov 2026 20:19:50 -0800
Subject: [PATCH 4/4] [AllocToken] Propagate !alloc_token through inlined
malloc_span wrappers
#198535 propagates an inlined allocation wrapper's !alloc_token to the
allocation call whose result the wrapper returns, but only follows
pointer-typed return values, so a malloc_span wrapper such as
__attribute__((always_inline, malloc_span))
sized_ptr_t sro_new(size_t n) { return __size_returning_new(n); }
left __size_returning_new with the fallback token.
Follow the returned value as a whole, of any type, through casts, phis and
selects, and through a load of a local temporary from the value last
stored to it in the same block (FindAvailableLoadedValue), as before SROA.
Spans assembled from their fields are not followed: in particular
field-wise stores to the return temporary (x86-64 before SROA), sret
returns, and temporaries filled by memcpy keep the fallback token.
Assisted-by: Gemini
---
clang/docs/AllocToken.md | 7 +-
llvm/lib/Transforms/Utils/InlineFunction.cpp | 30 +++--
llvm/test/Transforms/Inline/alloc-token.ll | 123 +++++++++++++++++++
3 files changed, 148 insertions(+), 12 deletions(-)
diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index c7a016e2fd9e79..3ebfc890757107 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -189,10 +189,13 @@ ptr2 = __alloc_token_my_malloc(size, token_id);
```
Note: Even in the default mode (without `-fsanitize-alloc-token-extended`),
-an *inline* allocation wrapper marked with the [malloc][malloc-attribute] or
-[alloc_size][alloc-size-attribute] attribute is
+an *inline* allocation wrapper marked with the [malloc][malloc-attribute],
+`malloc_span`, or [alloc_size][alloc-size-attribute] attribute is
supported if it is inlined into its caller: the inferred token is propagated to
the allocation call the wrapper returns, which is then instrumented normally.
+The wrapper must return the allocation call's result unchanged, e.g.
+`return __size_returning_new(size);`; a span assembled from its fields is not
+supported.
Wrappers that are not inlined still require
`-fsanitize-alloc-token-extended`.
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 918c8c02493bd5..5a9f0341674fca 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -26,6 +26,7 @@
#include "llvm/Analysis/CtxProfAnalysis.h"
#include "llvm/Analysis/IndirectCallVisitor.h"
#include "llvm/Analysis/InstructionSimplify.h"
+#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/MemoryProfileInfo.h"
#include "llvm/Analysis/ObjCARCAnalysisUtils.h"
#include "llvm/Analysis/ObjCARCUtil.h"
@@ -935,25 +936,34 @@ propagateMemProfMetadata(Function *Callee, CallBase &CB,
}
}
-/// Collect all calls that produce RetVal, following only pointer-preserving
-/// instructions (cast, phi, select).
-static void collectPointerReturningCalls(Value *RetVal,
- SmallVectorImpl<CallBase *> &Out) {
+/// Collect the calls whose result RetVal returns as a whole, following casts,
+/// phis, selects, and a load of a local temporary from the value last stored
+/// to it in the same block (as emitted before SROA, e.g. when an always_inline
+/// wrapper is inlined at -O0).
+static void collectReturnedCalls(Value *RetVal,
+ SmallVectorImpl<CallBase *> &Out) {
SmallVector<Value *, 8> Worklist{RetVal};
SmallPtrSet<Value *, 8> Visited;
while (!Worklist.empty()) {
Value *V = Worklist.pop_back_val();
- if (!V->getType()->isPointerTy() || !Visited.insert(V).second)
+ if (!Visited.insert(V).second)
continue;
- if (auto *CB = dyn_cast<CallBase>(V))
+ if (auto *CB = dyn_cast<CallBase>(V)) {
Out.push_back(CB);
- else if (isa<BitCastInst, AddrSpaceCastInst>(V))
+ } else if (isa<BitCastInst, AddrSpaceCastInst>(V)) {
Worklist.push_back(cast<CastInst>(V)->getOperand(0));
- else if (auto *PN = dyn_cast<PHINode>(V))
+ } else if (auto *PN = dyn_cast<PHINode>(V)) {
append_range(Worklist, PN->incoming_values());
- else if (auto *SI = dyn_cast<SelectInst>(V)) {
+ } else if (auto *SI = dyn_cast<SelectInst>(V)) {
Worklist.push_back(SI->getTrueValue());
Worklist.push_back(SI->getFalseValue());
+ } else if (auto *LI = dyn_cast<LoadInst>(V)) {
+ if (!isa<AllocaInst>(LI->getPointerOperand()->stripPointerCasts()))
+ continue;
+ BasicBlock::iterator ScanFrom = LI->getIterator();
+ Value *Stored = FindAvailableLoadedValue(LI, LI->getParent(), ScanFrom);
+ if (Stored && Stored->getType() == LI->getType())
+ Worklist.push_back(Stored);
}
}
}
@@ -974,7 +984,7 @@ propagateAllocTokenMetadata(Function *CalledFunc, CallBase &CB,
for (BasicBlock &BB : *CalledFunc)
if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator()))
if (Value *RV = RI->getReturnValue())
- collectPointerReturningCalls(RV, AllocCalls);
+ collectReturnedCalls(RV, AllocCalls);
for (CallBase *OrigCall : AllocCalls) {
auto *ClonedCall = dyn_cast_or_null<CallBase>(VMap.lookup(OrigCall));
diff --git a/llvm/test/Transforms/Inline/alloc-token.ll b/llvm/test/Transforms/Inline/alloc-token.ll
index 99ab7160050508..dbf0c6317e081a 100644
--- a/llvm/test/Transforms/Inline/alloc-token.ll
+++ b/llvm/test/Transforms/Inline/alloc-token.ll
@@ -44,6 +44,129 @@ define ptr @overwrite_unknown() {
ret ptr %c
}
+declare { ptr, i64 } @__size_returning_new(i64)
+declare [2 x i64] @alloc_coerced(i64)
+declare { ptr, i8 } @find_or_insert(i64)
+
+; A malloc_span wrapper's allocation inherits the token when the span is
+; returned as a whole: directly, through a phi, or through a local temporary
+; it is stored to and loaded from (as before SROA; here coerced to [2 x i64]
+; as on AArch64).
+define internal { ptr, i64 } @span_direct(i64 %size) alwaysinline {
+ %s = call { ptr, i64 } @__size_returning_new(i64 %size)
+ ret { ptr, i64 } %s
+}
+
+define internal [2 x i64] @span_temporary(i64 %size) alwaysinline {
+ %retval = alloca { ptr, i64 }
+ %s = call [2 x i64] @alloc_coerced(i64 %size)
+ store [2 x i64] %s, ptr %retval
+ %r = load [2 x i64], ptr %retval
+ ret [2 x i64] %r
+}
+
+; The span from a non-allocating call, rebuilt from its fields, is not followed.
+define internal { ptr, i64 } @span_phi(i64 %size, i1 %c) alwaysinline {
+entry:
+ br i1 %c, label %reuse, label %fresh
+reuse:
+ %f = call { ptr, i8 } @find_or_insert(i64 %size)
+ %p = extractvalue { ptr, i8 } %f, 0
+ %s0 = insertvalue { ptr, i64 } poison, ptr %p, 0
+ %s1 = insertvalue { ptr, i64 } %s0, i64 %size, 1
+ br label %done
+fresh:
+ %n = call { ptr, i64 } @__size_returning_new(i64 %size)
+ br label %done
+done:
+ %r = phi { ptr, i64 } [ %s1, %reuse ], [ %n, %fresh ]
+ ret { ptr, i64 } %r
+}
+
+; CHECK-LABEL: define void @span_whole(
+; CHECK: call { ptr, i64 } @__size_returning_new(i64 4){{.*}}, !alloc_token [[MD]]
+; CHECK: call [2 x i64] @alloc_coerced(i64 4){{.*}}, !alloc_token [[MD]]
+; CHECK: call { ptr, i8 } @find_or_insert(i64 4){{$}}
+; CHECK: call { ptr, i64 } @__size_returning_new(i64 4){{.*}}, !alloc_token [[MD]]
+define void @span_whole(i1 %c) {
+ %a = call { ptr, i64 } @span_direct(i64 4), !alloc_token !0
+ %b = call [2 x i64] @span_temporary(i64 4), !alloc_token !0
+ %d = call { ptr, i64 } @span_phi(i64 4, i1 %c), !alloc_token !0
+ ret void
+}
+
+; A span assembled field by field in a temporary (as Clang emits on x86-64
+; before SROA) is not followed.
+define internal { ptr, i64 } @span_fields(i64 %size) alwaysinline {
+ %retval = alloca { ptr, i64 }
+ %s = call { ptr, i64 } @__size_returning_new(i64 %size)
+ %p = extractvalue { ptr, i64 } %s, 0
+ store ptr %p, ptr %retval
+ %n.addr = getelementptr inbounds { ptr, i64 }, ptr %retval, i32 0, i32 1
+ %n = extractvalue { ptr, i64 } %s, 1
+ store i64 %n, ptr %n.addr
+ %r = load { ptr, i64 }, ptr %retval
+ ret { ptr, i64 } %r
+}
+
+; CHECK-LABEL: define void @span_fields_unsupported(
+; CHECK: call { ptr, i64 } @__size_returning_new(i64 4){{$}}
+define void @span_fields_unsupported() {
+ %a = call { ptr, i64 } @span_fields(i64 4), !alloc_token !0
+ ret void
+}
+
+; A pointer wrapper returning through a temporary: the call whose result is
+; last stored before the load inherits the token, an earlier one does not.
+define internal ptr @ptr_temporary(i64 %size) alwaysinline {
+ %p = alloca ptr
+ %h = call ptr @helper()
+ store ptr %h, ptr %p
+ %m = call ptr @malloc(i64 %size)
+ store ptr %m, ptr %p
+ %r = load ptr, ptr %p
+ ret ptr %r
+}
+
+; A call that may write memory between the store and the load stops it.
+define internal ptr @ptr_clobbered(i64 %size) alwaysinline {
+ %p = alloca ptr
+ %m = call ptr @malloc(i64 %size)
+ store ptr %m, ptr %p
+ %h = call ptr @helper()
+ %r = load ptr, ptr %p
+ ret ptr %r
+}
+
+; CHECK-LABEL: define void @ptr_temporaries(
+; CHECK: call ptr @helper(){{$}}
+; CHECK: call ptr @malloc(i64 4){{.*}}, !alloc_token [[MD]]
+; CHECK: call ptr @malloc(i64 4){{$}}
+; CHECK: call ptr @helper(){{$}}
+define void @ptr_temporaries() {
+ %a = call ptr @ptr_temporary(i64 4), !alloc_token !0
+ %b = call ptr @ptr_clobbered(i64 4), !alloc_token !0
+ ret void
+}
+
+; A pointer taken out of a non-span struct such as {ptr, i8} returned by a
+; non-allocating call is not followed.
+define internal ptr @ptr_field(i64 %size, i1 %c) alwaysinline {
+ %f = call { ptr, i8 } @find_or_insert(i64 %size)
+ %p = extractvalue { ptr, i8 } %f, 0
+ %m = call ptr @malloc(i64 %size)
+ %r = select i1 %c, ptr %p, ptr %m
+ ret ptr %r
+}
+
+; CHECK-LABEL: define void @ptr_from_field(
+; CHECK: call { ptr, i8 } @find_or_insert(i64 4){{$}}
+; CHECK: call ptr @malloc(i64 4){{.*}}, !alloc_token [[MD]]
+define void @ptr_from_field(i1 %c) {
+ %a = call ptr @ptr_field(i64 4, i1 %c), !alloc_token !0
+ ret void
+}
+
; CHECK-DAG: [[MD]] = !{!"Outer", i1 true}
; CHECK-DAG: [[OWN]] = !{!"Inner", i1 false}
; CHECK-DAG: [[CALLER]] = !{!"Outer", i1 true, !"overwrite_unknown"}
More information about the cfe-commits
mailing list