[clang] [clang][Sema] Avoid accessing a dangling ExpressionEvaluationContextRecord in HandleImmediateInvocations() (PR #239922)

Nathan Ridge via cfe-commits cfe-commits at lists.llvm.org
Sat Nov 7 00:14:34 PST 2026


https://github.com/HighCommander4 created https://github.com/llvm/llvm-project/pull/239922

HandleImmediateInvocations() takes a reference to an element of the vector Sema::ExprEvalContexts, but in RemoveNestedImmediateInvocation() it performs a transform that can push new contexts and invalidate the reference.

Save the fields from the record that are needed during and after RemoveNestedImmediateInvocation(), and use the saved fields rather than the potentially-dangling reference.

Fixes https://github.com/llvm/llvm-project/issues/232062

>From 423924c31d48168aa379d4f15b5ba9fc9ffb0008 Mon Sep 17 00:00:00 2001
From: Nathan Ridge <zeratul976 at hotmail.com>
Date: Thu, 5 Nov 2026 04:13:56 -0500
Subject: [PATCH] [clang][Sema] Avoid accessing a dangling
 ExpressionEvaluationContextRecord in HandleImmediateInvocations()

HandleImmediateInvocations() takes a reference to an element of the
vector Sema::ExprEvalContexts, but in RemoveNestedImmediateInvocation()
it performs a transform that can push new contexts and invalidate the
reference.

Save the fields from the record that are needed during and after
RemoveNestedImmediateInvocation(), and use the saved fields rather
than the potentially-dangling reference.

Fixes https://github.com/llvm/llvm-project/issues/232062
---
 clang/lib/Sema/SemaExpr.cpp                   | 75 ++++++++++++-------
 ...ediate-invocation-eval-context-realloc.cpp | 64 ++++++++++++++++
 2 files changed, 111 insertions(+), 28 deletions(-)
 create mode 100644 clang/test/PCH/immediate-invocation-eval-context-realloc.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 9b3384cdbdac8c..defa4b8975a83f 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -18722,8 +18722,12 @@ static void EvaluateAndDiagnoseImmediateInvocation(
   CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
 }
 
+/// \p DRSet and \p IISet must not be part of an element of
+/// Sema::ExprEvalContexts: the transform below can push evaluation contexts,
+/// which may reallocate ExprEvalContexts.
 static void RemoveNestedImmediateInvocation(
-    Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
+    Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet,
+    SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet,
     SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
   struct ComplexRemove : TreeTransform<ComplexRemove> {
     using Base = TreeTransform<ComplexRemove>;
@@ -18812,8 +18816,7 @@ static void RemoveNestedImmediateInvocation(
       return Res;
     }
     bool AllowSkippingFirstCXXConstructExpr = true;
-  } Transformer(SemaRef, Rec.ReferenceToConsteval,
-                Rec.ImmediateInvocationCandidates, It);
+  } Transformer(SemaRef, DRSet, IISet, It);
 
   /// CXXConstructExpr with a single argument are getting skipped by
   /// TreeTransform in some situtation because they could be implicit. This
@@ -18861,13 +18864,23 @@ HandleImmediateInvocations(Sema &SemaRef,
     }
   }
 
+  // The tree transform and the constant evaluation below can push evaluation
+  // contexts, which may reallocate ExprEvalContexts and leave Rec dangling.
+  // Take what we need from Rec now, and don't use it after this point.
+  SmallVector<Sema::ImmediateInvocationCandidate, 4> Candidates =
+      std::move(Rec.ImmediateInvocationCandidates);
+  llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval =
+      std::move(Rec.ReferenceToConsteval);
+  const Sema::ExpressionEvaluationContext RecContext = Rec.Context;
+  const bool InImmediateEscalatingFunctionContext =
+      Rec.InImmediateEscalatingFunctionContext;
+
   /// When we have more than 1 ImmediateInvocationCandidates or previously
   /// failed immediate invocations, we need to check for nested
   /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
   /// Otherwise we only need to remove ReferenceToConsteval in the immediate
   /// invocation.
