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

via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 21:36:56 PST 2026


llvmorg-github-actions[bot] wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang-analysis

Author: Wontae Choi (wtchoi)

<details>
<summary>Changes</summary>

Environment.initialize() currently crashes when handling a this-pointer captured by a nested lambda expression appearing in a field initializer of a struct. Consider the following example:

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

When handling the this-pointer captured in the inner lambda, Environment.initialize() tries to get the enclosing record by calling getLambdaContext() on the lambda's Closure. However, getLambdaContext() only works for the outermost lambda. For inner lambdas, it just returns nullptr, which causes a null-dereference.

This PR fixes that issue by introducing a helper function that finds the outermost lambda and get getLambdaContextDecl() from it.


---
Full diff: https://github.com/llvm/llvm-project/pull/245491.diff


2 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+21-1) 
- (modified) clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp (+69) 


``````````diff
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(

``````````

</details>


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


More information about the cfe-commits mailing list