[clang] [AllocToken] Infer the allocated type from placement new into the result (PR #241548)

David Li via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 17 23:09:31 PST 2026


https://github.com/david-xl updated https://github.com/llvm/llvm-project/pull/241548

>From 20efd37de41849dda7b7a10c0598566f58a802ce Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 13:18:40 -0800
Subject: [PATCH 1/9] [AllocToken] Infer the allocated type from placement new
 into the result

-fsanitize=alloc-token infers the allocated type of an untyped allocation
call (malloc, size-returning new, or any malloc/alloc_size function) from
a sizeof in its size argument or from a cast of its result. A common
idiom has neither: the code allocates raw storage and then constructs the
object in place,

  void *mem = alloc(size);
  T *obj = new (mem) T();

  sized_ptr res = size_returning_alloc(size);
  T *rep = new (res.p) T();

Such allocations currently get no type and therefore the fallback token,
which with a pointer-split token mode puts pointer-free objects into the
pointer-containing partition. In one large C++ code base this pattern
(an absl::Cord flat node allocated this way) accounts for ~40% of all
fallback-token memory that a type-aware profile marks as cold.

Add a third inference step: if no sizeof or cast names the type, look
for a placement new whose single placement argument is the allocation
call's result, either directly, through casts, parentheses or member
accesses (e.g. the pointer member of a size-returning allocation), or
via a local variable initialized with it. The placement-new uses of the
enclosing function body are collected once, lazily, per function
(infer_alloc::PlacementNewTypes, owned by CodeGenFunction). If different
types are constructed into the same storage, nothing is inferred. Like
the existing heuristics this ignores control flow and reassignments.
Custom placement operators (new (arena) T) are not affected since the
storage is not their placement argument. __builtin_infer_alloc_token is
unchanged, as it has no enclosing allocation to inspect.

Assisted-by: Gemini
---
 clang/docs/AllocToken.md              |  28 ++++++
 clang/docs/ReleaseNotes.md            |   7 ++
 clang/include/clang/AST/InferAlloc.h  |  50 ++++++++++-
 clang/lib/AST/InferAlloc.cpp          | 123 +++++++++++++++++++++++++-
 clang/lib/CodeGen/CGExpr.cpp          |   7 +-
 clang/lib/CodeGen/CodeGenFunction.h   |   6 ++
 clang/test/CodeGenCXX/alloc-token.cpp | 106 ++++++++++++++++++++++
 7 files changed, 323 insertions(+), 4 deletions(-)

diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index cca7136b652abd..6e6c9d4c84327a 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -56,6 +56,34 @@ 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. For allocation functions
+such as `malloc` that return untyped memory, the type is inferred from the
+allocation call and its surroundings, in this order:
+
+- A `sizeof` in a size argument, possibly in arithmetic:
+  `malloc(sizeof(T))`, `malloc(n * sizeof(T))`, `malloc(sizeof(T) + extra)`,
+  or a variable initialized from such an expression.
+- A cast of the result: `(T *)malloc(n)`.
+- Placement new into the result: `new (malloc(n)) T`, or, through a local
+  variable and optionally a cast or member access of the result,
+
+  ```c++
+  void *mem = alloc(n);
+  T *obj = new (mem) T;              // infers 'T' for alloc(n)
+
+  sized_ptr res = size_returning_alloc(n);
+  T *obj = new (res.p) T;            // infers 'T' for size_returning_alloc(n)
+  ```
+
+  If different types are constructed into the same storage, no type is
+  inferred.
+
+These are heuristics: they ignore control flow and reassignments of the
+variables involved. 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 72db5e7074108b..a945546b46610e 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1554,6 +1554,13 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
   modes for `-fsanitize=alloc-token`, selected with
   `-Xclang -falloc-token-mode=<mode>`. These modes derive token IDs from both
   the allocated type and the name of the function containing the allocation.
+- `-fsanitize=alloc-token` type inference now also recognizes memory that is
+  used as placement-new storage: for `new (p) T`, where `p` is the result of an
+  allocation call (directly, through a cast or member access such as the
+  pointer of a size-returning allocation, or via a local variable initialized
+  with it), the allocation is attributed to `T`. This covers the common
+  "allocate raw storage, then construct in place" idiom, which previously
+  received no type and therefore the fallback token.
 
 ### Python Binding Changes
 
diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index c3dc30204feafe..b6a6b28e1ba419 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -15,15 +15,63 @@
 
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/Support/AllocToken.h"
 #include <optional>
 
 namespace clang {
+
+class Stmt;
+class VarDecl;
+
 namespace infer_alloc {
 
+/// Lazily collects, for one function body, the types constructed by placement
+/// new into memory returned by allocation calls. This lets the allocated type
+/// be inferred for the common "allocate raw storage, then placement-new the
+/// object into it" idiom, where neither a sizeof nor a cast names the type:
+///
+///   void *mem = alloc(size);
+///   MyType *obj = new (mem) MyType();  // infers 'MyType' for alloc(size)
+///
+///   auto res = size_returning_alloc(size);
+///   new (res.p) MyType();              // infers 'MyType' (via member .p)
+///
+///   new (alloc(size)) MyType();        // infers 'MyType'
+///
+/// The placement argument may be wrapped in parentheses, casts, or member
+/// accesses of the call result (or of a local variable initialized with it).
+/// If placement news of different types use the same allocation, no type is
+/// inferred. Like the other inference heuristics, this ignores control flow
+/// and reassignments of the variable.
+class PlacementNewTypes {
+public:
+  explicit PlacementNewTypes(const Stmt *Body) : Body(Body) {}
+
+  /// Returns the type placement-constructed into the result of allocation call
+  /// \p E, or a null type if there is none or it is ambiguous.
+  QualType lookup(const CallExpr *E);
+
+private:
+  void collect();
+
+  const Stmt *Body;
+  bool Collected = false;
+  // Allocation call -> placement-new type (null if ambiguous).
+  llvm::DenseMap<const CallExpr *, QualType> CallTypes;
+  // Variable -> placement-new type of its contents (null if ambiguous).
+  llvm::DenseMap<const VarDecl *, QualType> VarTypes;
+  // Allocation call -> variable it initializes.
+  llvm::DenseMap<const CallExpr *, const VarDecl *> CallVars;
+};
+
 /// Infer the possible allocated type from an allocation call expression.
+/// \p CastE is the cast the call result is immediately used in, if any, and
+/// \p PlacementTypes the placement-new types of the enclosing function, if
+/// available.
 QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
-                           const CastExpr *CastE);
+                           const CastExpr *CastE,
+                           PlacementNewTypes *PlacementTypes = nullptr);
 
 /// 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..5f665d7bee115d 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -15,6 +15,8 @@
 #include "clang/AST/Decl.h"
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/Expr.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -169,7 +171,8 @@ static QualType inferPossibleTypeFromCastExpr(const CallExpr *CallE,
 
 QualType infer_alloc::inferPossibleType(const CallExpr *E,
                                         const ASTContext &Ctx,
-                                        const CastExpr *CastE) {
+                                        const CastExpr *CastE,
+                                        PlacementNewTypes *PlacementTypes) {
   QualType AllocType;
   // First check arguments.
   for (const Expr *Arg : E->arguments()) {
@@ -182,9 +185,127 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
   // Then check later casts.
   if (AllocType.isNull())
     AllocType = inferPossibleTypeFromCastExpr(E, CastE);
+  // Finally check if the result is used as placement-new storage.
+  if (AllocType.isNull() && PlacementTypes)
+    AllocType = PlacementTypes->lookup(E);
   return AllocType;
 }
 
+namespace {
+/// Strips the wrappers a placement argument may have around the expression
+/// that produced the storage: parentheses, casts, member accesses (e.g. the
+/// pointer member of a size-returning allocation result), and
+/// address-of/dereference pairs.
+const Expr *stripToStorageSource(const Expr *E) {
+  while (true) {
+    E = E->IgnoreParenCasts();
+    if (const auto *ME = dyn_cast<MemberExpr>(E)) {
+      E = ME->getBase();
+      continue;
+    }
+    if (const auto *UO = dyn_cast<UnaryOperator>(E);
+        UO && (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref)) {
+      E = UO->getSubExpr();
+      continue;
+    }
+    return E;
+  }
+}
+
+/// Finds the allocation call that initializes a variable, looking through the
+/// temporaries and elidable copies a class-typed initializer may carry.
+const CallExpr *initializingCall(const Expr *Init) {
+  while (Init) {
+    Init = Init->IgnoreParenImpCasts();
+    if (const auto *EWC = dyn_cast<ExprWithCleanups>(Init)) {
+      Init = EWC->getSubExpr();
+    } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
+      Init = MTE->getSubExpr();
+    } else if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) {
+      Init = BTE->getSubExpr();
+    } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Init);
+               CE && CE->getNumArgs() == 1 &&
+               (CE->isElidable() ||
+                CE->getConstructor()->isCopyOrMoveConstructor())) {
+      Init = CE->getArg(0);
+    } else if (const auto *FCE = dyn_cast<CXXFunctionalCastExpr>(Init)) {
+      Init = FCE->getSubExpr();
+    } else {
+      break;
+    }
+  }
+  return dyn_cast_or_null<CallExpr>(Init);
+}
+
+/// Records placement-new types per allocation call and per variable.
+class PlacementNewCollector
+    : public RecursiveASTVisitor<PlacementNewCollector> {
+public:
+  PlacementNewCollector(
+      llvm::DenseMap<const CallExpr *, QualType> &CallTypes,
+      llvm::DenseMap<const VarDecl *, QualType> &VarTypes,
+      llvm::DenseMap<const CallExpr *, const VarDecl *> &CallVars)
+      : CallTypes(CallTypes), VarTypes(VarTypes), CallVars(CallVars) {}
+
+  bool shouldVisitTemplateInstantiations() const { return true; }
+  bool shouldVisitImplicitCode() const { return true; }
+
+  bool VisitVarDecl(const VarDecl *VD) {
+    if (const CallExpr *CE = initializingCall(VD->getInit()))
+      CallVars.try_emplace(CE, VD);
+    return true;
+  }
+
+  bool VisitCXXNewExpr(const CXXNewExpr *NE) {
+    // Only the standard non-allocating placement form, new (storage) T, takes
+    // the storage as its single placement argument.
+    if (NE->getNumPlacementArgs() != 1)
+      return true;
+    const Expr *Source = stripToStorageSource(NE->getPlacementArg(0));
+    QualType T = NE->getAllocatedType();
+    if (const auto *CE = dyn_cast<CallExpr>(Source))
+      record(CallTypes, CE, T);
+    else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
+      if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
+        record(VarTypes, VD, T);
+    return true;
+  }
+
+private:
+  template <typename Key>
+  static void record(llvm::DenseMap<Key, QualType> &Map, Key K, QualType T) {
+    auto [It, Inserted] = Map.try_emplace(K, 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;
+  llvm::DenseMap<const VarDecl *, QualType> &VarTypes;
+  llvm::DenseMap<const CallExpr *, const VarDecl *> &CallVars;
+};
+} // namespace
+
+void PlacementNewTypes::collect() {
+  Collected = true;
+  if (!Body)
+    return;
+  PlacementNewCollector Collector(CallTypes, VarTypes, CallVars);
+  Collector.TraverseStmt(const_cast<Stmt *>(Body));
+}
+
+QualType PlacementNewTypes::lookup(const CallExpr *E) {
+  if (!Collected)
+    collect();
+  if (auto It = CallTypes.find(E); It != CallTypes.end())
+    return It->second;
+  if (auto VarIt = CallVars.find(E); VarIt != CallVars.end())
+    if (auto It = VarTypes.find(VarIt->second); It != VarTypes.end())
+      return It->second;
+  return QualType();
+}
+
 std::optional<llvm::AllocTokenMetadata>
 infer_alloc::getAllocTokenMetadata(QualType T, const ASTContext &Ctx) {
   llvm::AllocTokenMetadata ATMD;
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index ae5f4e723f5129..33d6d1e4d45a4e 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,8 +1407,11 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
 }
 
 llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
-  return buildAllocToken(
-      infer_alloc::inferPossibleType(E, getContext(), CurCast));
+  if (!AllocTokenPlacementTypes)
+    AllocTokenPlacementTypes = std::make_unique<infer_alloc::PlacementNewTypes>(
+        CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
+  return buildAllocToken(infer_alloc::inferPossibleType(
+      E, getContext(), CurCast, AllocTokenPlacementTypes.get()));
 }
 
 void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index 2c7820ec572253..d8545b86aae928 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -26,6 +26,7 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
+#include "clang/AST/InferAlloc.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
 #include "clang/AST/StmtSYCL.h"
@@ -375,6 +376,11 @@ class CodeGenFunction : public CodeGenTypeCache {
   /// expression.
   const CastExpr *CurCast = nullptr;
 
+  /// Placement-new types of the current function body, collected lazily for
+  /// -fsanitize=alloc-token type inference (see
+  /// infer_alloc::PlacementNewTypes).
+  std::unique_ptr<infer_alloc::PlacementNewTypes> 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 98842206dfc000..0f2310bb9331c2 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -150,6 +150,112 @@ 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.
+
+// 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_localv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR:![0-9]+]]
+PlacedWithPtr *test_placement_new_local() {
+  void *mem = malloc(64);
+  if (!mem)
+    return nullptr;
+  return new (mem) PlacedWithPtr();
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z30test_placement_new_sized_localv(
+// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_sized_local() {
+  __sized_ptr_t res = __size_returning_new(64);
+  PlacedNoPtr *rep = new (res.p) PlacedNoPtr();
+  rep->len = res.n;
+  return rep;
+}
+
+// CHECK-LABEL: define dso_local noundef ptr @_Z29test_placement_new_sized_castv(
+// CHECK: call { ptr, i64 } @__size_returning_new_hot_cold(i64 noundef 64, i8 noundef zeroext 1){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_sized_cast() {
+  auto res = __size_returning_new_hot_cold(64, __hot_cold_t{1});
+  return new (static_cast<char *>(res.p)) 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 or a cast of the result still takes precedence.
+// CHECK-LABEL: define dso_local noundef ptr @_Z34test_placement_new_sizeof_prevailsv(
+// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+PlacedNoPtr *test_placement_new_sizeof_prevails() {
+  void *mem = malloc(sizeof(PlacedWithPtr));
+  return new (mem) PlacedNoPtr();
+}
+
+// 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();
+}
+
+// Custom placement operators do not take the storage as placement argument, so
+// the malloc stays untyped (the custom operator new call itself is typed).
+struct Arena {};
+void *operator new(size_t, Arena &);
+// CHECK-LABEL: define dso_local void @_Z24test_placement_new_arenaR5Arena(
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+// CHECK: call noundef ptr @_ZnwmR5Arena(i64 noundef 16, {{.*}} !alloc_token [[META_PLACEDNOPTR]]
+void test_placement_new_arena(Arena &arena) {
+  sink = malloc(64);
+  sink = new (arena) 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}

>From 294e6290e76f4fdaff42668c7c69ecce6fab732b Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 14:46:40 -0800
Subject: [PATCH 2/9] Address review: stop at -> and unmatched &/*, require
 reserved placement operator new

- Only look through non-arrow member accesses of a by-value result and
  cancelling &*/*& pairs; indirect accesses and unmatched operators stop.
- Require the resolved operator new to be the reserved global placement
  form, as EmitCXXNewExpr does.
- Add regression tests and document the limits.
---
 clang/docs/AllocToken.md              |  6 +++-
 clang/lib/AST/InferAlloc.cpp          | 27 +++++++++++-----
 clang/test/CodeGenCXX/alloc-token.cpp | 44 +++++++++++++++++++++++++++
 3 files changed, 69 insertions(+), 8 deletions(-)

diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index 6e6c9d4c84327a..1641f026e24d6c 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -78,7 +78,11 @@ allocation call and its surroundings, in this order:
   ```
 
   If different types are constructed into the same storage, no type is
-  inferred.
+  inferred. Only the reserved non-allocating placement form
+  `::operator new(size_t, void *)` is considered; user-provided placement
+  operators may construct elsewhere. Likewise, indirect member accesses
+  (`h->p`) and unmatched `&`/`*` name storage other than the allocation and
+  are not looked through.
 
 These are heuristics: they ignore control flow and reassignments of the
 variables involved. If no type can be inferred, the allocation receives the
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 5f665d7bee115d..36425c4062ee1a 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -193,19 +193,28 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
 
 namespace {
 /// Strips the wrappers a placement argument may have around the expression
-/// that produced the storage: parentheses, casts, member accesses (e.g. the
-/// pointer member of a size-returning allocation result), and
-/// address-of/dereference pairs.
+/// that produced the storage: parentheses, casts, direct (non-arrow) member
+/// accesses of a by-value result (e.g. the pointer member of a size-returning
+/// allocation result), and cancelling `&*` / `*&` pairs. Anything that follows
+/// a pointer into different storage (`->`, an unmatched dereference) or takes
+/// the address of a different object (an unmatched address-of) stops the walk.
 const Expr *stripToStorageSource(const Expr *E) {
   while (true) {
     E = E->IgnoreParenCasts();
     if (const auto *ME = dyn_cast<MemberExpr>(E)) {
+      if (ME->isArrow())
+        return E;
       E = ME->getBase();
       continue;
     }
     if (const auto *UO = dyn_cast<UnaryOperator>(E);
         UO && (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref)) {
-      E = UO->getSubExpr();
+      const auto *Inner =
+          dyn_cast<UnaryOperator>(UO->getSubExpr()->IgnoreParens());
+      if (!Inner || Inner->getOpcode() == UO->getOpcode() ||
+          (Inner->getOpcode() != UO_AddrOf && Inner->getOpcode() != UO_Deref))
+        return E;
+      E = Inner->getSubExpr();
       continue;
     }
     return E;
@@ -257,9 +266,13 @@ class PlacementNewCollector
   }
 
   bool VisitCXXNewExpr(const CXXNewExpr *NE) {
-    // Only the standard non-allocating placement form, new (storage) T, takes
-    // the storage as its single placement argument.
-    if (NE->getNumPlacementArgs() != 1)
+    // Only the reserved non-allocating placement form, new (storage) T, is
+    // guaranteed to construct into its single placement argument. A
+    // class-specific or otherwise user-provided operator new(size_t, void *)
+    // may treat the argument as allocator state and return other storage.
+    const FunctionDecl *OperatorNew = NE->getOperatorNew();
+    if (NE->getNumPlacementArgs() != 1 || !OperatorNew ||
+        !OperatorNew->isReservedGlobalPlacementOperator())
       return true;
     const Expr *Source = stripToStorageSource(NE->getPlacementArg(0));
     QualType T = NE->getAllocatedType();
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 0f2310bb9331c2..39d19833c89ced 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -235,6 +235,49 @@ void test_placement_new_arena(Arena &arena) {
   sink = new (arena) PlacedNoPtr();
 }
 
+// A class-specific operator new(size_t, void *) may use its argument as
+// allocator state rather than as the storage, so the allocation feeding it
+// stays untyped.
+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 access and an unmatched address-of name storage other than
+// the allocation itself.
+struct Holder {
+  void *p;
+};
+Holder *alloc_holder(size_t) __attribute__((malloc));
+// 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: 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);
+}
+
+// Cancelling address-of/dereference pairs are still looked through.
+// CHECK-LABEL: define dso_local noundef ptr @_Z29test_placement_new_deref_addrv(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+PlacedNoPtr *test_placement_new_deref_addr() {
+  void *mem = malloc(64);
+  return new (*&mem) PlacedNoPtr();
+}
+
 template <typename T>
 T *placement_construct(size_t size) {
   __sized_ptr_t res = __size_returning_new(size);
@@ -259,3 +302,4 @@ void test_placement_new_template() {
 // CHECK: [[META_TESTCLASS]] = !{!"TestClass", i1 true}
 // CHECK: [[META_PLACEDNOPTR]] = !{!"PlacedNoPtr", i1 false}
 // CHECK: [[META_PLACEDWITHPTR]] = !{!"PlacedWithPtr", i1 true}
+// CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}

>From cfdb918a39a1af17f020f6d784842265481634dd Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 15:41:24 -0800
Subject: [PATCH 3/9] Address review: simplify collector, placement new
 prevails over raw-storage casts

- Replace PlacementNewTypes with collectPlacementNewTypes() returning one
  map; CodeGenFunction holds it in a std::optional, no new include.
- Use ConstDynamicRecursiveASTVisitor; drop the shouldVisit* overrides.
- __builtin_infer_alloc_token calls inferPossibleType directly.
- A placement new prevails over an inferred void/char/std::byte type
  (cast to a raw storage pointer or sizeof(char) size).
- Drop the &*/*& pair handling; only peel non-static fields of a
  by-value result; only look through trivial copy/move constructors.
- Tests: &h->p, static member, raw-storage casts, direct .p of a
  size-returning call, lambdas (non-generic and generic), arena operator
  whose argument comes from an allocation.
- Trim docs and release note.
---
 clang/docs/AllocToken.md              |  35 ++-----
 clang/docs/ReleaseNotes.md            |  10 +-
 clang/include/clang/AST/InferAlloc.h  |  59 ++++--------
 clang/lib/AST/InferAlloc.cpp          | 127 ++++++++++----------------
 clang/lib/CodeGen/CGBuiltin.cpp       |   6 +-
 clang/lib/CodeGen/CGExpr.cpp          |  16 +++-
 clang/lib/CodeGen/CodeGenFunction.h   |  10 +-
 clang/test/CodeGenCXX/alloc-token.cpp |  78 ++++++++++++----
 8 files changed, 159 insertions(+), 182 deletions(-)

diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index 1641f026e24d6c..c9bbe2e6c06ad4 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -58,35 +58,12 @@ The following command-line options affect generated token IDs:
 
 ## Allocated Type Inference
 
-For `new` expressions the allocated type is known. For allocation functions
-such as `malloc` that return untyped memory, the type is inferred from the
-allocation call and its surroundings, in this order:
-
-- A `sizeof` in a size argument, possibly in arithmetic:
-  `malloc(sizeof(T))`, `malloc(n * sizeof(T))`, `malloc(sizeof(T) + extra)`,
-  or a variable initialized from such an expression.
-- A cast of the result: `(T *)malloc(n)`.
-- Placement new into the result: `new (malloc(n)) T`, or, through a local
-  variable and optionally a cast or member access of the result,
-
-  ```c++
-  void *mem = alloc(n);
-  T *obj = new (mem) T;              // infers 'T' for alloc(n)
-
-  sized_ptr res = size_returning_alloc(n);
-  T *obj = new (res.p) T;            // infers 'T' for size_returning_alloc(n)
-  ```
-
-  If different types are constructed into the same storage, no type is
-  inferred. Only the reserved non-allocating placement form
-  `::operator new(size_t, void *)` is considered; user-provided placement
-  operators may construct elsewhere. Likewise, indirect member accesses
-  (`h->p`) and unmatched `&`/`*` name storage other than the allocation and
-  are not looked through.
-
-These are heuristics: they ignore control flow and reassignments of the
-variables involved. If no type can be inferred, the allocation receives the
-fallback token.
+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, for example from a `sizeof` in the size
+argument, a cast of the result, or a placement `new` into the result. The
+heuristics are syntactic and ignore control flow and reassignments. If no type
+can be inferred, the allocation receives the fallback token.
 
 ## Querying Token IDs with `__builtin_infer_alloc_token`
 
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index a945546b46610e..d5c10a1eb569ed 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1554,13 +1554,9 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
   modes for `-fsanitize=alloc-token`, selected with
   `-Xclang -falloc-token-mode=<mode>`. These modes derive token IDs from both
   the allocated type and the name of the function containing the allocation.
-- `-fsanitize=alloc-token` type inference now also recognizes memory that is
-  used as placement-new storage: for `new (p) T`, where `p` is the result of an
-  allocation call (directly, through a cast or member access such as the
-  pointer of a size-returning allocation, or via a local variable initialized
-  with it), the allocation is attributed to `T`. This covers the common
-  "allocate raw storage, then construct in place" idiom, which previously
-  received no type and therefore the fallback token.
+- `-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 b6a6b28e1ba419..fe27e007af3ecd 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -22,14 +22,24 @@
 namespace clang {
 
 class Stmt;
-class VarDecl;
 
 namespace infer_alloc {
 
-/// Lazily collects, for one function body, the types constructed by placement
-/// new into memory returned by allocation calls. This lets the allocated type
-/// be inferred for the common "allocate raw storage, then placement-new the
-/// object into it" idiom, where neither a sizeof nor a cast names the type:
+/// Infer the possible allocated type from an allocation call expression.
+/// \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);
+
+/// Returns true if \p T only names raw storage rather than an object type:
+/// void, the character types, and std::byte. For such a result, a placement
+/// new into the allocation is stronger evidence of the allocated type.
+bool isRawStorageType(QualType T);
+
+/// Maps the allocation calls in \p Body whose result is used as placement-new
+/// storage, directly or via a local variable initialized with it, to the type
+/// constructed (null if different types are constructed into the same
+/// storage). This covers the "allocate raw storage, then construct in place"
+/// idiom, where neither a sizeof nor a cast names the type:
 ///
 ///   void *mem = alloc(size);
 ///   MyType *obj = new (mem) MyType();  // infers 'MyType' for alloc(size)
@@ -37,41 +47,10 @@ namespace infer_alloc {
 ///   auto res = size_returning_alloc(size);
 ///   new (res.p) MyType();              // infers 'MyType' (via member .p)
 ///
-///   new (alloc(size)) MyType();        // infers 'MyType'
-///
-/// The placement argument may be wrapped in parentheses, casts, or member
-/// accesses of the call result (or of a local variable initialized with it).
-/// If placement news of different types use the same allocation, no type is
-/// inferred. Like the other inference heuristics, this ignores control flow
-/// and reassignments of the variable.
-class PlacementNewTypes {
-public:
-  explicit PlacementNewTypes(const Stmt *Body) : Body(Body) {}
-
-  /// Returns the type placement-constructed into the result of allocation call
-  /// \p E, or a null type if there is none or it is ambiguous.
-  QualType lookup(const CallExpr *E);
-
-private:
-  void collect();
-
-  const Stmt *Body;
-  bool Collected = false;
-  // Allocation call -> placement-new type (null if ambiguous).
-  llvm::DenseMap<const CallExpr *, QualType> CallTypes;
-  // Variable -> placement-new type of its contents (null if ambiguous).
-  llvm::DenseMap<const VarDecl *, QualType> VarTypes;
-  // Allocation call -> variable it initializes.
-  llvm::DenseMap<const CallExpr *, const VarDecl *> CallVars;
-};
-
-/// Infer the possible allocated type from an allocation call expression.
-/// \p CastE is the cast the call result is immediately used in, if any, and
-/// \p PlacementTypes the placement-new types of the enclosing function, if
-/// available.
-QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
-                           const CastExpr *CastE,
-                           PlacementNewTypes *PlacementTypes = nullptr);
+/// Like the other inference heuristics, this ignores control flow and
+/// reassignments of the variable.
+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 36425c4062ee1a..ae74908f91abd4 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -14,9 +14,9 @@
 #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/RecursiveASTVisitor.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "llvm/ADT/SmallPtrSet.h"
@@ -171,8 +171,7 @@ static QualType inferPossibleTypeFromCastExpr(const CallExpr *CallE,
 
 QualType infer_alloc::inferPossibleType(const CallExpr *E,
                                         const ASTContext &Ctx,
-                                        const CastExpr *CastE,
-                                        PlacementNewTypes *PlacementTypes) {
+                                        const CastExpr *CastE) {
   QualType AllocType;
   // First check arguments.
   for (const Expr *Arg : E->arguments()) {
@@ -185,47 +184,35 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
   // Then check later casts.
   if (AllocType.isNull())
     AllocType = inferPossibleTypeFromCastExpr(E, CastE);
-  // Finally check if the result is used as placement-new storage.
-  if (AllocType.isNull() && PlacementTypes)
-    AllocType = PlacementTypes->lookup(E);
   return AllocType;
 }
 
+bool infer_alloc::isRawStorageType(QualType T) {
+  return T->isVoidType() || T->isCharType() || T->isStdByteType();
+}
+
 namespace {
 /// Strips the wrappers a placement argument may have around the expression
-/// that produced the storage: parentheses, casts, direct (non-arrow) member
+/// that produced the storage: parentheses, casts, and non-static member
 /// accesses of a by-value result (e.g. the pointer member of a size-returning
-/// allocation result), and cancelling `&*` / `*&` pairs. Anything that follows
-/// a pointer into different storage (`->`, an unmatched dereference) or takes
-/// the address of a different object (an unmatched address-of) stops the walk.
+/// allocation result). Anything that follows a pointer into different storage
+/// (`->`, `*`) or names a different object (`&`) stops the walk.
 const Expr *stripToStorageSource(const Expr *E) {
   while (true) {
     E = E->IgnoreParenCasts();
-    if (const auto *ME = dyn_cast<MemberExpr>(E)) {
-      if (ME->isArrow())
-        return E;
-      E = ME->getBase();
-      continue;
-    }
-    if (const auto *UO = dyn_cast<UnaryOperator>(E);
-        UO && (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref)) {
-      const auto *Inner =
-          dyn_cast<UnaryOperator>(UO->getSubExpr()->IgnoreParens());
-      if (!Inner || Inner->getOpcode() == UO->getOpcode() ||
-          (Inner->getOpcode() != UO_AddrOf && Inner->getOpcode() != UO_Deref))
-        return E;
-      E = Inner->getSubExpr();
-      continue;
-    }
-    return E;
+    const auto *ME = dyn_cast<MemberExpr>(E);
+    if (!ME || ME->isArrow() || !isa<FieldDecl>(ME->getMemberDecl()))
+      return E;
+    E = ME->getBase();
   }
 }
 
-/// Finds the allocation call that initializes a variable, looking through the
-/// temporaries and elidable copies a class-typed initializer may carry.
+/// Finds the allocation call that initializes a variable, looking through
+/// casts and the temporaries and trivial copies a class-typed initializer may
+/// carry.
 const CallExpr *initializingCall(const Expr *Init) {
   while (Init) {
-    Init = Init->IgnoreParenImpCasts();
+    Init = Init->IgnoreParenCasts();
     if (const auto *EWC = dyn_cast<ExprWithCleanups>(Init)) {
       Init = EWC->getSubExpr();
     } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
@@ -234,8 +221,10 @@ const CallExpr *initializingCall(const Expr *Init) {
       Init = BTE->getSubExpr();
     } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Init);
                CE && CE->getNumArgs() == 1 &&
-               (CE->isElidable() ||
-                CE->getConstructor()->isCopyOrMoveConstructor())) {
+               CE->getConstructor()->isCopyOrMoveConstructor() &&
+               CE->getConstructor()->isTrivial()) {
+      // A non-trivial copy or move may not be elided (-fno-elide-constructors)
+      // and could replace the pointer.
       Init = CE->getArg(0);
     } else if (const auto *FCE = dyn_cast<CXXFunctionalCastExpr>(Init)) {
       Init = FCE->getSubExpr();
@@ -246,77 +235,61 @@ const CallExpr *initializingCall(const Expr *Init) {
   return dyn_cast_or_null<CallExpr>(Init);
 }
 
-/// Records placement-new types per allocation call and per variable.
-class PlacementNewCollector
-    : public RecursiveASTVisitor<PlacementNewCollector> {
+/// Records, per allocation call, the type placement-constructed into its
+/// result. A variable's declaration precedes its uses in traversal order, so
+/// uses through a variable are resolved to the initializing call on the fly.
+class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
 public:
-  PlacementNewCollector(
-      llvm::DenseMap<const CallExpr *, QualType> &CallTypes,
-      llvm::DenseMap<const VarDecl *, QualType> &VarTypes,
-      llvm::DenseMap<const CallExpr *, const VarDecl *> &CallVars)
-      : CallTypes(CallTypes), VarTypes(VarTypes), CallVars(CallVars) {}
-
-  bool shouldVisitTemplateInstantiations() const { return true; }
-  bool shouldVisitImplicitCode() const { return true; }
+  explicit PlacementNewCollector(
+      llvm::DenseMap<const CallExpr *, QualType> &CallTypes)
+      : CallTypes(CallTypes) {}
 
-  bool VisitVarDecl(const VarDecl *VD) {
+  bool VisitVarDecl(const VarDecl *VD) override {
     if (const CallExpr *CE = initializingCall(VD->getInit()))
-      CallVars.try_emplace(CE, VD);
+      VarCalls.try_emplace(VD, CE);
     return true;
   }
 
-  bool VisitCXXNewExpr(const CXXNewExpr *NE) {
+  bool VisitCXXNewExpr(const CXXNewExpr *NE) override {
     // Only the reserved non-allocating placement form, new (storage) T, is
     // guaranteed to construct into its single placement argument. A
     // class-specific or otherwise user-provided operator new(size_t, void *)
     // may treat the argument as allocator state and return other storage.
+    // Dependent new-expressions (e.g. in a generic lambda) have no resolved
+    // operator and are skipped.
     const FunctionDecl *OperatorNew = NE->getOperatorNew();
     if (NE->getNumPlacementArgs() != 1 || !OperatorNew ||
         !OperatorNew->isReservedGlobalPlacementOperator())
       return true;
     const Expr *Source = stripToStorageSource(NE->getPlacementArg(0));
-    QualType T = NE->getAllocatedType();
-    if (const auto *CE = dyn_cast<CallExpr>(Source))
-      record(CallTypes, CE, T);
-    else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
+    const CallExpr *CE = dyn_cast<CallExpr>(Source);
+    if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
       if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
-        record(VarTypes, VD, T);
-    return true;
-  }
-
-private:
-  template <typename Key>
-  static void record(llvm::DenseMap<Key, QualType> &Map, Key K, QualType T) {
-    auto [It, Inserted] = Map.try_emplace(K, T);
+        CE = VarCalls.lookup(VD);
+    if (!CE)
+      return true;
+    QualType T = NE->getAllocatedType();
+    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();
+    return true;
   }
 
+private:
   llvm::DenseMap<const CallExpr *, QualType> &CallTypes;
-  llvm::DenseMap<const VarDecl *, QualType> &VarTypes;
-  llvm::DenseMap<const CallExpr *, const VarDecl *> &CallVars;
+  // Variable -> allocation call initializing it.
+  llvm::DenseMap<const VarDecl *, const CallExpr *> VarCalls;
 };
 } // namespace
 
-void PlacementNewTypes::collect() {
-  Collected = true;
-  if (!Body)
-    return;
-  PlacementNewCollector Collector(CallTypes, VarTypes, CallVars);
-  Collector.TraverseStmt(const_cast<Stmt *>(Body));
-}
-
-QualType PlacementNewTypes::lookup(const CallExpr *E) {
-  if (!Collected)
-    collect();
-  if (auto It = CallTypes.find(E); It != CallTypes.end())
-    return It->second;
-  if (auto VarIt = CallVars.find(E); VarIt != CallVars.end())
-    if (auto It = VarTypes.find(VarIt->second); It != VarTypes.end())
-      return It->second;
-  return QualType();
+llvm::DenseMap<const CallExpr *, QualType>
+infer_alloc::collectPlacementNewTypes(const Stmt *Body) {
+  llvm::DenseMap<const CallExpr *, QualType> CallTypes;
+  if (Body)
+    PlacementNewCollector(CallTypes).TraverseStmt(Body);
+  return CallTypes;
 }
 
 std::optional<llvm::AllocTokenMetadata>
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index c520016ab1a513..80d826170e9e6d 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"
@@ -4891,7 +4892,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 33d6d1e4d45a4e..09c4d9846eb58a 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,11 +1407,17 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
 }
 
 llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
-  if (!AllocTokenPlacementTypes)
-    AllocTokenPlacementTypes = std::make_unique<infer_alloc::PlacementNewTypes>(
-        CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
-  return buildAllocToken(infer_alloc::inferPossibleType(
-      E, getContext(), CurCast, AllocTokenPlacementTypes.get()));
+  QualType T = infer_alloc::inferPossibleType(E, getContext(), CurCast);
+  // A placement new into the result is stronger evidence than a cast to a raw
+  // storage pointer (void *, char *, ...) or a sizeof(char)-based size.
+  if (T.isNull() || infer_alloc::isRawStorageType(T)) {
+    if (!AllocTokenPlacementTypes)
+      AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
+          CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
+    if (QualType PT = AllocTokenPlacementTypes->lookup(E); !PT.isNull())
+      T = PT;
+  }
+  return buildAllocToken(T);
 }
 
 void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, const CallExpr *E) {
diff --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index d8545b86aae928..83cf4b474d3b0a 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -26,7 +26,6 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/ExprObjC.h"
 #include "clang/AST/ExprOpenMP.h"
-#include "clang/AST/InferAlloc.h"
 #include "clang/AST/StmtOpenACC.h"
 #include "clang/AST/StmtOpenMP.h"
 #include "clang/AST/StmtSYCL.h"
@@ -376,10 +375,11 @@ class CodeGenFunction : public CodeGenTypeCache {
   /// expression.
   const CastExpr *CurCast = nullptr;
 
-  /// Placement-new types of the current function body, collected lazily for
-  /// -fsanitize=alloc-token type inference (see
-  /// infer_alloc::PlacementNewTypes).
-  std::unique_ptr<infer_alloc::PlacementNewTypes> AllocTokenPlacementTypes;
+  /// 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 39d19833c89ced..f634bd0a1a0601 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -222,22 +222,22 @@ void test_placement_new_ambiguous(int which) {
     sink = new (mem) PlacedWithPtr();
 }
 
-// Custom placement operators do not take the storage as placement argument, so
-// the malloc stays untyped (the custom operator new call itself is typed).
+// 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 &);
-// CHECK-LABEL: define dso_local void @_Z24test_placement_new_arenaR5Arena(
-// CHECK: call noalias ptr @malloc(i64 noundef 64)
-// CHECK-NOT: @malloc{{.*}}!alloc_token
-// CHECK: call noundef ptr @_ZnwmR5Arena(i64 noundef 16, {{.*}} !alloc_token [[META_PLACEDNOPTR]]
-void test_placement_new_arena(Arena &arena) {
-  sink = malloc(64);
+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();
 }
 
-// A class-specific operator new(size_t, void *) may use its argument as
-// allocator state rather than as the storage, so the allocation feeding it
-// stays untyped.
+// Same for a class-specific operator new(size_t, void *).
 struct ClassPlacement {
   void *next;
   static void *operator new(size_t, void *ctx);
@@ -251,31 +251,73 @@ void test_placement_new_class_specific() {
   sink = new (ctx) ClassPlacement;
 }
 
-// Indirect member access and an unmatched address-of name storage other than
-// the allocation itself.
+// 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 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();
+  Holder *h2 = alloc_holder(64);
+  sink = new (&h2->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 cast to a raw storage pointer (void *, char *, ...) is weaker evidence
+// than the placement new, which prevails; a cast to an object type does not.
+// CHECK-LABEL: define dso_local void @_Z30test_placement_new_raw_storagev(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// 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 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+void test_placement_new_raw_storage() {
+  char *p1 = static_cast<char *>(malloc(64));
+  sink = new (p1) PlacedWithPtr();
+  auto *p2 = (unsigned char *)malloc(64);
+  sink = new (p2) PlacedWithPtr();
+  // The member access is an implicit lvalue-to-rvalue cast to void *.
+  sink = new (__size_returning_new(64).p) PlacedWithPtr();
+  void *p3 = malloc(sizeof(char) * 64);
+  sink = new (p3) PlacedWithPtr();
+  auto *p4 = (PlacedWithPtr *)malloc(16);
+  sink = new (p4) PlacedNoPtr();
 }
 
-// Cancelling address-of/dereference pairs are still looked through.
-// CHECK-LABEL: define dso_local noundef ptr @_Z29test_placement_new_deref_addrv(
+// 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]]
-PlacedNoPtr *test_placement_new_deref_addr() {
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+void test_placement_new_lambda() {
   void *mem = malloc(64);
-  return new (*&mem) PlacedNoPtr();
+  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>

>From d6fff822286c1d299a8d8348a6a9f15f50243f4d Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 16:13:20 -0800
Subject: [PATCH 4/9] Placement new takes precedence over sizeof and cast
 inference

The constructed type is the most precise evidence; a sizeof or cast may
only describe the storage (a char buffer or a base class). Drop the
raw-storage special case and test the base-class cast case.
---
 clang/include/clang/AST/InferAlloc.h  |  8 ++------
 clang/lib/AST/InferAlloc.cpp          |  4 ----
 clang/lib/CodeGen/CGExpr.cpp          | 19 +++++++++----------
 clang/test/CodeGenCXX/alloc-token.cpp | 19 ++++++++++++-------
 4 files changed, 23 insertions(+), 27 deletions(-)

diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index fe27e007af3ecd..7faf8329d01d08 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -30,16 +30,12 @@ namespace infer_alloc {
 QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
                            const CastExpr *CastE);
 
-/// Returns true if \p T only names raw storage rather than an object type:
-/// void, the character types, and std::byte. For such a result, a placement
-/// new into the allocation is stronger evidence of the allocated type.
-bool isRawStorageType(QualType T);
-
 /// Maps the allocation calls in \p Body whose result is used as placement-new
 /// storage, directly or via a local variable initialized with it, to the type
 /// constructed (null if different types are constructed into the same
 /// storage). This covers the "allocate raw storage, then construct in place"
-/// idiom, where neither a sizeof nor a cast names the type:
+/// idiom; the constructed type is more precise than a sizeof or a cast, which
+/// may only describe the storage (a char buffer, a base class):
 ///
 ///   void *mem = alloc(size);
 ///   MyType *obj = new (mem) MyType();  // infers 'MyType' for alloc(size)
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index ae74908f91abd4..5e6923bfd41bed 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -187,10 +187,6 @@ QualType infer_alloc::inferPossibleType(const CallExpr *E,
   return AllocType;
 }
 
-bool infer_alloc::isRawStorageType(QualType T) {
-  return T->isVoidType() || T->isCharType() || T->isStdByteType();
-}
-
 namespace {
 /// Strips the wrappers a placement argument may have around the expression
 /// that produced the storage: parentheses, casts, and non-static member
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 09c4d9846eb58a..110432d25cabdd 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,16 +1407,15 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
 }
 
 llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
-  QualType T = infer_alloc::inferPossibleType(E, getContext(), CurCast);
-  // A placement new into the result is stronger evidence than a cast to a raw
-  // storage pointer (void *, char *, ...) or a sizeof(char)-based size.
-  if (T.isNull() || infer_alloc::isRawStorageType(T)) {
-    if (!AllocTokenPlacementTypes)
-      AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
-          CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
-    if (QualType PT = AllocTokenPlacementTypes->lookup(E); !PT.isNull())
-      T = PT;
-  }
+  // A placement new into the result is the strongest evidence of the allocated
+  // type: it names the object actually constructed, whereas a sizeof or a cast
+  // may only describe the raw storage (e.g. a char buffer or a base class).
+  if (!AllocTokenPlacementTypes)
+    AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
+        CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
+  QualType T = AllocTokenPlacementTypes->lookup(E);
+  if (T.isNull())
+    T = infer_alloc::inferPossibleType(E, getContext(), CurCast);
   return buildAllocToken(T);
 }
 
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index f634bd0a1a0601..4ff69b6817170f 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -201,9 +201,10 @@ PlacedNoPtr *test_placement_new_array() {
   return new (mem) PlacedNoPtr[10];
 }
 
-// A sizeof in the size argument or a cast of the result still takes precedence.
+// The placement new names the constructed object and takes precedence over a
+// sizeof in the size argument, which may only describe the storage.
 // CHECK-LABEL: define dso_local noundef ptr @_Z34test_placement_new_sizeof_prevailsv(
-// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDNOPTR]]
 PlacedNoPtr *test_placement_new_sizeof_prevails() {
   void *mem = malloc(sizeof(PlacedWithPtr));
   return new (mem) PlacedNoPtr();
@@ -284,14 +285,17 @@ void test_placement_new_indirect() {
   sink = new (span.storage) PlacedNoPtr();
 }
 
-// A cast to a raw storage pointer (void *, char *, ...) is weaker evidence
-// than the placement new, which prevails; a cast to an object type does not.
+// Likewise over a cast of the result, whether to a raw storage pointer
+// (void *, char *, ...) or to a base class of the constructed type.
+struct DerivedWithPtr : PlacedNoPtr {
+  void *next;
+};
 // CHECK-LABEL: define dso_local void @_Z30test_placement_new_raw_storagev(
 // CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
 // 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 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
-// CHECK: call noalias ptr @malloc(i64 noundef 16){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 32){{.*}} !alloc_token [[META_DERIVEDWITHPTR:![0-9]+]]
 void test_placement_new_raw_storage() {
   char *p1 = static_cast<char *>(malloc(64));
   sink = new (p1) PlacedWithPtr();
@@ -301,8 +305,8 @@ void test_placement_new_raw_storage() {
   sink = new (__size_returning_new(64).p) PlacedWithPtr();
   void *p3 = malloc(sizeof(char) * 64);
   sink = new (p3) PlacedWithPtr();
-  auto *p4 = (PlacedWithPtr *)malloc(16);
-  sink = new (p4) PlacedNoPtr();
+  auto *base = static_cast<PlacedNoPtr *>(malloc(32));
+  sink = new (base) DerivedWithPtr();
 }
 
 // Non-generic lambdas use the captured variable; a generic lambda's dependent
@@ -345,3 +349,4 @@ void test_placement_new_template() {
 // CHECK: [[META_PLACEDNOPTR]] = !{!"PlacedNoPtr", i1 false}
 // CHECK: [[META_PLACEDWITHPTR]] = !{!"PlacedWithPtr", i1 true}
 // CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}
+// CHECK: [[META_DERIVEDWITHPTR]] = !{!"DerivedWithPtr", i1 true}

>From 6af1d9c045964e8f3a5986260b6f59a9364d7c61 Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Wed, 11 Nov 2026 17:53:21 -0800
Subject: [PATCH 5/9] Resolve placement-new variables with a lexical def-use
 chain

A use new (p) T is matched to the nearest preceding definition of p
(initializer or p = <call>) that lexically dominates it: same control-flow
context or an enclosing one, and no later definition inside a loop that
contains the use. Other writes (compound assignment, ++/--, &p) and
definitions in non-dominating branches make the use ambiguous. This
attributes the type to the allocation that actually flows into the
placement new rather than to the variable's initializer.
---
 clang/include/clang/AST/InferAlloc.h  |   7 +-
 clang/lib/AST/InferAlloc.cpp          | 180 +++++++++++++++++++++++---
 clang/test/CodeGenCXX/alloc-token.cpp |  74 +++++++++++
 3 files changed, 238 insertions(+), 23 deletions(-)

diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index 7faf8329d01d08..5a32cd04644b4f 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -31,7 +31,7 @@ QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
                            const CastExpr *CastE);
 
 /// Maps the allocation calls in \p Body whose result is used as placement-new
-/// storage, directly or via a local variable initialized with it, to the type
+/// storage, directly or via a local variable holding it, to the type
 /// constructed (null if different types are constructed into the same
 /// storage). This covers the "allocate raw storage, then construct in place"
 /// idiom; the constructed type is more precise than a sizeof or a cast, which
@@ -43,8 +43,9 @@ QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
 ///   auto res = size_returning_alloc(size);
 ///   new (res.p) MyType();              // infers 'MyType' (via member .p)
 ///
-/// Like the other inference heuristics, this ignores control flow and
-/// reassignments of the variable.
+/// Variables are resolved with a lexical def-use chain: the nearest preceding
+/// definition that dominates the use, with no conflicting later definition in
+/// an enclosing loop; otherwise nothing is inferred.
 llvm::DenseMap<const CallExpr *, QualType>
 collectPlacementNewTypes(const Stmt *Body);
 
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 5e6923bfd41bed..20cdb0f402a439 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -19,7 +19,10 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/IdentifierTable.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include <vector>
 
 using namespace clang;
 using namespace infer_alloc;
@@ -203,9 +206,9 @@ const Expr *stripToStorageSource(const Expr *E) {
   }
 }
 
-/// Finds the allocation call that initializes a variable, looking through
-/// casts and the temporaries and trivial copies a class-typed initializer may
-/// carry.
+/// Finds the allocation call an initializer or assigned value consists of,
+/// looking through casts and the temporaries and trivial copies a class-typed
+/// value may carry.
 const CallExpr *initializingCall(const Expr *Init) {
   while (Init) {
     Init = Init->IgnoreParenCasts();
@@ -232,17 +235,55 @@ const CallExpr *initializingCall(const Expr *Init) {
 }
 
 /// Records, per allocation call, the type placement-constructed into its
-/// result. A variable's declaration precedes its uses in traversal order, so
-/// uses through a variable are resolved to the initializing call on the fly.
+/// result.
+///
+/// Placement arguments that name a variable are resolved with a lexical
+/// def-use chain: a use `new (p) T` is matched to the nearest preceding
+/// definition of `p` (its initializer or an assignment `p = <call>`) in
+/// traversal order, provided that definition lexically dominates the use,
+/// i.e. it is in the same control-flow context as the use or an enclosing
+/// one. A definition in a branch that does not enclose the use, a later
+/// definition that can reach the use around a loop, or any other write to
+/// the variable (compound assignment, increment, address-of) makes the use
+/// ambiguous and nothing is inferred for it.
 class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
 public:
   explicit PlacementNewCollector(
       llvm::DenseMap<const CallExpr *, QualType> &CallTypes)
-      : CallTypes(CallTypes) {}
+      : CallTypes(CallTypes) {
+    // Context 0 is the function body itself.
+    Contexts.push_back({/*Parent=*/-1, /*IsLoop=*/false});
+  }
+
+  void finish() {
+    for (const Use &U : Uses) {
+      const CallExpr *CE = resolve(U);
+      if (CE)
+        record(CE, U.Type);
+    }
+  }
 
   bool VisitVarDecl(const VarDecl *VD) override {
-    if (const CallExpr *CE = initializingCall(VD->getInit()))
-      VarCalls.try_emplace(VD, CE);
+    if (VD->isLocalVarDecl())
+      addDef(VD, initializingCall(VD->getInit()));
+    return true;
+  }
+
+  bool VisitBinaryOperator(const BinaryOperator *BO) override {
+    if (!BO->isAssignmentOp())
+      return true;
+    if (const VarDecl *VD = referencedVar(BO->getLHS()))
+      addDef(VD, BO->getOpcode() == BO_Assign ? initializingCall(BO->getRHS())
+                                              : nullptr);
+    return true;
+  }
+
+  bool VisitUnaryOperator(const UnaryOperator *UO) override {
+    if (UO->getOpcode() != UO_AddrOf && !UO->isIncrementDecrementOp())
+      return true;
+    // The variable may be written through the pointer or reference.
+    if (const VarDecl *VD = referencedVar(UO->getSubExpr()))
+      addDef(VD, nullptr);
     return true;
   }
 
@@ -258,33 +299,132 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
         !OperatorNew->isReservedGlobalPlacementOperator())
       return true;
     const Expr *Source = stripToStorageSource(NE->getPlacementArg(0));
-    const CallExpr *CE = dyn_cast<CallExpr>(Source);
-    if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
-      if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
-        CE = VarCalls.lookup(VD);
-    if (!CE)
-      return true;
     QualType T = NE->getAllocatedType();
+    if (const auto *CE = dyn_cast<CallExpr>(Source))
+      record(CE, T);
+    else if (const VarDecl *VD = referencedVar(Source))
+      Uses.push_back({VD, Seq++, CurContext, T});
+    return true;
+  }
+
+  // Control-flow constructs open a new context for the statements they
+  // contain; a definition inside one does not dominate uses outside it.
+#define PLACEMENT_CONTEXT(CLASS, IS_LOOP)                                      \
+  bool Traverse##CLASS(const CLASS *S) override {                              \
+    return inContext(IS_LOOP, [&] {                                            \
+      return ConstDynamicRecursiveASTVisitor::Traverse##CLASS(S);              \
+    });                                                                        \
+  }
+  PLACEMENT_CONTEXT(IfStmt, false)
+  PLACEMENT_CONTEXT(SwitchStmt, false)
+  PLACEMENT_CONTEXT(ConditionalOperator, false)
+  PLACEMENT_CONTEXT(BinaryConditionalOperator, false)
+  PLACEMENT_CONTEXT(LambdaExpr, false)
+  PLACEMENT_CONTEXT(StmtExpr, false)
+  PLACEMENT_CONTEXT(ForStmt, true)
+  PLACEMENT_CONTEXT(WhileStmt, true)
+  PLACEMENT_CONTEXT(DoStmt, true)
+  PLACEMENT_CONTEXT(CXXForRangeStmt, true)
+#undef PLACEMENT_CONTEXT
+
+private:
+  struct Context {
+    int Parent;
+    bool IsLoop;
+  };
+  struct Def {
+    unsigned Seq;
+    int Context;
+    const CallExpr *Call; // null: a write that is not an allocation call
+  };
+  struct Use {
+    const VarDecl *Var;
+    unsigned Seq;
+    int Context;
+    QualType Type;
+  };
+
+  bool inContext(bool IsLoop, llvm::function_ref<bool()> Traverse) {
+    int Saved = CurContext;
+    Contexts.push_back({Saved, IsLoop});
+    CurContext = Contexts.size() - 1;
+    bool Result = Traverse();
+    CurContext = Saved;
+    return Result;
+  }
+
+  static const VarDecl *referencedVar(const Expr *E) {
+    if (const auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
+      return dyn_cast<VarDecl>(DRE->getDecl());
+    return nullptr;
+  }
+
+  void addDef(const VarDecl *VD, const CallExpr *CE) {
+    Defs[VD].push_back({Seq++, CurContext, CE});
+  }
+
+  bool isAncestorOrSelf(int Ancestor, int Ctx) const {
+    for (; Ctx >= 0; Ctx = Contexts[Ctx].Parent)
+      if (Ctx == Ancestor)
+        return true;
+    return false;
+  }
+
+  bool isInLoop(int Ctx) const {
+    for (; Ctx >= 0; Ctx = Contexts[Ctx].Parent)
+      if (Contexts[Ctx].IsLoop)
+        return true;
+    return false;
+  }
+
+  /// Returns the allocation call that defines the variable of \p U at the
+  /// use, or null if there is none or it cannot be determined.
+  const CallExpr *resolve(const Use &U) const {
+    auto It = Defs.find(U.Var);
+    if (It == Defs.end())
+      return nullptr;
+    const Def *Reaching = nullptr;
+    bool LaterDef = false;
+    for (const Def &D : It->second) {
+      if (D.Seq < U.Seq)
+        Reaching = &D; // defs are in traversal order; keep the last one
+      else
+        LaterDef = true;
+    }
+    if (!Reaching || !Reaching->Call ||
+        !isAncestorOrSelf(Reaching->Context, U.Context))
+      return nullptr;
+    // A later definition can reach the use around a loop back edge.
+    if (LaterDef && isInLoop(U.Context))
+      return nullptr;
+    return Reaching->Call;
+  }
+
+  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();
-    return true;
   }
 
-private:
   llvm::DenseMap<const CallExpr *, QualType> &CallTypes;
-  // Variable -> allocation call initializing it.
-  llvm::DenseMap<const VarDecl *, const CallExpr *> VarCalls;
+  std::vector<Context> Contexts;
+  int CurContext = 0;
+  unsigned Seq = 0;
+  llvm::DenseMap<const VarDecl *, llvm::SmallVector<Def, 2>> Defs;
+  std::vector<Use> Uses;
 };
 } // namespace
 
 llvm::DenseMap<const CallExpr *, QualType>
 infer_alloc::collectPlacementNewTypes(const Stmt *Body) {
   llvm::DenseMap<const CallExpr *, QualType> CallTypes;
-  if (Body)
-    PlacementNewCollector(CallTypes).TraverseStmt(Body);
+  if (Body) {
+    PlacementNewCollector Collector(CallTypes);
+    Collector.TraverseStmt(Body);
+    Collector.finish();
+  }
   return CallTypes;
 }
 
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 4ff69b6817170f..db07ae2cec7ac0 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));
@@ -324,6 +325,79 @@ void test_placement_new_lambda() {
   construct2(PlacedNoPtr{});
 }
 
+// Variables are resolved with a lexical def-use chain: the nearest preceding
+// definition that dominates the use.
+// CHECK-LABEL: define dso_local void @_Z27test_placement_new_reassignv(
+// CHECK: call noalias ptr @malloc(i64 noundef 8)
+// CHECK-NOT: @malloc{{.*}}!alloc_token
+// CHECK: call noalias ptr @malloc(i64 noundef 8){{.*}} !alloc_token [[META_LONG]]
+// 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 noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+void test_placement_new_reassign() {
+  // The first allocation is freed and the variable reassigned before the
+  // placement new: only the second allocation is typed.
+  void *p = malloc(8);
+  free(p);
+  p = malloc(8);
+  sink = new (p) long(10);
+  // Declared without initializer, assigned later.
+  void *q;
+  q = malloc(64);
+  sink = new (q) PlacedNoPtr();
+  // Each definition is matched to the uses that follow it.
+  void *r = malloc(64);
+  sink = new (r) PlacedWithPtr();
+  r = malloc(64);
+  sink = new (r) PlacedNoPtr();
+}
+
+// Definitions that do not dominate the use, later definitions in a loop, and
+// other writes to the variable make the use ambiguous: nothing is inferred.
+// CHECK-LABEL: define dso_local void @_Z29test_placement_new_ambiguous2b(
+// 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: ret void
+void test_placement_new_ambiguous2(bool c) {
+  // A definition in a branch does not dominate the use after it.
+  void *p = malloc(64);
+  if (c)
+    p = malloc(32);
+  sink = new (p) PlacedNoPtr();
+  // A definition after the use inside the loop reaches it around the back
+  // edge.
+  void *q = malloc(64);
+  for (int i = 0; i < 2; ++i) {
+    sink = new (q) PlacedNoPtr();
+    q = malloc(32);
+  }
+  // Address taken: the variable may be written through the pointer.
+  void *r = malloc(64);
+  sink = &r;
+  sink = new (r) PlacedNoPtr();
+}
+
+// Uses inside a branch or loop are dominated by a definition before it.
+// CHECK-LABEL: define dso_local void @_Z29test_placement_new_dominatingb(
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+void test_placement_new_dominating(bool c) {
+  void *p = malloc(64);
+  if (c)
+    sink = new (p) PlacedNoPtr();
+  void *q = malloc(64);
+  for (int i = 0; i < 2; ++i)
+    sink = new (q) PlacedWithPtr();
+}
+
 template <typename T>
 T *placement_construct(size_t size) {
   __sized_ptr_t res = __size_returning_new(size);

>From 6be79d63e40b73cdba4c44574449b27feccfa767 Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Fri, 13 Nov 2026 09:05:15 -0800
Subject: [PATCH 6/9] Use a single-definition rule for placement-new variables;
 sizeof prevails

- A variable is used only if the function defines it exactly once (its
  initializer, excluding null pointer initializers, or one assignment)
  and never writes to it otherwise (compound assignment, increment,
  address-of, field write, non-const member call, binding to a non-const
  reference). Parameters are not used. This replaces the lexical def-use
  chain, which was unsound for if/else arms and by-reference lambdas.
- Inference order is sizeof, then placement new, then cast: a sizeof
  states what the allocation was sized for and may describe a header
  plus elements, so the placement new no longer overrides it. The
  placement-new lookup is a callback into inferPossibleType, so the body
  is traversed only when no sizeof is found.
- initializingCall uses IgnoreImplicit()->IgnoreParenCasts(); drop the
  dead CXXFunctionalCastExpr branch, the Stmt forward declaration, and
  std::vector.
- Tests renamed and regrouped to match: sizeof_prevails, over_cast,
  single_definition, reassigned, parameter, other_writes.
- Docs updated accordingly.
---
 clang/docs/AllocToken.md              |  11 +-
 clang/include/clang/AST/InferAlloc.h  |  26 +--
 clang/lib/AST/InferAlloc.cpp          | 269 ++++++++++++--------------
 clang/lib/CodeGen/CGExpr.cpp          |  20 +-
 clang/test/CodeGenCXX/alloc-token.cpp | 229 +++++++++++++---------
 5 files changed, 294 insertions(+), 261 deletions(-)

diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index c9bbe2e6c06ad4..dc3c28975a2c13 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -60,10 +60,13 @@ The following command-line options affect generated token IDs:
 
 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, for example from a `sizeof` in the size
-argument, a cast of the result, or a placement `new` into the result. The
-heuristics are syntactic and ignore control flow and reassignments. If no type
-can be inferred, the allocation receives the fallback token.
+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 function defines the variable exactly once (variables that are reassigned
+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`
 
diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index 5a32cd04644b4f..9aaa106009e729 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -16,26 +16,28 @@
 #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 {
-
-class Stmt;
-
 namespace infer_alloc {
 
-/// Infer the possible allocated type from an allocation call expression.
-/// \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);
+/// 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, directly or via a local variable holding it, to the type
 /// constructed (null if different types are constructed into the same
 /// storage). This covers the "allocate raw storage, then construct in place"
-/// idiom; the constructed type is more precise than a sizeof or a cast, which
-/// may only describe the storage (a char buffer, a base class):
+/// idiom:
 ///
 ///   void *mem = alloc(size);
 ///   MyType *obj = new (mem) MyType();  // infers 'MyType' for alloc(size)
@@ -43,9 +45,9 @@ QualType inferPossibleType(const CallExpr *E, const ASTContext &Ctx,
 ///   auto res = size_returning_alloc(size);
 ///   new (res.p) MyType();              // infers 'MyType' (via member .p)
 ///
-/// Variables are resolved with a lexical def-use chain: the nearest preceding
-/// definition that dominates the use, with no conflicting later definition in
-/// an enclosing loop; otherwise nothing is inferred.
+/// A variable is only used if the function defines it exactly once and never
+/// writes to it otherwise, so that its value is known regardless of control
+/// flow; reassigned variables are not used for inference.
 llvm::DenseMap<const CallExpr *, QualType>
 collectPlacementNewTypes(const Stmt *Body);
 
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 20cdb0f402a439..376649a79d8c02 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -22,7 +22,6 @@
 #include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
-#include <vector>
 
 using namespace clang;
 using namespace infer_alloc;
@@ -172,11 +171,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())
@@ -184,6 +183,10 @@ 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);
@@ -207,83 +210,121 @@ const Expr *stripToStorageSource(const Expr *E) {
 }
 
 /// Finds the allocation call an initializer or assigned value consists of,
-/// looking through casts and the temporaries and trivial copies a class-typed
-/// value may carry.
+/// looking through parentheses, casts, temporaries, and the trivial copy or
+/// move a class-typed value may carry.
 const CallExpr *initializingCall(const Expr *Init) {
   while (Init) {
-    Init = Init->IgnoreParenCasts();
-    if (const auto *EWC = dyn_cast<ExprWithCleanups>(Init)) {
-      Init = EWC->getSubExpr();
-    } else if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Init)) {
-      Init = MTE->getSubExpr();
-    } else if (const auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Init)) {
-      Init = BTE->getSubExpr();
-    } else if (const auto *CE = dyn_cast<CXXConstructExpr>(Init);
-               CE && CE->getNumArgs() == 1 &&
-               CE->getConstructor()->isCopyOrMoveConstructor() &&
-               CE->getConstructor()->isTrivial()) {
-      // A non-trivial copy or move may not be elided (-fno-elide-constructors)
-      // and could replace the pointer.
-      Init = CE->getArg(0);
-    } else if (const auto *FCE = dyn_cast<CXXFunctionalCastExpr>(Init)) {
-      Init = FCE->getSubExpr();
-    } else {
+    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);
 }
 
+/// Returns true if \p Init is a null pointer constant (nullptr, NULL, 0).
+bool isNullPointerInit(const Expr *Init) {
+  Init = Init->IgnoreParenCasts();
+  if (isa<CXXNullPtrLiteralExpr, GNUNullExpr>(Init))
+    return true;
+  const auto *IL = dyn_cast<IntegerLiteral>(Init);
+  return IL && IL->getValue() == 0;
+}
+
+/// Returns the local variable an lvalue expression writes to: the variable
+/// itself, or the variable whose non-static field is written (`res.p = ...`).
+/// \p Direct is set when the variable itself is the lvalue.
+const VarDecl *writtenVar(const Expr *E, bool &Direct) {
+  E = E->IgnoreParens();
+  Direct = true;
+  while (const auto *ME = dyn_cast<MemberExpr>(E)) {
+    if (ME->isArrow() || !isa<FieldDecl>(ME->getMemberDecl()))
+      return nullptr;
+    E = ME->getBase()->IgnoreParenImpCasts();
+    Direct = false;
+  }
+  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
+    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
+        VD && VD->hasLocalStorage())
+      return VD;
+  return nullptr;
+}
+
 /// Records, per allocation call, the type placement-constructed into its
 /// result.
 ///
-/// Placement arguments that name a variable are resolved with a lexical
-/// def-use chain: a use `new (p) T` is matched to the nearest preceding
-/// definition of `p` (its initializer or an assignment `p = <call>`) in
-/// traversal order, provided that definition lexically dominates the use,
-/// i.e. it is in the same control-flow context as the use or an enclosing
-/// one. A definition in a branch that does not enclose the use, a later
-/// definition that can reach the use around a loop, or any other write to
-/// the variable (compound assignment, increment, address-of) makes the use
-/// ambiguous and nothing is inferred for it.
+/// A placement argument that names a local variable (not a parameter, whose
+/// incoming value is a definition that cannot be seen) is resolved only if the
+/// function body contains exactly one definition of that variable (its
+/// initializer, or one assignment; a null pointer initializer does not count)
+/// and no other write to it: no compound assignment, increment, address-of,
+/// write to one of its fields, non-const member call, or binding to a
+/// non-const reference. Every value such a variable ever holds then comes from
+/// that one definition, so the attribution holds under any control flow,
+/// including loops, lambdas, and exceptions. Variables with more than one
+/// definition or any other write are not used for inference.
 class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
 public:
   explicit PlacementNewCollector(
       llvm::DenseMap<const CallExpr *, QualType> &CallTypes)
-      : CallTypes(CallTypes) {
-    // Context 0 is the function body itself.
-    Contexts.push_back({/*Parent=*/-1, /*IsLoop=*/false});
-  }
+      : CallTypes(CallTypes) {}
 
   void finish() {
-    for (const Use &U : Uses) {
-      const CallExpr *CE = resolve(U);
-      if (CE)
-        record(CE, U.Type);
-    }
+    for (const auto &[VD, T] : Uses)
+      if (const CallExpr *CE = Defs.lookup(VD))
+        record(CE, T);
   }
 
   bool VisitVarDecl(const VarDecl *VD) override {
-    if (VD->isLocalVarDecl())
-      addDef(VD, initializingCall(VD->getInit()));
+    if (!VD->hasInit())
+      return true;
+    if (VD->hasLocalStorage() && !isNullPointerInit(VD->getInit()))
+      addDef(VD, VD->getInit());
+    // `T &r = p;` lets the variable be written through the reference.
+    if (VD->getType()->isReferenceType())
+      noteWrite(VD->getInit());
     return true;
   }
 
   bool VisitBinaryOperator(const BinaryOperator *BO) override {
     if (!BO->isAssignmentOp())
       return true;
-    if (const VarDecl *VD = referencedVar(BO->getLHS()))
-      addDef(VD, BO->getOpcode() == BO_Assign ? initializingCall(BO->getRHS())
-                                              : nullptr);
+    bool Direct = false;
+    if (const VarDecl *VD = writtenVar(BO->getLHS(), Direct))
+      addDef(VD,
+             Direct && BO->getOpcode() == BO_Assign ? BO->getRHS() : nullptr);
     return true;
   }
 
   bool VisitUnaryOperator(const UnaryOperator *UO) override {
-    if (UO->getOpcode() != UO_AddrOf && !UO->isIncrementDecrementOp())
-      return true;
-    // The variable may be written through the pointer or reference.
-    if (const VarDecl *VD = referencedVar(UO->getSubExpr()))
-      addDef(VD, nullptr);
+    // The variable may be written through the pointer, or is modified.
+    if (UO->getOpcode() == UO_AddrOf || UO->isIncrementDecrementOp())
+      noteWrite(UO->getSubExpr());
+    return true;
+  }
+
+  bool VisitCallExpr(const CallExpr *CE) override {
+    // Arguments bound to non-const references may be written by the callee.
+    if (const FunctionDecl *FD = CE->getDirectCallee())
+      noteReferenceArgs(FD, CE->arguments());
+    return true;
+  }
+
+  bool VisitCXXConstructExpr(const CXXConstructExpr *CE) override {
+    noteReferenceArgs(CE->getConstructor(), CE->arguments());
+    return true;
+  }
+
+  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) override {
+    // A non-const member function may modify a class-typed variable.
+    const CXXMethodDecl *MD = MCE->getMethodDecl();
+    if (MD && !MD->isConst() && !MD->isStatic())
+      noteWrite(MCE->getImplicitObjectArgument());
     return true;
   }
 
@@ -302,102 +343,41 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
     QualType T = NE->getAllocatedType();
     if (const auto *CE = dyn_cast<CallExpr>(Source))
       record(CE, T);
-    else if (const VarDecl *VD = referencedVar(Source))
-      Uses.push_back({VD, Seq++, CurContext, T});
+    else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
+      // A parameter's incoming value is a definition that cannot be seen.
+      if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
+          VD && VD->hasLocalStorage() && !isa<ParmVarDecl>(VD))
+        Uses.emplace_back(VD, T);
     return true;
   }
 
-  // Control-flow constructs open a new context for the statements they
-  // contain; a definition inside one does not dominate uses outside it.
-#define PLACEMENT_CONTEXT(CLASS, IS_LOOP)                                      \
-  bool Traverse##CLASS(const CLASS *S) override {                              \
-    return inContext(IS_LOOP, [&] {                                            \
-      return ConstDynamicRecursiveASTVisitor::Traverse##CLASS(S);              \
-    });                                                                        \
-  }
-  PLACEMENT_CONTEXT(IfStmt, false)
-  PLACEMENT_CONTEXT(SwitchStmt, false)
-  PLACEMENT_CONTEXT(ConditionalOperator, false)
-  PLACEMENT_CONTEXT(BinaryConditionalOperator, false)
-  PLACEMENT_CONTEXT(LambdaExpr, false)
-  PLACEMENT_CONTEXT(StmtExpr, false)
-  PLACEMENT_CONTEXT(ForStmt, true)
-  PLACEMENT_CONTEXT(WhileStmt, true)
-  PLACEMENT_CONTEXT(DoStmt, true)
-  PLACEMENT_CONTEXT(CXXForRangeStmt, true)
-#undef PLACEMENT_CONTEXT
-
 private:
-  struct Context {
-    int Parent;
-    bool IsLoop;
-  };
-  struct Def {
-    unsigned Seq;
-    int Context;
-    const CallExpr *Call; // null: a write that is not an allocation call
-  };
-  struct Use {
-    const VarDecl *Var;
-    unsigned Seq;
-    int Context;
-    QualType Type;
-  };
-
-  bool inContext(bool IsLoop, llvm::function_ref<bool()> Traverse) {
-    int Saved = CurContext;
-    Contexts.push_back({Saved, IsLoop});
-    CurContext = Contexts.size() - 1;
-    bool Result = Traverse();
-    CurContext = Saved;
-    return Result;
-  }
-
-  static const VarDecl *referencedVar(const Expr *E) {
-    if (const auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
-      return dyn_cast<VarDecl>(DRE->getDecl());
-    return nullptr;
-  }
-
-  void addDef(const VarDecl *VD, const CallExpr *CE) {
-    Defs[VD].push_back({Seq++, CurContext, CE});
+  /// Records a definition of \p VD with \p Value (null for a write that is not
+  /// a plain assignment). A second definition disqualifies the variable.
+  void addDef(const VarDecl *VD, const Expr *Value) {
+    auto [It, Inserted] =
+        Defs.try_emplace(VD, Value ? initializingCall(Value) : nullptr);
+    if (!Inserted)
+      It->second = nullptr;
   }
 
-  bool isAncestorOrSelf(int Ancestor, int Ctx) const {
-    for (; Ctx >= 0; Ctx = Contexts[Ctx].Parent)
-      if (Ctx == Ancestor)
-        return true;
-    return false;
-  }
-
-  bool isInLoop(int Ctx) const {
-    for (; Ctx >= 0; Ctx = Contexts[Ctx].Parent)
-      if (Contexts[Ctx].IsLoop)
-        return true;
-    return false;
+  void noteWrite(const Expr *E) {
+    bool Direct = false;
+    if (const VarDecl *VD = writtenVar(E, Direct))
+      addDef(VD, nullptr);
   }
 
-  /// Returns the allocation call that defines the variable of \p U at the
-  /// use, or null if there is none or it cannot be determined.
-  const CallExpr *resolve(const Use &U) const {
-    auto It = Defs.find(U.Var);
-    if (It == Defs.end())
-      return nullptr;
-    const Def *Reaching = nullptr;
-    bool LaterDef = false;
-    for (const Def &D : It->second) {
-      if (D.Seq < U.Seq)
-        Reaching = &D; // defs are in traversal order; keep the last one
-      else
-        LaterDef = true;
+  void noteReferenceArgs(const FunctionDecl *FD,
+                         CallExpr::const_arg_range Args) {
+    unsigned I = 0;
+    for (const Expr *Arg : Args) {
+      if (I >= FD->getNumParams())
+        break;
+      QualType ParamTy = FD->getParamDecl(I++)->getType();
+      if (ParamTy->isLValueReferenceType() &&
+          !ParamTy.getNonReferenceType().isConstQualified())
+        noteWrite(Arg);
     }
-    if (!Reaching || !Reaching->Call ||
-        !isAncestorOrSelf(Reaching->Context, U.Context))
-      return nullptr;
-    // A later definition can reach the use around a loop back edge.
-    if (LaterDef && isInLoop(U.Context))
-      return nullptr;
-    return Reaching->Call;
   }
 
   void record(const CallExpr *CE, QualType T) {
@@ -409,11 +389,10 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
   }
 
   llvm::DenseMap<const CallExpr *, QualType> &CallTypes;
-  std::vector<Context> Contexts;
-  int CurContext = 0;
-  unsigned Seq = 0;
-  llvm::DenseMap<const VarDecl *, llvm::SmallVector<Def, 2>> Defs;
-  std::vector<Use> Uses;
+  // Variable -> its single defining allocation call; null once the variable
+  // has a second definition or another write.
+  llvm::DenseMap<const VarDecl *, const CallExpr *> Defs;
+  llvm::SmallVector<std::pair<const VarDecl *, QualType>> Uses;
 };
 } // namespace
 
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 110432d25cabdd..d7bea0fae62cc7 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -1407,16 +1407,16 @@ void CodeGenFunction::EmitAllocToken(llvm::CallBase *CB, QualType AllocType) {
 }
 
 llvm::MDNode *CodeGenFunction::buildAllocToken(const CallExpr *E) {
-  // A placement new into the result is the strongest evidence of the allocated
-  // type: it names the object actually constructed, whereas a sizeof or a cast
-  // may only describe the raw storage (e.g. a char buffer or a base class).
-  if (!AllocTokenPlacementTypes)
-    AllocTokenPlacementTypes = infer_alloc::collectPlacementNewTypes(
-        CurCodeDecl ? CurCodeDecl->getBody() : nullptr);
-  QualType T = AllocTokenPlacementTypes->lookup(E);
-  if (T.isNull())
-    T = infer_alloc::inferPossibleType(E, getContext(), CurCast);
-  return buildAllocToken(T);
+  // 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/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index db07ae2cec7ac0..e7cfdad21aa850 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -162,7 +162,8 @@ struct PlacedWithPtr {
   long len;
 };
 
-// Allocation calls whose result is only named by a later placement new.
+// 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]+]]
@@ -202,13 +203,40 @@ PlacedNoPtr *test_placement_new_array() {
   return new (mem) PlacedNoPtr[10];
 }
 
-// The placement new names the constructed object and takes precedence over a
-// sizeof in the size argument, which may only describe the storage.
+// 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 16){{.*}} !alloc_token [[META_PLACEDNOPTR]]
-PlacedNoPtr *test_placement_new_sizeof_prevails() {
-  void *mem = malloc(sizeof(PlacedWithPtr));
-  return new (mem) PlacedNoPtr();
+// CHECK: call noalias ptr @malloc(i64 noundef 40){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// 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 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();
+  auto *p2 = (unsigned char *)malloc(64);
+  sink = new (p2) 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.
@@ -286,116 +314,136 @@ void test_placement_new_indirect() {
   sink = new (span.storage) PlacedNoPtr();
 }
 
-// Likewise over a cast of the result, whether to a raw storage pointer
-// (void *, char *, ...) or to a base class of the constructed type.
-struct DerivedWithPtr : PlacedNoPtr {
-  void *next;
-};
-// CHECK-LABEL: define dso_local void @_Z30test_placement_new_raw_storagev(
-// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
-// 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]]
+// A variable is used only if the function defines it exactly once, so that
+// its value does not depend on control flow. A null pointer initializer does
+// not count as a definition.
+// CHECK-LABEL: define dso_local void @_Z36test_placement_new_single_definitionb(
+// 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 noalias ptr @malloc(i64 noundef 32){{.*}} !alloc_token [[META_DERIVEDWITHPTR:![0-9]+]]
-void test_placement_new_raw_storage() {
-  char *p1 = static_cast<char *>(malloc(64));
-  sink = new (p1) PlacedWithPtr();
-  auto *p2 = (unsigned char *)malloc(64);
-  sink = new (p2) PlacedWithPtr();
-  // The member access is an implicit lvalue-to-rvalue cast to void *.
-  sink = new (__size_returning_new(64).p) PlacedWithPtr();
-  void *p3 = malloc(sizeof(char) * 64);
-  sink = new (p3) PlacedWithPtr();
-  auto *base = static_cast<PlacedNoPtr *>(malloc(32));
-  sink = new (base) DerivedWithPtr();
-}
-
-// 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{});
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+void test_placement_new_single_definition(bool c) {
+  // Declared without initializer, assigned once.
+  void *p;
+  p = malloc(64);
+  sink = new (p) PlacedNoPtr();
+  // Initialized to null, assigned once in a branch.
+  void *q = nullptr;
+  if (c)
+    q = malloc(64);
+  if (q)
+    sink = new (q) PlacedWithPtr();
+  // Defined once, used inside a branch and a loop.
+  void *r = malloc(64);
+  if (c)
+    sink = new (r) PlacedNoPtr();
+  void *s = malloc(64);
+  for (int i = 0; i < 2; ++i)
+    sink = new (s) PlacedWithPtr();
 }
 
-// Variables are resolved with a lexical def-use chain: the nearest preceding
-// definition that dominates the use.
-// CHECK-LABEL: define dso_local void @_Z27test_placement_new_reassignv(
+// Reassigned variables are not used: the storage the placement new ends up in
+// depends on control flow, and the sizeof or cast of the other definition
+// would be overridden. Nothing is inferred for any of these allocations.
+// CHECK-LABEL: define dso_local void @_Z29test_placement_new_reassignedb(
 // CHECK: call noalias ptr @malloc(i64 noundef 8)
-// CHECK-NOT: @malloc{{.*}}!alloc_token
-// CHECK: call noalias ptr @malloc(i64 noundef 8){{.*}} !alloc_token [[META_LONG]]
-// 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 noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
-void test_placement_new_reassign() {
-  // The first allocation is freed and the variable reassigned before the
-  // placement new: only the second allocation is typed.
+// 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: ret void
+void test_placement_new_reassigned(bool c) {
+  // Freed and reassigned before the placement new.
   void *p = malloc(8);
   free(p);
   p = malloc(8);
   sink = new (p) long(10);
-  // Declared without initializer, assigned later.
-  void *q;
-  q = malloc(64);
-  sink = new (q) PlacedNoPtr();
-  // Each definition is matched to the uses that follow it.
+  // Redefined in one branch of an if, used in the other.
+  void *q = malloc(64);
+  if (c)
+    q = malloc(32);
+  else
+    sink = new (q) PlacedNoPtr();
+  // Captured by reference and reassigned before the lambda runs.
   void *r = malloc(64);
-  sink = new (r) PlacedWithPtr();
-  r = malloc(64);
-  sink = new (r) PlacedNoPtr();
+  auto construct = [&] { sink = new (r) PlacedNoPtr(); };
+  r = malloc(32);
+  construct();
 }
 
-// Definitions that do not dominate the use, later definitions in a loop, and
-// other writes to the variable make the use ambiguous: nothing is inferred.
-// CHECK-LABEL: define dso_local void @_Z29test_placement_new_ambiguous2b(
+// A parameter's incoming value is a definition that cannot be seen, so
+// parameters are not used.
+// CHECK-LABEL: define dso_local void @_Z28test_placement_new_parameterPvb(
 // 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: ret void
+void test_placement_new_parameter(void *p, bool c) {
+  if (c)
+    p = malloc(64);
+  sink = new (p) PlacedNoPtr();
+}
+
+// Other writes to the variable disqualify it as well: compound assignment,
+// address-of, a write to one of its fields, a non-const member call, and
+// binding to a non-const reference, directly or as a call argument.
+struct Storage {
+  void *p;
+  size_t n;
+  void reset();
+};
+Storage alloc_storage(size_t) __attribute__((malloc_span));
+void rebind(void *&p);
+// CHECK-LABEL: define dso_local void @_Z31test_placement_new_other_writesv(
 // CHECK: call noalias ptr @malloc(i64 noundef 64)
 // CHECK-NOT: !alloc_token
-// CHECK: call noalias ptr @malloc(i64 noundef 32)
+// CHECK: call { ptr, i64 } @_Z13alloc_storagem(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: ret void
-void test_placement_new_ambiguous2(bool c) {
-  // A definition in a branch does not dominate the use after it.
+void test_placement_new_other_writes() {
   void *p = malloc(64);
-  if (c)
-    p = malloc(32);
+  sink = &p;
   sink = new (p) PlacedNoPtr();
-  // A definition after the use inside the loop reaches it around the back
-  // edge.
+  Storage s1 = alloc_storage(64);
+  s1.p = sink;
+  sink = new (s1.p) PlacedNoPtr();
+  Storage s2 = alloc_storage(64);
+  s2.reset();
+  sink = new (s2.p) PlacedNoPtr();
   void *q = malloc(64);
-  for (int i = 0; i < 2; ++i) {
-    sink = new (q) PlacedNoPtr();
-    q = malloc(32);
-  }
-  // Address taken: the variable may be written through the pointer.
+  void *&qref = q;
+  qref = sink;
+  sink = new (q) PlacedNoPtr();
   void *r = malloc(64);
-  sink = &r;
+  rebind(r);
   sink = new (r) PlacedNoPtr();
 }
 
-// Uses inside a branch or loop are dominated by a definition before it.
-// CHECK-LABEL: define dso_local void @_Z29test_placement_new_dominatingb(
+// 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){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
-void test_placement_new_dominating(bool c) {
-  void *p = malloc(64);
-  if (c)
-    sink = new (p) PlacedNoPtr();
-  void *q = malloc(64);
-  for (int i = 0; i < 2; ++i)
-    sink = new (q) PlacedWithPtr();
+// 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>
@@ -422,5 +470,6 @@ void test_placement_new_template() {
 // CHECK: [[META_TESTCLASS]] = !{!"TestClass", i1 true}
 // CHECK: [[META_PLACEDNOPTR]] = !{!"PlacedNoPtr", i1 false}
 // CHECK: [[META_PLACEDWITHPTR]] = !{!"PlacedWithPtr", i1 true}
-// CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}
+// CHECK: [[META_CHAR]] = !{!"char", i1 false}
 // CHECK: [[META_DERIVEDWITHPTR]] = !{!"DerivedWithPtr", i1 true}
+// CHECK: [[META_CLASSPLACEMENT]] = !{!"ClassPlacement", i1 true}

>From 78b13e7598ce3654dfe99d381ba02e0bbfc6e61f Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Fri, 13 Nov 2026 09:52:09 -0800
Subject: [PATCH 7/9] Test the remaining single-definition cases

Compound assignment, increment, a non-const reference constructor
argument, non-local variables, p = new (p) T, and the negative controls
(const reference argument, const member call).
---
 clang/test/CodeGenCXX/alloc-token.cpp | 69 +++++++++++++++++++++++----
 1 file changed, 60 insertions(+), 9 deletions(-)

diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index e7cfdad21aa850..be138fbffd116e 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -317,11 +317,21 @@ void test_placement_new_indirect() {
 // A variable is used only if the function defines it exactly once, so that
 // its value does not depend on control flow. A null pointer initializer does
 // not count as a definition.
+struct Storage {
+  void *p;
+  size_t n;
+  size_t size() const;
+  void reset();
+};
+Storage alloc_storage(size_t) __attribute__((malloc_span));
+void peek(void *const &p);
 // CHECK-LABEL: define dso_local void @_Z36test_placement_new_single_definitionb(
 // 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 noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
 // CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
+// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
+// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
 void test_placement_new_single_definition(bool c) {
   // Declared without initializer, assigned once.
   void *p;
@@ -340,6 +350,14 @@ void test_placement_new_single_definition(bool c) {
   void *s = malloc(64);
   for (int i = 0; i < 2; ++i)
     sink = new (s) PlacedWithPtr();
+  // Reads through a const reference or a const member function are not
+  // writes.
+  void *t = malloc(64);
+  peek(t);
+  sink = new (t) PlacedNoPtr();
+  Storage u = alloc_storage(64);
+  (void)u.size();
+  sink = new (u.p) PlacedWithPtr();
 }
 
 // Reassigned variables are not used: the storage the placement new ends up in
@@ -358,6 +376,8 @@ void test_placement_new_single_definition(bool c) {
 // 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: ret void
 void test_placement_new_reassigned(bool c) {
   // Freed and reassigned before the placement new.
@@ -376,6 +396,9 @@ void test_placement_new_reassigned(bool c) {
   auto construct = [&] { sink = new (r) PlacedNoPtr(); };
   r = malloc(32);
   construct();
+  // The assignment of the placement new's result is a second definition.
+  void *s = malloc(64);
+  s = new (s) PlacedNoPtr();
 }
 
 // A parameter's incoming value is a definition that cannot be seen, so
@@ -390,19 +413,19 @@ void test_placement_new_parameter(void *p, bool c) {
   sink = new (p) PlacedNoPtr();
 }
 
-// Other writes to the variable disqualify it as well: compound assignment,
-// address-of, a write to one of its fields, a non-const member call, and
-// binding to a non-const reference, directly or as a call argument.
-struct Storage {
-  void *p;
-  size_t n;
-  void reset();
-};
-Storage alloc_storage(size_t) __attribute__((malloc_span));
+// Other writes to the variable disqualify it as well: address-of, compound
+// assignment, increment, a write to one of its fields, a non-const member
+// call, and binding to a non-const reference, directly, as a call argument,
+// or as a constructor argument.
 void rebind(void *&p);
+struct Rebinder {
+  Rebinder(void *&p);
+};
 // CHECK-LABEL: define dso_local void @_Z31test_placement_new_other_writesv(
 // 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 { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
 // CHECK-NOT: !alloc_token
 // CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
@@ -411,11 +434,20 @@ void rebind(void *&p);
 // 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_other_writes() {
   void *p = malloc(64);
   sink = &p;
   sink = new (p) PlacedNoPtr();
+  // With the variable disqualified, the cast of the result applies instead.
+  char *p2 = static_cast<char *>(malloc(64));
+  p2 += 8;
+  sink = new (p2) PlacedNoPtr();
+  char *p3 = static_cast<char *>(malloc(64));
+  ++p3;
+  sink = new (p3) PlacedNoPtr();
   Storage s1 = alloc_storage(64);
   s1.p = sink;
   sink = new (s1.p) PlacedNoPtr();
@@ -429,6 +461,25 @@ void test_placement_new_other_writes() {
   void *r = malloc(64);
   rebind(r);
   sink = new (r) PlacedNoPtr();
+  void *t = malloc(64);
+  Rebinder rebinder(t);
+  sink = new (t) 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: call 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;
+  static_storage = malloc(64);
+  sink = new (static_storage) PlacedNoPtr();
 }
 
 // Non-generic lambdas use the captured variable; a generic lambda's dependent

>From 2f210725c0101d89397a081c3b7a7a43fb99e50e Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Mon, 16 Nov 2026 10:53:17 -0800
Subject: [PATCH 8/9] Qualify variables by reads only; definitions are
 initializers only

A variable is used only if it is initialized by the allocation call and
every other reference to it (or to one of its fields) is consumed by an
lvalue-to-rvalue conversion. Assignment, compound assignment, increment,
address-of, reference binding of any form, member and operator calls and
by-reference captures all disqualify it without being enumerated.
Assignment-as-definition and the null-initializer exemption are dropped.
Free helpers are static instead of in an anonymous namespace;
stripToStorageSource is a single pass.
---
 clang/docs/AllocToken.md              |   7 +-
 clang/include/clang/AST/InferAlloc.h  |   7 +-
 clang/lib/AST/InferAlloc.cpp          | 179 +++++++--------------
 clang/test/CodeGenCXX/alloc-token.cpp | 215 ++++++++++++--------------
 4 files changed, 161 insertions(+), 247 deletions(-)

diff --git a/clang/docs/AllocToken.md b/clang/docs/AllocToken.md
index dc3c28975a2c13..092e4eb56f0679 100644
--- a/clang/docs/AllocToken.md
+++ b/clang/docs/AllocToken.md
@@ -64,9 +64,10 @@ 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 function defines the variable exactly once (variables that are reassigned
-are not used for inference). If no type can be inferred, the allocation
-receives the fallback token.
+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`
 
diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index 9aaa106009e729..0bee13a0054076 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -45,9 +45,10 @@ QualType inferPossibleType(
 ///   auto res = size_returning_alloc(size);
 ///   new (res.p) MyType();              // infers 'MyType' (via member .p)
 ///
-/// A variable is only used if the function defines it exactly once and never
-/// writes to it otherwise, so that its value is known regardless of control
-/// flow; reassigned variables are not used for inference.
+/// A variable is only used if it is initialized by the allocation call and is
+/// otherwise only ever read, so that its value is known regardless of control
+/// flow; variables that are assigned to, or whose address or reference is
+/// taken, are not used for inference.
 llvm::DenseMap<const CallExpr *, QualType>
 collectPlacementNewTypes(const Stmt *Body);
 
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index 376649a79d8c02..a21c254bfff54e 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -193,26 +193,34 @@ QualType infer_alloc::inferPossibleType(
   return AllocType;
 }
 
-namespace {
+/// 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;
+}
+
 /// Strips the wrappers a placement argument may have around the expression
 /// that produced the storage: parentheses, casts, and non-static member
-/// accesses of a by-value result (e.g. the pointer member of a size-returning
-/// allocation result). Anything that follows a pointer into different storage
-/// (`->`, `*`) or names a different object (`&`) stops the walk.
-const Expr *stripToStorageSource(const Expr *E) {
-  while (true) {
-    E = E->IgnoreParenCasts();
-    const auto *ME = dyn_cast<MemberExpr>(E);
-    if (!ME || ME->isArrow() || !isa<FieldDecl>(ME->getMemberDecl()))
-      return E;
-    E = ME->getBase();
-  }
+/// accesses of a by-value result. Anything that follows a pointer into
+/// different storage (`->`, `*`) or names a different object (`&`) stops the
+/// walk.
+static const Expr *stripToStorageSource(const Expr *E) {
+  return stripFields(E->IgnoreParenCasts());
 }
 
-/// Finds the allocation call an initializer or assigned value consists of,
-/// looking through parentheses, casts, temporaries, and the trivial copy or
-/// move a class-typed value may carry.
-const CallExpr *initializingCall(const Expr *Init) {
+/// 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);
@@ -227,53 +235,26 @@ const CallExpr *initializingCall(const Expr *Init) {
   return dyn_cast_or_null<CallExpr>(Init);
 }
 
-/// Returns true if \p Init is a null pointer constant (nullptr, NULL, 0).
-bool isNullPointerInit(const Expr *Init) {
-  Init = Init->IgnoreParenCasts();
-  if (isa<CXXNullPtrLiteralExpr, GNUNullExpr>(Init))
-    return true;
-  const auto *IL = dyn_cast<IntegerLiteral>(Init);
-  return IL && IL->getValue() == 0;
-}
-
-/// Returns the local variable an lvalue expression writes to: the variable
-/// itself, or the variable whose non-static field is written (`res.p = ...`).
-/// \p Direct is set when the variable itself is the lvalue.
-const VarDecl *writtenVar(const Expr *E, bool &Direct) {
-  E = E->IgnoreParens();
-  Direct = true;
-  while (const auto *ME = dyn_cast<MemberExpr>(E)) {
-    if (ME->isArrow() || !isa<FieldDecl>(ME->getMemberDecl()))
-      return nullptr;
-    E = ME->getBase()->IgnoreParenImpCasts();
-    Direct = false;
-  }
-  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
-    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
-        VD && VD->hasLocalStorage())
-      return VD;
-  return nullptr;
-}
-
+namespace {
 /// Records, per allocation call, the type placement-constructed into its
 /// result.
 ///
-/// A placement argument that names a local variable (not a parameter, whose
-/// incoming value is a definition that cannot be seen) is resolved only if the
-/// function body contains exactly one definition of that variable (its
-/// initializer, or one assignment; a null pointer initializer does not count)
-/// and no other write to it: no compound assignment, increment, address-of,
-/// write to one of its fields, non-const member call, or binding to a
-/// non-const reference. Every value such a variable ever holds then comes from
-/// that one definition, so the attribution holds under any control flow,
-/// including loops, lambdas, and exceptions. Variables with more than one
-/// definition or any other write are not used for inference.
+/// A placement argument that names a local variable is resolved only if the
+/// variable is initialized by the allocation call and is otherwise only ever
+/// read: every other reference to it (or to one of its fields) is consumed by
+/// an lvalue-to-rvalue conversion. Any other use (assignment, compound
+/// assignment, increment, address-of, binding to a reference, a member or
+/// operator call, a by-reference capture) may change its value and
+/// disqualifies it, so the value is known regardless of control flow.
+/// Parameters are not used, as their incoming value is unknown.
 class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
 public:
   explicit PlacementNewCollector(
       llvm::DenseMap<const CallExpr *, QualType> &CallTypes)
       : CallTypes(CallTypes) {}
 
+  // Resolved after the traversal: a use that is not a read may follow the
+  // placement new and still disqualify the variable.
   void finish() {
     for (const auto &[VD, T] : Uses)
       if (const CallExpr *CE = Defs.lookup(VD))
@@ -281,50 +262,27 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
   }
 
   bool VisitVarDecl(const VarDecl *VD) override {
-    if (!VD->hasInit())
-      return true;
-    if (VD->hasLocalStorage() && !isNullPointerInit(VD->getInit()))
-      addDef(VD, VD->getInit());
-    // `T &r = p;` lets the variable be written through the reference.
-    if (VD->getType()->isReferenceType())
-      noteWrite(VD->getInit());
-    return true;
-  }
-
-  bool VisitBinaryOperator(const BinaryOperator *BO) override {
-    if (!BO->isAssignmentOp())
-      return true;
-    bool Direct = false;
-    if (const VarDecl *VD = writtenVar(BO->getLHS(), Direct))
-      addDef(VD,
-             Direct && BO->getOpcode() == BO_Assign ? BO->getRHS() : nullptr);
+    if (VD->hasLocalStorage() && !isa<ParmVarDecl>(VD))
+      if (const CallExpr *CE = initializingCall(VD->getInit()))
+        Defs.try_emplace(VD, CE);
     return true;
   }
 
-  bool VisitUnaryOperator(const UnaryOperator *UO) override {
-    // The variable may be written through the pointer, or is modified.
-    if (UO->getOpcode() == UO_AddrOf || UO->isIncrementDecrementOp())
-      noteWrite(UO->getSubExpr());
+  // 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;
   }
 
-  bool VisitCallExpr(const CallExpr *CE) override {
-    // Arguments bound to non-const references may be written by the callee.
-    if (const FunctionDecl *FD = CE->getDirectCallee())
-      noteReferenceArgs(FD, CE->arguments());
-    return true;
-  }
-
-  bool VisitCXXConstructExpr(const CXXConstructExpr *CE) override {
-    noteReferenceArgs(CE->getConstructor(), CE->arguments());
-    return true;
-  }
-
-  bool VisitCXXMemberCallExpr(const CXXMemberCallExpr *MCE) override {
-    // A non-const member function may modify a class-typed variable.
-    const CXXMethodDecl *MD = MCE->getMethodDecl();
-    if (MD && !MD->isConst() && !MD->isStatic())
-      noteWrite(MCE->getImplicitObjectArgument());
+  // 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;
   }
 
@@ -344,42 +302,12 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
     if (const auto *CE = dyn_cast<CallExpr>(Source))
       record(CE, T);
     else if (const auto *DRE = dyn_cast<DeclRefExpr>(Source))
-      // A parameter's incoming value is a definition that cannot be seen.
-      if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
-          VD && VD->hasLocalStorage() && !isa<ParmVarDecl>(VD))
+      if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
         Uses.emplace_back(VD, T);
     return true;
   }
 
 private:
-  /// Records a definition of \p VD with \p Value (null for a write that is not
-  /// a plain assignment). A second definition disqualifies the variable.
-  void addDef(const VarDecl *VD, const Expr *Value) {
-    auto [It, Inserted] =
-        Defs.try_emplace(VD, Value ? initializingCall(Value) : nullptr);
-    if (!Inserted)
-      It->second = nullptr;
-  }
-
-  void noteWrite(const Expr *E) {
-    bool Direct = false;
-    if (const VarDecl *VD = writtenVar(E, Direct))
-      addDef(VD, nullptr);
-  }
-
-  void noteReferenceArgs(const FunctionDecl *FD,
-                         CallExpr::const_arg_range Args) {
-    unsigned I = 0;
-    for (const Expr *Arg : Args) {
-      if (I >= FD->getNumParams())
-        break;
-      QualType ParamTy = FD->getParamDecl(I++)->getType();
-      if (ParamTy->isLValueReferenceType() &&
-          !ParamTy.getNonReferenceType().isConstQualified())
-        noteWrite(Arg);
-    }
-  }
-
   void record(const CallExpr *CE, QualType T) {
     auto [It, Inserted] = CallTypes.try_emplace(CE, T);
     // Different types constructed into the same storage: ambiguous.
@@ -389,9 +317,10 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
   }
 
   llvm::DenseMap<const CallExpr *, QualType> &CallTypes;
-  // Variable -> its single defining allocation call; null once the variable
-  // has a second definition or another write.
+  // 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
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index be138fbffd116e..5c9c08672e07dd 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -314,56 +314,46 @@ void test_placement_new_indirect() {
   sink = new (span.storage) PlacedNoPtr();
 }
 
-// A variable is used only if the function defines it exactly once, so that
-// its value does not depend on control flow. A null pointer initializer does
-// not count as a definition.
+// 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;
-  size_t size() const;
-  void reset();
 };
 Storage alloc_storage(size_t) __attribute__((malloc_span));
-void peek(void *const &p);
-// CHECK-LABEL: define dso_local void @_Z36test_placement_new_single_definitionb(
-// 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-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 noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
-// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR]]
-void test_placement_new_single_definition(bool c) {
-  // Declared without initializer, assigned once.
-  void *p;
-  p = malloc(64);
-  sink = new (p) PlacedNoPtr();
-  // Initialized to null, assigned once in a branch.
-  void *q = nullptr;
-  if (c)
-    q = malloc(64);
-  if (q)
-    sink = new (q) PlacedWithPtr();
-  // Defined once, used inside a branch and a loop.
-  void *r = malloc(64);
+// 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 (r) PlacedNoPtr();
-  void *s = malloc(64);
+    sink = new (p) PlacedNoPtr();
+  sink = p;
+  void *q = malloc(64);
   for (int i = 0; i < 2; ++i)
-    sink = new (s) PlacedWithPtr();
-  // Reads through a const reference or a const member function are not
-  // writes.
-  void *t = malloc(64);
-  peek(t);
-  sink = new (t) PlacedNoPtr();
-  Storage u = alloc_storage(64);
-  (void)u.size();
-  sink = new (u.p) PlacedWithPtr();
-}
-
-// Reassigned variables are not used: the storage the placement new ends up in
-// depends on control flow, and the sizeof or cast of the other definition
-// would be overridden. Nothing is inferred for any of these allocations.
-// CHECK-LABEL: define dso_local void @_Z29test_placement_new_reassignedb(
+    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)
@@ -378,92 +368,86 @@ void test_placement_new_single_definition(bool c) {
 // CHECK-NOT: !alloc_token
 // CHECK: call noalias ptr @malloc(i64 noundef 64)
 // CHECK-NOT: !alloc_token
-// CHECK: ret void
-void test_placement_new_reassigned(bool c) {
-  // Freed and reassigned before the placement new.
-  void *p = malloc(8);
-  free(p);
-  p = malloc(8);
-  sink = new (p) long(10);
-  // Redefined in one branch of an if, used in the other.
-  void *q = malloc(64);
-  if (c)
-    q = malloc(32);
-  else
-    sink = new (q) PlacedNoPtr();
-  // Captured by reference and reassigned before the lambda runs.
-  void *r = malloc(64);
-  auto construct = [&] { sink = new (r) PlacedNoPtr(); };
-  r = malloc(32);
-  construct();
-  // The assignment of the placement new's result is a second definition.
-  void *s = malloc(64);
-  s = new (s) PlacedNoPtr();
-}
-
-// A parameter's incoming value is a definition that cannot be seen, so
-// parameters are not used.
-// CHECK-LABEL: define dso_local void @_Z28test_placement_new_parameterPvb(
+// 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: ret void
-void test_placement_new_parameter(void *p, bool c) {
-  if (c)
-    p = malloc(64);
-  sink = new (p) PlacedNoPtr();
-}
-
-// Other writes to the variable disqualify it as well: address-of, compound
-// assignment, increment, a write to one of its fields, a non-const member
-// call, and binding to a non-const reference, directly, as a call argument,
-// or as a constructor argument.
-void rebind(void *&p);
-struct Rebinder {
-  Rebinder(void *&p);
-};
-// CHECK-LABEL: define dso_local void @_Z31test_placement_new_other_writesv(
+// 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){{.*}} !alloc_token [[META_CHAR]]
-// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_CHAR]]
-// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
+// CHECK: call noalias ptr @malloc(i64 noundef 64)
 // CHECK-NOT: !alloc_token
-// CHECK: call { ptr, i64 } @_Z13alloc_storagem(i64 noundef 64)
+// 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_other_writes() {
-  void *p = malloc(64);
-  sink = &p;
+void test_placement_new_not_initialized(void *p, bool c) {
+  if (c)
+    p = malloc(64);
   sink = new (p) PlacedNoPtr();
-  // With the variable disqualified, the cast of the result applies instead.
-  char *p2 = static_cast<char *>(malloc(64));
-  p2 += 8;
-  sink = new (p2) PlacedNoPtr();
-  char *p3 = static_cast<char *>(malloc(64));
-  ++p3;
-  sink = new (p3) PlacedNoPtr();
-  Storage s1 = alloc_storage(64);
-  s1.p = sink;
-  sink = new (s1.p) PlacedNoPtr();
-  Storage s2 = alloc_storage(64);
-  s2.reset();
-  sink = new (s2.p) PlacedNoPtr();
-  void *q = malloc(64);
-  void *&qref = q;
-  qref = sink;
-  sink = new (q) PlacedNoPtr();
-  void *r = malloc(64);
-  rebind(r);
-  sink = new (r) PlacedNoPtr();
-  void *t = malloc(64);
-  Rebinder rebinder(t);
-  sink = new (t) 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.
@@ -471,14 +455,13 @@ 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: call noalias ptr @malloc(i64 noundef 64)
+// 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;
-  static_storage = malloc(64);
+  static void *static_storage = malloc(64);
   sink = new (static_storage) PlacedNoPtr();
 }
 

>From a036887291a7fc4c69ac98464c2020d4d918cdbc Mon Sep 17 00:00:00 2001
From: David Li <davidxl at google.com>
Date: Tue, 17 Nov 2026 23:09:13 -0800
Subject: [PATCH 9/9] Trim comments, helpers and redundant tests

---
 clang/include/clang/AST/InferAlloc.h  | 18 ++--------
 clang/lib/AST/InferAlloc.cpp          | 52 +++++++--------------------
 clang/test/CodeGenCXX/alloc-token.cpp | 34 +-----------------
 3 files changed, 16 insertions(+), 88 deletions(-)

diff --git a/clang/include/clang/AST/InferAlloc.h b/clang/include/clang/AST/InferAlloc.h
index 0bee13a0054076..79c65889d410d6 100644
--- a/clang/include/clang/AST/InferAlloc.h
+++ b/clang/include/clang/AST/InferAlloc.h
@@ -34,21 +34,9 @@ QualType inferPossibleType(
     llvm::function_ref<QualType(const CallExpr *)> PlacementNewType = nullptr);
 
 /// Maps the allocation calls in \p Body whose result is used as placement-new
-/// storage, directly or via a local variable holding it, to the type
-/// constructed (null if different types are constructed into the same
-/// storage). This covers the "allocate raw storage, then construct in place"
-/// idiom:
-///
-///   void *mem = alloc(size);
-///   MyType *obj = new (mem) MyType();  // infers 'MyType' for alloc(size)
-///
-///   auto res = size_returning_alloc(size);
-///   new (res.p) MyType();              // infers 'MyType' (via member .p)
-///
-/// A variable is only used if it is initialized by the allocation call and is
-/// otherwise only ever read, so that its value is known regardless of control
-/// flow; variables that are assigned to, or whose address or reference is
-/// taken, are not used for inference.
+/// 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);
 
diff --git a/clang/lib/AST/InferAlloc.cpp b/clang/lib/AST/InferAlloc.cpp
index a21c254bfff54e..6767b3bf4dd308 100644
--- a/clang/lib/AST/InferAlloc.cpp
+++ b/clang/lib/AST/InferAlloc.cpp
@@ -19,7 +19,6 @@
 #include "clang/AST/ExprCXX.h"
 #include "clang/AST/Type.h"
 #include "clang/Basic/IdentifierTable.h"
-#include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/SmallVector.h"
 
@@ -208,15 +207,6 @@ static const Expr *stripFields(const Expr *E) {
   return E;
 }
 
-/// Strips the wrappers a placement argument may have around the expression
-/// that produced the storage: parentheses, casts, and non-static member
-/// accesses of a by-value result. Anything that follows a pointer into
-/// different storage (`->`, `*`) or names a different object (`&`) stops the
-/// walk.
-static const Expr *stripToStorageSource(const Expr *E) {
-  return stripFields(E->IgnoreParenCasts());
-}
-
 /// 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.
@@ -236,29 +226,17 @@ static const CallExpr *initializingCall(const Expr *Init) {
 }
 
 namespace {
-/// Records, per allocation call, the type placement-constructed into its
-/// result.
-///
-/// A placement argument that names a local variable is resolved only if the
-/// variable is initialized by the allocation call and is otherwise only ever
-/// read: every other reference to it (or to one of its fields) is consumed by
-/// an lvalue-to-rvalue conversion. Any other use (assignment, compound
-/// assignment, increment, address-of, binding to a reference, a member or
-/// operator call, a by-reference capture) may change its value and
-/// disqualifies it, so the value is known regardless of control flow.
-/// Parameters are not used, as their incoming value is unknown.
+/// 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(
-      llvm::DenseMap<const CallExpr *, QualType> &CallTypes)
-      : CallTypes(CallTypes) {}
-
   // Resolved after the traversal: a use that is not a read may follow the
   // placement new and still disqualify the variable.
-  void finish() {
+  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 {
@@ -287,17 +265,14 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
   }
 
   bool VisitCXXNewExpr(const CXXNewExpr *NE) override {
-    // Only the reserved non-allocating placement form, new (storage) T, is
-    // guaranteed to construct into its single placement argument. A
-    // class-specific or otherwise user-provided operator new(size_t, void *)
-    // may treat the argument as allocator state and return other storage.
-    // Dependent new-expressions (e.g. in a generic lambda) have no resolved
-    // operator and are skipped.
+    // 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 = stripToStorageSource(NE->getPlacementArg(0));
+    const Expr *Source =
+        stripFields(NE->getPlacementArg(0)->IgnoreParenCasts());
     QualType T = NE->getAllocatedType();
     if (const auto *CE = dyn_cast<CallExpr>(Source))
       record(CE, T);
@@ -316,7 +291,7 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
       It->second = QualType();
   }
 
-  llvm::DenseMap<const CallExpr *, QualType> &CallTypes;
+  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;
@@ -327,13 +302,10 @@ class PlacementNewCollector : public ConstDynamicRecursiveASTVisitor {
 
 llvm::DenseMap<const CallExpr *, QualType>
 infer_alloc::collectPlacementNewTypes(const Stmt *Body) {
-  llvm::DenseMap<const CallExpr *, QualType> CallTypes;
-  if (Body) {
-    PlacementNewCollector Collector(CallTypes);
+  PlacementNewCollector Collector;
+  if (Body)
     Collector.TraverseStmt(Body);
-    Collector.finish();
-  }
-  return CallTypes;
+  return std::move(Collector).finish();
 }
 
 std::optional<llvm::AllocTokenMetadata>
diff --git a/clang/test/CodeGenCXX/alloc-token.cpp b/clang/test/CodeGenCXX/alloc-token.cpp
index 5c9c08672e07dd..e51ed861edd9ad 100644
--- a/clang/test/CodeGenCXX/alloc-token.cpp
+++ b/clang/test/CodeGenCXX/alloc-token.cpp
@@ -171,31 +171,6 @@ PlacedNoPtr *test_placement_new_direct() {
   return new (malloc(64)) PlacedNoPtr();
 }
 
-// CHECK-LABEL: define dso_local noundef ptr @_Z24test_placement_new_localv(
-// CHECK: call noalias ptr @malloc(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDWITHPTR:![0-9]+]]
-PlacedWithPtr *test_placement_new_local() {
-  void *mem = malloc(64);
-  if (!mem)
-    return nullptr;
-  return new (mem) PlacedWithPtr();
-}
-
-// CHECK-LABEL: define dso_local noundef ptr @_Z30test_placement_new_sized_localv(
-// CHECK: call { ptr, i64 } @__size_returning_new(i64 noundef 64){{.*}} !alloc_token [[META_PLACEDNOPTR]]
-PlacedNoPtr *test_placement_new_sized_local() {
-  __sized_ptr_t res = __size_returning_new(64);
-  PlacedNoPtr *rep = new (res.p) PlacedNoPtr();
-  rep->len = res.n;
-  return rep;
-}
-
-// CHECK-LABEL: define dso_local noundef ptr @_Z29test_placement_new_sized_castv(
-// CHECK: call { ptr, i64 } @__size_returning_new_hot_cold(i64 noundef 64, i8 noundef zeroext 1){{.*}} !alloc_token [[META_PLACEDNOPTR]]
-PlacedNoPtr *test_placement_new_sized_cast() {
-  auto res = __size_returning_new_hot_cold(64, __hot_cold_t{1});
-  return new (static_cast<char *>(res.p)) 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() {
@@ -207,7 +182,7 @@ PlacedNoPtr *test_placement_new_array() {
 // 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]]
+// 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));
@@ -225,14 +200,11 @@ struct DerivedWithPtr : PlacedNoPtr {
 };
 // 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 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();
-  auto *p2 = (unsigned char *)malloc(64);
-  sink = new (p2) 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));
@@ -296,8 +268,6 @@ 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 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)
@@ -306,8 +276,6 @@ SpanWithStatic alloc_span_with_static(size_t) __attribute__((malloc_span));
 void test_placement_new_indirect() {
   Holder *h = alloc_holder(64);
   sink = new (h->p) PlacedNoPtr();
-  Holder *h2 = alloc_holder(64);
-  sink = new (&h2->p) PlacedNoPtr();
   void *mem = malloc(64);
   sink = new (&mem) unsigned char(0);
   SpanWithStatic span = alloc_span_with_static(64);



More information about the cfe-commits mailing list