Initial implementation of the experimental C++ Lifetime Safety Analysis (-Wexperimental-lifetime-safety) has just landed in Clang

18 points by aapoalas


An initial implementation of the experimental C++ Lifetime Safety Analysis (-Wexperimental-lifetime-safety) has just landed in Clang. The work was originally announced in the linked post with the following status:

Lifetime Analysis: Current Status

For those not already familiar, we’re working on a new lifetime analysis in Clang to catch issues like use-after-scope or returning pointers to stack memory. The analysis is alias-based and draws inspiration from Rust’s borrow checker (specifically, Polonius). More details in the RFC: https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291

The initial implementation targets intra-procedural analysis for C++ raw pointers. This keeps the surface area small while we iterate. Over time, we aim to enable this analysis by default in Clang, with both “permissive” and “strict” modes to balance noise and coverage.

The landed PR is this:

Example: [LifetimeSafety] Introduce intra-procedural analysis in Clang

Key Components

andyc

I didn’t read that carefully, but what I was interested in is if you need more annotations, i.e. if you are “changing the language you’re writing in”

https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291

That’s necessary if you want to be 100% correct, but it looks like this is aimed at issuing warnings, with tradeoffs for false negatives and false positives:

The analysis offers different strictness levels (-Wdangling-safety and -Wdangling-safety-permissive). This configuration allows users to control the sensitivity of the warnings issued, managing the trade-off between finding more potential bugs and reducing false positive reports (as detailed in the Permissive vs. Strict Modes section).

But there are also hints at new language annotations:

Future enhancements

Annotation Suggestions: Diagnostics suggesting the addition of [[clang::lifetimebound]] where the analysis detects lifetimes escaping functions, helping users improve function contracts.

Annotation Verification: Diagnostics verifying that function implementations adhere to their declared [[clang::lifetimebound]] contracts, catching mismatches between declaration and behavior.