[clang] [clang] Implement lifetime analysis for lifetime_capture_by(X) (PR #115921)

Haojian Wu via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 14 13:26:11 PST 2024


================
@@ -1420,9 +1446,18 @@ static void checkExprLifetimeImpl(Sema &SemaRef,
              ? IndirectLocalPathEntry::LifetimeBoundCall
              : IndirectLocalPathEntry::GslPointerAssignment,
          Init});
+  } else if (LK == LK_LifetimeCapture) {
+    Path.push_back({IndirectLocalPathEntry::LifetimeCapture, Init});
+    if (isRecordWithAttr<PointerAttr>(Init->getType()))
----------------
hokein wrote:

 Some interesting cases to consider:

```cpp
void capture1(std::string_view s [[clang::lifetime_capture_by(x)]], vector<std::string_view>& x);

// Intended to capture the "string_view" itself
void capture2_1(const std::string_view& s [[clang::lifetime_capture_by(x)]], vector<std::string_view*>& x);
// Intended to capture the pointee of the "string_view"
void capture2_2(const std::string_view& s [[clang::lifetime_capture_by(x)]], vector<std::string_view>& x);

void test1() {
   capture1(std::string(), x1); // should warn
   capture1(std::string_view(), x1); // should not warn
  
   capture2_1(std::string_view(), x2); // expected to warn
   capture2_1(std::string(), x2); // expected to warn
   
   capture2_2(std::string_view(), x3); // ?? should probably not warn
   capture2_2(std::string(), x3); // expected to warn
}
```

If I understand correctly, the current implementation handles the `capture1` case appropriately. However, for the `capture2` cases, it treats them similarly to `capture2_2`, which appears inconsistent with the `lifetime_capture_by` [documentation](https://clang.llvm.org/docs/AttributeReference.html#lifetime-capture-by). According to the documentation, for a reference type, we should consider the referenced type (`std::string_view` itself in this case).

Furthermore, the implementation seem to rely on the `gsl::pointer` annotation, the documentation does not mention GSL pointer types. E.g.

```cpp
// `my_view` is not annotated with gsl pointer.
void capture3(my_view s [[clang::lifetime_capture_by(x)]], vector<my_view>& x);
```

In this situation, I think no diagnostic should be triggered, this means that we might need to update the documentation accordingly.

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


More information about the cfe-commits mailing list