[clang] Fix a crash in handling this-pointer captured in nested lambdas in field initializater. (PR #245491)

Wontae Choi via cfe-commits cfe-commits at lists.llvm.org
Tue Nov 24 17:04:05 PST 2026


https://github.com/wtchoi updated https://github.com/llvm/llvm-project/pull/245491

>From bf474df53117296c9434d6e2ee6697eea39579c9 Mon Sep 17 00:00:00 2001
From: Wontae Choi <wtchoi at google.com>
Date: Tue, 24 Nov 2026 01:09:23 +0000
Subject: [PATCH 1/3] Environment::initialize now properly handles "this"
 pointer captured by a nested lambda expression, when the lambda expression
 was apeparing in the field initializer. Consider the following example:

struct {
  int f = int f{[this]() { return [this]() { return 1; }(); }()};
}

In the above code, "this" pointer captured by the inner lambda was not
properly handled, causing null-dereference.
---
 .../FlowSensitive/DataflowEnvironment.cpp     | 22 +++++-
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 69 +++++++++++++++++++
 2 files changed, 90 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 33f2d4782db119..d6f69cf61d3f61 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -1101,6 +1101,26 @@ Environment::Environment(const Environment &Other)
       ExprToLoc(Other.ExprToLoc), ExprToVal(Other.ExprToVal),
       LocToVal(Other.LocToVal), BoolState(Other.BoolState->clone()) {}
 
+// Returns the field whose default member initializer contains the lambda with
+// closure type `Closure`, or null if there is no such field.
+//
+// `Closure` may be nested inside other lambdas within the default member
+// initializer. In that case only the outermost closure has the `FieldDecl` as
+// its lambda context declaration. So walk out through the enclosing lambdas
+// until a context declaration is found.
+static const FieldDecl *getFieldBeingInitialized(const CXXRecordDecl *Closure) {
+  while (true) {
+    assert(Closure->isLambda());
+    if (const Decl *ContextDecl = Closure->getLambdaContextDecl())
+      return dyn_cast<FieldDecl>(ContextDecl);
+    const auto *EnclosingMethod =
+        dyn_cast<CXXMethodDecl>(Closure->getDeclContext());
+    if (EnclosingMethod == nullptr || !EnclosingMethod->getParent()->isLambda())
+      return nullptr;
+    Closure = EnclosingMethod->getParent();
+  }
+}
+
 void Environment::initialize() {
   if (InitialTargetStmt == nullptr)
     return;
@@ -1148,7 +1168,7 @@ void Environment::initialize() {
             setThisPointeeStorageLocation(
                 cast<RecordStorageLocation>(createObject(ThisPointeeType)));
           } else if (auto *FieldBeingInitialized =
-                         dyn_cast<FieldDecl>(Parent->getLambdaContextDecl())) {
+                         getFieldBeingInitialized(Parent)) {
             // This is in a field initializer, rather than a method.
             const RecordDecl *RD = FieldBeingInitialized->getParent();
             const ASTContext &Ctx = RD->getASTContext();
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index 6bab26d472e66a..b9a6d7bce0b4f2 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -552,6 +552,75 @@ TEST_F(EnvironmentTest, LambdaCapturingThisInFieldInitializer) {
   ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
 }
 
+/*
+TEST_F(EnvironmentTest, NestedLambdaCapturingThisInFieldInitializer) {
+  using namespace ast_matchers;
+  std::string Code = R"cc(
+      struct S {
+      int f{[this]() { return [this]() { return 1; }(); }()};
+      };
+    )cc";
+
+  auto Unit =
+      tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results = match(cxxMethodDecl(hasName("operator()"), isDefinition(),
+                                     ofClass(cxxRecordDecl(isLambda())))
+                           .bind("method"),
+                       Context);
+
+  // Touch all methods and make sure initialization doesn't crash on any.
+  for (const auto& Node : Results) {
+    const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
+    if (Method->isDependentContext())
+      continue;
+    Environment Env(DAContext, *Method);
+    // Don't crash when initializing.
+    Env.initialize();
+    // And initialize the captured `this` pointee.
+    ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
+  }
+}
+*/
+
+TEST_F(EnvironmentTest,
+       NestedLambdaCapturingClassTemplateThisInFieldInitializer) {
+  using namespace ast_matchers;
+  std::string Code = R"cc(
+      template <class T>
+      struct S {
+        int f{[this]() { return [this]() { return 1; }(); }()};
+      };
+      S<int> s;
+    )cc";
+
+  auto Unit =
+      tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results = match(cxxMethodDecl(hasName("operator()"), isDefinition(),
+                                     ofClass(cxxRecordDecl(isLambda())))
+                           .bind("method"),
+                       Context);
+
+  // Touch all methods and make sure initialization doesn't crash on any.
+  for (const auto &Node : Results) {
+    const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
+    if (Method->isDependentContext())
+      continue;
+    Environment Env(DAContext, *Method);
+    // Don't crash when initializing.
+    Env.initialize();
+    // And initialize the captured `this` pointee.
+    ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
+  }
+}
+
 TEST_F(EnvironmentTest, ThisExprLocInNonMemberIsInitListLoc) {
   using namespace ast_matchers;
   std::string Code = R"cc(

>From fe4d4b4ab26fbaf872cbaf593dc5ce01482aff61 Mon Sep 17 00:00:00 2001
From: Wontae Choi <wtchoi at google.com>
Date: Tue, 24 Nov 2026 17:14:46 +0000
Subject: [PATCH 2/3] - Update the helper function name, and removed assertion.
 - Uncomment one test, and update all tests to check the number of matches.

---
 .../FlowSensitive/DataflowEnvironment.cpp     |  9 +++++----
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 19 ++++++++++++++-----
 2 files changed, 19 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index d6f69cf61d3f61..a52462afeb20a1 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -1108,9 +1108,9 @@ Environment::Environment(const Environment &Other)
 // initializer. In that case only the outermost closure has the `FieldDecl` as
 // its lambda context declaration. So walk out through the enclosing lambdas
 // until a context declaration is found.
-static const FieldDecl *getFieldBeingInitialized(const CXXRecordDecl *Closure) {
-  while (true) {
-    assert(Closure->isLambda());
+static const FieldDecl *
+getFieldBeingInitializedByLambda(const CXXRecordDecl *Closure) {
+  while (Closure->isLambda()) {
     if (const Decl *ContextDecl = Closure->getLambdaContextDecl())
       return dyn_cast<FieldDecl>(ContextDecl);
     const auto *EnclosingMethod =
@@ -1119,6 +1119,7 @@ static const FieldDecl *getFieldBeingInitialized(const CXXRecordDecl *Closure) {
       return nullptr;
     Closure = EnclosingMethod->getParent();
   }
+  return nullptr;
 }
 
 void Environment::initialize() {
@@ -1168,7 +1169,7 @@ void Environment::initialize() {
             setThisPointeeStorageLocation(
                 cast<RecordStorageLocation>(createObject(ThisPointeeType)));
           } else if (auto *FieldBeingInitialized =
-                         getFieldBeingInitialized(Parent)) {
+                         getFieldBeingInitializedByLambda(Parent)) {
             // This is in a field initializer, rather than a method.
             const RecordDecl *RD = FieldBeingInitialized->getParent();
             const ASTContext &Ctx = RD->getASTContext();
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index b9a6d7bce0b4f2..ee886844be74dc 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -552,7 +552,6 @@ TEST_F(EnvironmentTest, LambdaCapturingThisInFieldInitializer) {
   ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
 }
 
-/*
 TEST_F(EnvironmentTest, NestedLambdaCapturingThisInFieldInitializer) {
   using namespace ast_matchers;
   std::string Code = R"cc(
@@ -572,8 +571,11 @@ TEST_F(EnvironmentTest, NestedLambdaCapturingThisInFieldInitializer) {
                            .bind("method"),
                        Context);
 
-  // Touch all methods and make sure initialization doesn't crash on any.
-  for (const auto& Node : Results) {
+  // We will get 4 matches (2 matches for the inner lambda, and 2 matches for
+  // the outer lambda). Make sure environment initialization doesn't fail on
+  // them.
+  int LambdaCount = 0;
+  for (const auto &Node : Results) {
     const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
     if (Method->isDependentContext())
       continue;
@@ -582,9 +584,10 @@ TEST_F(EnvironmentTest, NestedLambdaCapturingThisInFieldInitializer) {
     Env.initialize();
     // And initialize the captured `this` pointee.
     ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
+    LambdaCount++;
   }
+  ASSERT_EQ(LambdaCount, 4);
 }
-*/
 
 TEST_F(EnvironmentTest,
        NestedLambdaCapturingClassTemplateThisInFieldInitializer) {
@@ -608,7 +611,11 @@ TEST_F(EnvironmentTest,
                            .bind("method"),
                        Context);
 
-  // Touch all methods and make sure initialization doesn't crash on any.
+  // We will get 8 matches (2 for the inner lambda in the template and 2 for the
+  // outer lambda in the template. Similarly, we will get 2+2 matches for the
+  // lambdas in the template instantiation). Make sure environment
+  // initialization doesn't fail on them.
+  int LambdaCount = 0;
   for (const auto &Node : Results) {
     const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
     if (Method->isDependentContext())
@@ -618,7 +625,9 @@ TEST_F(EnvironmentTest,
     Env.initialize();
     // And initialize the captured `this` pointee.
     ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
+    LambdaCount++;
   }
+  ASSERT_EQ(LambdaCount, 8);
 }
 
 TEST_F(EnvironmentTest, ThisExprLocInNonMemberIsInitListLoc) {

>From f101e16454056617006e671df32525885be0b09e Mon Sep 17 00:00:00 2001
From: Wontae Choi <wtchoi at google.com>
Date: Wed, 25 Nov 2026 00:55:11 +0000
Subject: [PATCH 3/3] - Remove unnecessary condition in the helper function -
 Remove unnecessary conditional in one test. - Replace isDependentContext call
 to isTemplated to make it more   explicit. - Update comment in texts to hide
 some details.

---
 .../FlowSensitive/DataflowEnvironment.cpp        |  3 ++-
 .../FlowSensitive/DataflowEnvironmentTest.cpp    | 16 ++++++----------
 2 files changed, 8 insertions(+), 11 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index a52462afeb20a1..99e6af72317274 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -1115,8 +1115,9 @@ getFieldBeingInitializedByLambda(const CXXRecordDecl *Closure) {
       return dyn_cast<FieldDecl>(ContextDecl);
     const auto *EnclosingMethod =
         dyn_cast<CXXMethodDecl>(Closure->getDeclContext());
-    if (EnclosingMethod == nullptr || !EnclosingMethod->getParent()->isLambda())
+    if (EnclosingMethod == nullptr) {
       return nullptr;
+    }
     Closure = EnclosingMethod->getParent();
   }
   return nullptr;
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index ee886844be74dc..6a916ffcbb935c 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -571,14 +571,11 @@ TEST_F(EnvironmentTest, NestedLambdaCapturingThisInFieldInitializer) {
                            .bind("method"),
                        Context);
 
-  // We will get 4 matches (2 matches for the inner lambda, and 2 matches for
-  // the outer lambda). Make sure environment initialization doesn't fail on
-  // them.
+  // We will get 4 matches. Make sure environment initialization doesn't
+  // fail on them.
   int LambdaCount = 0;
   for (const auto &Node : Results) {
     const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
-    if (Method->isDependentContext())
-      continue;
     Environment Env(DAContext, *Method);
     // Don't crash when initializing.
     Env.initialize();
@@ -611,14 +608,13 @@ TEST_F(EnvironmentTest,
                            .bind("method"),
                        Context);
 
-  // We will get 8 matches (2 for the inner lambda in the template and 2 for the
-  // outer lambda in the template. Similarly, we will get 2+2 matches for the
-  // lambdas in the template instantiation). Make sure environment
-  // initialization doesn't fail on them.
+  // We will get 8 matches (excluding ones in the template). Make sure
+  // environment initialization doesn't fail on them.
   int LambdaCount = 0;
   for (const auto &Node : Results) {
     const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
-    if (Method->isDependentContext())
+    // Skip nodes in template.
+    if (Method->isTemplated())
       continue;
     Environment Env(DAContext, *Method);
     // Don't crash when initializing.



More information about the cfe-commits mailing list