[clang] [LifetimeSafety] resolved lifetimeBound violation in constructor (PR #204797)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Jun 19 04:07:22 PDT 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-temporal-safety
Author: Jiaqi He (heturing)
<details>
<summary>Changes</summary>
Fix https://github.com/llvm/llvm-project/issues/203839.
Constructor body does not produce `ReturnEscapeFact`, but a constructor parameter marked [[clang::lifetimebound]] may still be valid if it escapes into a field of the constructed object.
Update the `LifetimeBound` logic to accept `FieldEscapeFact` for constructors, and add a test case for this pattern.
---
Full diff: https://github.com/llvm/llvm-project/pull/204797.diff
2 Files Affected:
- (modified) clang/lib/Analysis/LifetimeSafety/Checker.cpp (+4-1)
- (added) clang/test/Sema/LifetimeSafety/lifetimebound.cpp (+35)
``````````diff
diff --git a/clang/lib/Analysis/LifetimeSafety/Checker.cpp b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
index d41d6f43f837b..595f9a1d32eba 100644
--- a/clang/lib/Analysis/LifetimeSafety/Checker.cpp
+++ b/clang/lib/Analysis/LifetimeSafety/Checker.cpp
@@ -135,7 +135,10 @@ class LifetimeChecker {
return;
if (PVD->hasAttr<LifetimeBoundAttr>()) {
// Track that this lifetimebound parameter correctly escapes.
- if (isa<ReturnEscapeFact>(OEF))
+ bool isVerifiedEscape =
+ isa<ReturnEscapeFact>(OEF) ||
+ (isa<FieldEscapeFact>(OEF) && isa<CXXConstructorDecl>(FD));
+ if (isVerifiedEscape)
VerifiedLiftimeboundEscapes.insert(PVD);
} else {
// Otherwise, suggest lifetimebound for parameter escaping through
diff --git a/clang/test/Sema/LifetimeSafety/lifetimebound.cpp b/clang/test/Sema/LifetimeSafety/lifetimebound.cpp
new file mode 100644
index 0000000000000..a5e26b5bdadf2
--- /dev/null
+++ b/clang/test/Sema/LifetimeSafety/lifetimebound.cpp
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -fsyntax-only -Wlifetime-safety-all -verify %s
+
+
+using size_t = decltype(sizeof(0));
+extern "C" size_t strlen(const char *);
+
+#define LIFETIMEBOUND [[clang::lifetimebound]]
+
+struct View
+{
+ View(const char* data LIFETIMEBOUND)
+ : mData(data)
+ , mSize(strlen(data))
+ {}
+
+ const char* data() const {
+ return mData;
+ }
+
+ size_t size() const {
+ return mSize;
+ }
+
+private:
+ const char* mData;
+ size_t mSize;
+};
+
+void test() {
+ char *c = new char[5]; //expected-warning {{allocated object does not live long enough}}
+ View v(c);
+ delete[] c; // expected-note {{freed here}}
+ const char *c1 = v.data(); // expected-note {{later used here}}
+ return;
+}
\ No newline at end of file
``````````
</details>
https://github.com/llvm/llvm-project/pull/204797
More information about the cfe-commits
mailing list