-  if (Rec.ImmediateInvocationCandidates.size() > 1 ||
-      !SemaRef.FailedImmediateInvocations.empty()) {
+  if (Candidates.size() > 1 || !SemaRef.FailedImmediateInvocations.empty()) {
 
     /// Prevent sema calls during the tree transform from adding pointers that
     /// are already in the sets.
@@ -18877,12 +18890,11 @@ HandleImmediateInvocations(Sema &SemaRef,
     /// Prevent diagnostic during tree transfrom as they are duplicates
     Sema::TentativeAnalysisScope DisableDiag(SemaRef);
 
-    for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
-         It != Rec.ImmediateInvocationCandidates.rend(); It++)
+    for (auto It = Candidates.rbegin(); It != Candidates.rend(); It++)
       if (!It->getInt())
-        RemoveNestedImmediateInvocation(SemaRef, Rec, It);
-  } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
-             Rec.ReferenceToConsteval.size()) {
+        RemoveNestedImmediateInvocation(SemaRef, ReferenceToConsteval,
+                                        Candidates, It);
+  } else if (Candidates.size() == 1 && ReferenceToConsteval.size()) {
     struct SimpleRemove : DynamicRecursiveASTVisitor {
       llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
       SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
@@ -18890,14 +18902,13 @@ HandleImmediateInvocations(Sema &SemaRef,
         DRSet.erase(E);
         return DRSet.size();
       }
-    } Visitor(Rec.ReferenceToConsteval);
-    Visitor.TraverseStmt(
-        Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
+    } Visitor(ReferenceToConsteval);
+    Visitor.TraverseStmt(Candidates.front().getPointer()->getSubExpr());
   }
-  for (auto CE : Rec.ImmediateInvocationCandidates)
+  for (auto CE : Candidates)
     if (!CE.getInt())
       EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
