[clang] [LifetimeSafety] Add details for `-Wlifetime-safety-return-stack-addr` diagnostic (PR #199432)

Utkarsh Saxena via cfe-commits cfe-commits at lists.llvm.org
Mon May 25 06:40:31 PDT 2026


================
@@ -396,6 +400,21 @@ class LifetimeSafetySemaHelperImpl : public LifetimeSafetySemaHelper {
   }
 
 private:
+  static std::string getLifetimeDiagSubject(const internal::Loan *L) {
+    if (L->getAccessPath().getAsMaterializeTemporaryExpr())
+      return "local temporary";
+
+    const auto *DRE = dyn_cast<DeclRefExpr>(L->getIssuingExpr());
+    assert(DRE && "expected lifetime diagnostic loan issued by a DeclRefExpr");
+
+    const ValueDecl *VD = DRE->getDecl();
+    std::string Subject =
+        isa<ParmVarDecl>(VD) ? "parameter '" : "local variable '";
+    Subject += VD->getNameAsString();
+    Subject += "'";
+    return Subject;
----------------
usx95 wrote:

FWIW:
We could introduce 2 overloads for this, one for expr and other for decl.

```cpp
std::string getDiagSubjectDescription(const ValueDecl *VD) {
  std::string Res;
  llvm::raw_string_ostream OS(Res);
  OS << (isa<ParmVarDecl>(VD) ? "parameter" : "local variable");
  OS << " '";
  VD->getNameForDiagnostic(OS, S.getPrintingPolicy(), /*Qualified=*/false);
  OS << "'";
  return Res;
}

std::string getDiagSubjectDescription(const Expr *E) {
  if (isa<MaterializeTemporaryExpr>(E))
    return "local temporary";

  if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
    return getDiagSubjectDescription(DRE->getDecl());
  // todo handle others...
  return "";
}
```

The caller atm can just use `getDiagSubjectDescription(L->getIssuingExpr())`.

Also if there is no need for `AccessPath`, we can postpone exposing loans here until there is need. I suspect other kind of loans might need this in future, like placeholder, fields, etc, which will useful.


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


More information about the cfe-commits mailing list