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

Utkarsh Saxena via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 14 09:25:54 PST 2024


================
@@ -3229,6 +3231,52 @@ void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
         << ParamName << (FDecl != nullptr) << FDecl;
 }
 
+void Sema::checkLifetimeCaptureBy(FunctionDecl *FD, bool IsMemberFunction,
+                                  const Expr *ThisArg,
+                                  ArrayRef<const Expr *> Args) {
+  auto GetArgAt = [&](int Idx) -> Expr * {
+    if (Idx == LifetimeCaptureByAttr::GLOBAL ||
+        Idx == LifetimeCaptureByAttr::UNKNOWN)
+      return nullptr;
+    if (IsMemberFunction && Idx == 0)
+      return const_cast<Expr *>(ThisArg);
+    return const_cast<Expr *>(Args[Idx - int(IsMemberFunction)]);
+  };
+  for (unsigned I = 0; I < FD->getNumParams(); ++I) {
+    auto *CapturedByAttr =
+        FD->getParamDecl(I)->getAttr<LifetimeCaptureByAttr>();
+    if (!CapturedByAttr)
+      continue;
+    for (int CapturingParamIdx : CapturedByAttr->params()) {
+      Expr *Capturing = GetArgAt(CapturingParamIdx);
+      Expr *Captured = GetArgAt(I + IsMemberFunction);
+      CapturingEntity CE{Capturing};
+      // Ensure that 'Captured' outlives the 'Capturing' entity.
+      checkExprLifetime(*this, CE, Captured);
+    }
+  }
+  // Check when the 'this' object is captured.
+  if (IsMemberFunction) {
+    TypeSourceInfo *TSI = FD->getTypeSourceInfo();
+    if (!TSI)
+      return;
+    AttributedTypeLoc ATL;
----------------
usx95 wrote:

You could combine the two loop variables into one
```cpp
    for (AttributedTypeLoc ATL =
             TSI->getTypeLoc().getAsAdjusted<AttributedTypeLoc>();
         ATL; ATL = ATL.getModifiedLoc().getAsAdjusted<AttributedTypeLoc>()) {
...
}
```
But I would keep it simpler by using two loop variables for readability. Since they are different types, both cannot be part of for expression.

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


More information about the cfe-commits mailing list