-  for (auto *DR : Rec.ReferenceToConsteval) {
+  for (auto *DR : ReferenceToConsteval) {
     // If the expression is immediate escalating, it is not an error;
     // The outer context itself becomes immediate and further errors,
     // if any, will be handled by DiagnoseImmediateEscalatingReason.
@@ -18916,14 +18927,13 @@ HandleImmediateInvocations(Sema &SemaRef,
     // that is not a subexpression of an immediate invocation.
     bool ImmediateEscalating = false;
     bool IsPotentiallyEvaluated =
-        Rec.Context ==
-            Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
-        Rec.Context ==
+        RecContext == Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
+        RecContext ==
             Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
     if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
-      ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
+      ImmediateEscalating = InImmediateEscalatingFunctionContext;
 
-    if (!Rec.InImmediateEscalatingFunctionContext ||
+    if (!InImmediateEscalatingFunctionContext ||
         (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
       SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
           << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
@@ -18986,12 +18996,20 @@ void Sema::PopExpressionEvaluationContext() {
   }
 
   WarnOnPendingNoDerefs(Rec);
+
+  [[maybe_unused]] size_t Depth = ExprEvalContexts.size();
   HandleImmediateInvocations(*this, Rec);
+  // HandleImmediateInvocations can push and pop evaluation contexts, which may
+  // reallocate ExprEvalContexts, so Rec may now be dangling. Since everything
+  // pushed was popped again, the innermost element is still the same context.
+  assert(ExprEvalContexts.size() == Depth &&
+         "HandleImmediateInvocations left evaluation contexts pushed");
+  ExpressionEvaluationContextRecord &CurRec = ExprEvalContexts.back();
 
   // Warn on any volatile-qualified simple-assignments that are not discarded-
   // value expressions nor unevaluated operands (those cases get removed from
   // this list by CheckUnusedVolatileAssignment).
-  for (auto *BO : Rec.VolatileAssignmentLHSs)
+  for (auto *BO : CurRec.VolatileAssignmentLHSs)
     Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
         << BO->getType();
 
@@ -18999,16 +19017,17 @@ void Sema::PopExpressionEvaluationContext() {
   // temporaries that we may have created as part of the evaluation of
   // the expression in that context: they aren't relevant because they
   // will never be constructed.
-  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
-    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
+  if (CurRec.isUnevaluated() || CurRec.isConstantEvaluated()) {
+    ExprCleanupObjects.erase(ExprCleanupObjects.begin() +
+                                 CurRec.NumCleanupObjects,
                              ExprCleanupObjects.end());
-    Cleanup = Rec.ParentCleanup;
+    Cleanup = CurRec.ParentCleanup;
     CleanupVarDeclMarking();
-    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
-  // Otherwise, merge the contexts together.
+    std::swap(MaybeODRUseExprs, CurRec.SavedMaybeODRUseExprs);
+    // Otherwise, merge the contexts together.
   } else {
-    Cleanup.mergeFrom(Rec.ParentCleanup);
-    MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
+    Cleanup.mergeFrom(CurRec.ParentCleanup);
+    MaybeODRUseExprs.insert_range(CurRec.SavedMaybeODRUseExprs);
   }
 
   DiagnoseMisalignedMembers();
diff --git a/clang/test/PCH/immediate-invocation-eval-context-realloc.cpp b/clang/test/PCH/immediate-invocation-eval-context-realloc.cpp
new file mode 100644
index 00000000000000..7512b8cdefaa16
--- /dev/null
+++ b/clang/test/PCH/immediate-invocation-eval-context-realloc.cpp
@@ -0,0 +1,64 @@
+// RUN: %clang_cc1 -std=c++20 -emit-pch -o %t %s
+// RUN: %clang_cc1 -std=c++20 -include-pch %t -verify %s
+// RUN: %clang_cc1 -std=c++20 -include %s -verify %s
+
+// expected-no-diagnostics
+
+// GH232062: when an expression contains nested immediate invocations,
+// HandleImmediateInvocations runs a TreeTransform (ComplexRemove) over it while
+// holding references into Sema::ExprEvalContexts. Rebuilding the call to
+// format() during that transform re-checks the constraint on AsStringView,
+// which pushes enough nested evaluation contexts (about 3 per level of the
+// C0..C9 chain) to reallocate ExprEvalContexts, leaving the references
+// dangling.
+//
+// The PCH matters: in the main file, Sema starts with a fresh ExprEvalContexts
+// (8 elements inline), and the rebuild repeats the full constraint check. The
+// static_assert on P2 in the main file first moves the vector to a heap buffer
+// of 17 elements, so that the reallocation during the rebuild (to more than 17
+// elements) frees the memory the dangling references point into. Without that,
+// the stale references would point into the never-freed inline storage, and
+// the bug would go unnoticed even under ASan.
+//
+// The depths are chosen with margin: in the main file, the static_assert peaks
+// at about 11 contexts (between 9 and 17, so the vector moves to a 17-element
+// heap buffer), and the rebuild peaks at about 32 (more than 17).
+//
+// Without a fix, the freed buffer gets reused during the rebuild in practice,
+// and the compile crashes. Strictly, that depends on the allocator; ASan
+// detects the use-after-free directly.
+
+#ifndef HEADER_INCLUDED
+#define HEADER_INCLUDED
+
+template <class T> concept C0 = requires(T &t) { t = t; };
+template <class T> concept C1 = requires { requires C0<T>; };
+template <class T> concept C2 = requires { requires C1<T>; };
+template <class T> concept C3 = requires { requires C2<T>; };
+template <class T> concept C4 = requires { requires C3<T>; };
+template <class T> concept C5 = requires { requires C4<T>; };
+template <class T> concept C6 = requires { requires C5<T>; };
+template <class T> concept C7 = requires { requires C6<T>; };
+template <class T> concept C8 = requires { requires C7<T>; };
+template <class T> concept C9 = requires { requires C8<T>; };
+
+template <class> struct FormatString {
+  consteval FormatString(int) {}
+};
+consteval int fmt(int) { return 0; }
+
+template <C9> using AsStringView = int;
+template <class S> void format(FormatString<AsStringView<S>>, S);
+
+void emplace_test(auto) { format(fmt(0), 0); }
+
+#else
+
+template <class T> concept P0 = requires(T &t) { t = t; };
+template <class T> concept P1 = requires { requires P0<T>; };
+template <class T> concept P2 = requires { requires P1<T>; };
+static_assert(P2<long>);
+
+void f() { emplace_test(0); }
+
+#endif



More information about the cfe-commits mailing list