[clang] [LifetimeSafety] Warn on inapplicable [[clang::lifetimebound]] parameters (PR #201101)
Utkarsh Saxena via cfe-commits
cfe-commits at lists.llvm.org
Wed Jun 10 05:11:19 PDT 2026
================
@@ -467,6 +468,21 @@ class LifetimeChecker {
}
}
+ void reportInapplicableLifetimebound() {
+ const auto *FDef = dyn_cast<FunctionDecl>(FD);
+ if (!FDef)
+ return;
+
+ if (FDef->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate ||
+ FDef->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
+ return;
+
+ for (const auto &PVD : FDef->parameters())
+ if (PVD->hasAttr<LifetimeBoundAttr>() &&
+ !FactMgr.getOriginMgr().hasOrigins(PVD->getType()))
----------------
usx95 wrote:
`hasOrigins` is actually sensitive to the function body as it uses `LifetimeAnnotatedOriginTypes`.
So the following would not trigger for example:
```cpp
std::vector<int*> foo(const int& a [[clang::lifetimebound]]);
// wrongly annotated but not detected!
int* getFirst(std::vector<int*> a [[clang::lifetimebound]]) {
int x = 42;
// use foo.
foo(x);
return a[0];
}
```
(add this test)
It might make sense to detect these by making hasOrigins to be optionally strict and disallow special casing. The rest of the parts of hasOrigins are not context sensitive and so should be fine to use as is.
High-level suggestion:
```cpp
/// Determines whether a type can carry lifetime origins.
///
/// \param QT The type to check.
/// \param IntrinsicOnly If true, only consider types that can intrinsically
/// carry origins (pointers, references, gsl::Pointer types). If false,
/// also include types that are tracked due to context-sensitive
/// annotations (e.g., return types of [[clang::lifetimebound]] functions).
///
/// Intrinsic origin types:
/// - Pointer types (int*, void*)
/// - Reference types (int&, const T&)
/// - gsl::Pointer annotated types (std::string_view)
/// - Lambdas capturing pointer-like objects
/// - Standard callable wrappers (std::function)
///
/// Contextual origin types (excluded when IntrinsicOnly=true):
/// - Types appearing as return values of functions with
/// [[clang::lifetimebound]] parameters, stored in
/// LifetimeAnnotatedOriginTypes during function body analysis.
bool hasOrigins(QualType QT, bool IntrinsicOnly = false) const;
// In checker:
if (!FactMgr.getOriginMgr().hasOrigins(PVD->getType(), /*IntrinsicOnly=*/true))
SemaHelper->reportInapplicableLifetimebound(PVD);
```
https://github.com/llvm/llvm-project/pull/201101
More information about the cfe-commits
mailing list