xref: /llvm-project/clang/test/SemaCXX/attr-lifetimebound.cpp (revision 4cc9bf149f07edec5ea910af8b3ead17ae8b29b7)
1 // RUN: %clang_cc1 -std=c++23 -verify %s
2 
3 namespace usage_invalid {
4   void void_return(int &param [[clang::lifetimebound]]); // expected-error {{'lifetimebound' attribute cannot be applied to a parameter of a function that returns void; did you mean 'lifetime_capture_by(X)'}}
5 
6   int *not_class_member() [[clang::lifetimebound]]; // expected-error {{non-member function has no implicit object parameter}}
7   struct A {
8     A() [[clang::lifetimebound]]; // expected-error {{cannot be applied to a constructor}}
9     ~A() [[clang::lifetimebound]]; // expected-error {{cannot be applied to a destructor}}
10     static int *static_class_member() [[clang::lifetimebound]]; // expected-error {{static member function has no implicit object parameter}}
11     int *explicit_object(this A&) [[clang::lifetimebound]]; // expected-error {{explicit object member function has no implicit object parameter}}
12     int attr_on_var [[clang::lifetimebound]]; // expected-error {{only applies to parameters and implicit object parameters}}
13     int [[clang::lifetimebound]] attr_on_int; // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
14     int * [[clang::lifetimebound]] attr_on_int_ptr; // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
15     int * [[clang::lifetimebound]] * attr_on_int_ptr_ptr; // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
16     int (* [[clang::lifetimebound]] attr_on_func_ptr)(); // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
17     void void_return_member() [[clang::lifetimebound]]; // expected-error {{'lifetimebound' attribute cannot be applied to an implicit object parameter of a function that returns void; did you mean 'lifetime_capture_by(X)'}}
18   };
19   int *attr_with_param(int &param [[clang::lifetimebound(42)]]); // expected-error {{takes no arguments}}
20 
21   void attr_on_ptr_arg(int * [[clang::lifetimebound]] ptr); // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
22   static_assert((int [[clang::lifetimebound]]) 12); // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
23   int* attr_on_unnamed_arg(const int& [[clang::lifetimebound]]); // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
24   template <typename T>
25   int* attr_on_template_ptr_arg(T * [[clang::lifetimebound]] ptr); // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
26 
27   int (*func_ptr)(int) [[clang::lifetimebound]]; // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
28   int (*(*func_ptr_ptr)(int) [[clang::lifetimebound]])(int); // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
29   struct X {};
30   int (X::*member_func_ptr)(int) [[clang::lifetimebound]]; // expected-error {{'lifetimebound' attribute only applies to parameters and implicit object parameters}}
31 }
32 
33 namespace usage_ok {
34   struct IntRef { int *target; };
35 
36   const int &crefparam(const int &param); // Omitted in first decl
37   const int &crefparam(const int &param); // Omitted in second decl
38   const int &crefparam(const int &param [[clang::lifetimebound]]); // Add LB
39   const int &crefparam(const int &param) { return param; } // Omit in impl
40   int &refparam(int &param [[clang::lifetimebound]]);
41   int &classparam(IntRef param [[clang::lifetimebound]]);
42 
43   // Do not diagnose non-void return types; they can still be lifetime-bound.
44   long long ptrintcast(int &param [[clang::lifetimebound]]) {
45     return (long long)&param;
46   }
47   // Likewise.
48   int &intptrcast(long long param [[clang::lifetimebound]]) {
49     return *(int*)param;
50   }
51 
52   template <class T, class R = void> R dependent_void(const T& t [[clang::lifetimebound]]);
53   void dependent_void_instantiation() {
54     dependent_void<int>(1); // OK: Returns void.
55     int x = dependent_void<int, int>(1); // expected-warning {{temporary whose address is used as value of local variable 'x' will be destroyed at the end of the full-expression}}
56     dependent_void<int, int>(1); // OK: Returns an unused value.
57   }
58 
59   struct A {
60     A();
61     A(int);
62     int *class_member() [[clang::lifetimebound]];
63     operator int*() [[clang::lifetimebound]];
64   };
65 
66   int *p = A().class_member(); // expected-warning {{temporary whose address is used as value of local variable 'p' will be destroyed at the end of the full-expression}}
67   int *q = A(); // expected-warning {{temporary whose address is used as value of local variable 'q' will be destroyed at the end of the full-expression}}
68   int *r = A(1); // expected-warning {{temporary whose address is used as value of local variable 'r' will be destroyed at the end of the full-expression}}
69   const int& s = crefparam(2); // expected-warning {{temporary bound to local reference 's' will be destroyed at the end of the full-expression}}
70 
71   void test_assignment() {
72     p = A().class_member(); // expected-warning {{object backing the pointer p will be destroyed at the end of the full-expression}}
73     p = {A().class_member()}; // expected-warning {{object backing the pointer p will be destroyed at the end of the full-expression}}
74     q = A(); // expected-warning {{object backing the pointer q will be destroyed at the end of the full-expression}}
75     r = A(1); // expected-warning {{object backing the pointer r will be destroyed at the end of the full-expression}}
76   }
77 
78   struct FieldCheck {
79     struct Set {
80       int a;
81     };
82     struct Pair {
83       const int& a;
84       int b;
85       Set c;
86       int * d;
87     };
88     Pair p;
89     FieldCheck(const int& a): p(a){}
90     Pair& getR() [[clang::lifetimebound]] { return p; }
91     Pair* getP() [[clang::lifetimebound]] { return &p; }
92     Pair* getNoLB() { return &p; }
93   };
94   void test_field_access() {
95     int x = 0;
96     const int& a = FieldCheck{x}.getR().a;
97     const int& b = FieldCheck{x}.getP()->b;   // expected-warning {{temporary bound to local reference 'b' will be destroyed at the end of the full-expression}}
98     const int& c = FieldCheck{x}.getP()->c.a; // expected-warning {{temporary bound to local reference 'c' will be destroyed at the end of the full-expression}}
99     const int& d = FieldCheck{x}.getNoLB()->c.a;
100     const int* e = FieldCheck{x}.getR().d;
101   }
102 }
103 
104 namespace std {
105   using size_t = __SIZE_TYPE__;
106   template<typename T>
107   struct basic_string {
108     basic_string();
109     basic_string(const T*);
110 
111     char &operator[](size_t) const [[clang::lifetimebound]];
112   };
113   using string =  basic_string<char>;
114   string operator""s(const char *, size_t); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved}}
115 
116   template<typename T>
117   struct basic_string_view {
118     basic_string_view();
119     basic_string_view(const T *p);
120     basic_string_view(const string &s [[clang::lifetimebound]]);
121   };
122   using string_view = basic_string_view<char>;
123   string_view operator""sv(const char *, size_t); // expected-warning {{user-defined literal suffixes not starting with '_' are reserved}}
124 
125   struct vector {
126     int *data();
127     size_t size();
128   };
129 
130   template<typename K, typename V> struct map {};
131 }
132 
133 using std::operator""s;
134 using std::operator""sv;
135 
136 namespace default_args {
137   using IntArray = int[];
138   const int *defaultparam1(const int &def1 [[clang::lifetimebound]] = 0); // #def1
139   const int &defaultparam_array([[clang::lifetimebound]] const int *p = IntArray{1, 2, 3}); // #def2
140   struct A {
141     A(const char *, const int &def3 [[clang::lifetimebound]] = 0); // #def3
142   };
143   const int &defaultparam2(const int &def4 [[clang::lifetimebound]] = 0); // #def4
144   const int &defaultparam3(const int &def5 [[clang::lifetimebound]] = defaultparam2(), const int &def6 [[clang::lifetimebound]] = 0); // #def5 #def6
145   std::string_view defaultparam4(std::string_view s [[clang::lifetimebound]] = std::string()); // #def7
146 
147   const int *test_default_args() {
148     const int *c = defaultparam1(); // expected-warning {{temporary whose address is used as value of local variable 'c' will be destroyed at the end of the full-expression}} expected-note@#def1 {{initializing parameter 'def1' with default argument}}
149     A a = A(""); // expected-warning {{temporary whose address is used as value of local variable 'a' will be destroyed at the end of the full-expression}} expected-note@#def3 {{initializing parameter 'def3' with default argument}}
150     const int &s = defaultparam2(); // expected-warning {{temporary bound to local reference 's' will be destroyed at the end of the full-expression}} expected-note@#def4 {{initializing parameter 'def4' with default argument}}
151     const int &t = defaultparam3(); // expected-warning {{temporary bound to local reference 't' will be destroyed at the end of the full-expression}} expected-note@#def4 {{initializing parameter 'def4' with default argument}} expected-note@#def5 {{initializing parameter 'def5' with default argument}} expected-warning {{temporary bound to local reference 't' will be destroyed at the end of the full-expression}} expected-note@#def6 {{initializing parameter 'def6' with default argument}}
152     const int &u = defaultparam_array(); // expected-warning {{temporary bound to local reference 'u' will be destroyed at the end of the full-expression}} expected-note@#def2 {{initializing parameter 'p' with default argument}}
153     int local;
154     const int &v = defaultparam2(local); // no warning
155     const int &w = defaultparam2(1); // expected-warning {{temporary bound to local reference 'w' will be destroyed at the end of the full-expression}}
156     if (false) {
157       return &defaultparam2();  // expected-warning {{returning address of local temporary object}}
158     }
159     if (false) {
160       return &defaultparam2(0);  // expected-warning {{returning address of local temporary object}} expected-note@#def4 {{initializing parameter 'def4' with default argument}}
161     }
162     std::string_view sv = defaultparam4(); // expected-warning {{temporary whose address is used as value of local variable 'sv' will be destroyed at the end of the full-expression}} expected-note@#def7 {{initializing parameter 's' with default argument}}
163     return nullptr;
164   }
165 } // namespace default_args
166 
167 namespace p0936r0_examples {
168   std::string_view s = "foo"s; // expected-warning {{temporary}}
169 
170   std::string operator+(std::string_view s1, std::string_view s2);
171   void f() {
172     std::string_view sv = "hi";
173     std::string_view sv2 = sv + sv; // expected-warning {{temporary}}
174     sv2 = sv + sv; // expected-warning {{object backing the pointer}}
175   }
176 
177   struct X { int a, b; };
178   const int &f(const X &x [[clang::lifetimebound]]) { return x.a; }
179   const int &r = f(X()); // expected-warning {{temporary}}
180 
181   char &c = std::string("hello my pretty long strong")[0]; // expected-warning {{temporary}}
182 
183   struct reversed_range {
184     int *begin();
185     int *end();
186     int *p;
187     std::size_t n;
188   };
189   template <typename R> reversed_range reversed(R &&r [[clang::lifetimebound]]) {
190     return reversed_range{r.data(), r.size()};
191   }
192 
193   std::vector make_vector();
194   void use_reversed_range() {
195     // FIXME: Don't expose the name of the internal range variable.
196     for (auto x : reversed(make_vector())) {} // expected-warning {{temporary implicitly bound to local reference will be destroyed at the end of the full-expression}}
197   }
198 
199   template <typename K, typename V>
200   const V &findOrDefault(const std::map<K, V> &m [[clang::lifetimebound]],
201                          const K &key,
202                          const V &defvalue [[clang::lifetimebound]]);
203 
204   // FIXME: Maybe weaken the wording here: "local reference 'v' could bind to temporary that will be destroyed at end of full-expression"?
205   std::map<std::string, std::string> m;
206   const std::string &v = findOrDefault(m, "foo"s, "bar"s); // expected-warning {{temporary bound to local reference 'v'}}
207 }
208 
209 // definitions for std::move, std::forward et al.
210 namespace std {
211 inline namespace foo {
212 
213 template <class T> struct remove_reference {
214     typedef T type;
215 };
216 template <class T> struct remove_reference<T &> {
217     typedef T type;
218 };
219 template <class T> struct remove_reference<T &&> {
220     typedef T type;
221 };
222 
223 template <class T> constexpr typename remove_reference<T>::type &&move(T &&t) {
224     return static_cast<typename remove_reference<T>::type>(t);
225 }
226 
227 template <class T>
228 constexpr T &&forward(typename remove_reference<T>::type &t) {
229     return static_cast<T &&>(t);
230 }
231 
232 template <class T>
233 constexpr T &&forward(typename remove_reference<T>::type &&t) {
234     return static_cast<T &&>(t);
235 }
236 
237 template <class T> constexpr const T &as_const(T &x) { return x; }
238 
239 template <class T, bool RValueRef> struct PickRef {
240     using type = typename remove_reference<T>::type &;
241 };
242 template <class T> struct PickRef<T, true> {
243     using type = typename remove_reference<T>::type &&;
244 };
245 
246 template <class T> struct is_lvalue_reference {
247     static constexpr bool value = false;
248 };
249 
250 template <class T> struct is_lvalue_reference<T &> {
251     static constexpr bool value = true;
252 };
253 
254 template <class T> struct is_const {
255     static constexpr bool value = false;
256 };
257 
258 template <class T> struct is_const<const T> {
259     static constexpr bool value = true;
260 };
261 
262 template <bool B, class T, class F> struct conditional {
263     using type = T;
264 };
265 
266 template <class T, class F> struct conditional<false, T, F> {
267     using type = F;
268 };
269 
270 template <class U, class T>
271 using CopyConst = typename conditional<is_const<remove_reference<U>>::value,
272                                        const T, T>::type;
273 
274 template <class U, class T>
275 using OverrideRef =
276     typename conditional<is_lvalue_reference<U &&>::value,
277                          typename remove_reference<T>::type &,
278                          typename remove_reference<T>::type &&>::type;
279 
280 template <class U, class T>
281 using ForwardLikeRetType = OverrideRef<U &&, CopyConst<U, T>>;
282 
283 template <class U>
284 constexpr auto forward_like(auto &&t) -> ForwardLikeRetType<U, decltype(t)> {
285     return static_cast<ForwardLikeRetType<U, decltype(t)>>(t);
286 }
287 
288 template <class T>
289 auto move_if_noexcept(T &t) ->
290     typename PickRef<T, noexcept(T(static_cast<T &&>(t)))>::type {
291     return static_cast<
292         typename PickRef<T, noexcept(T(static_cast<T &&>(t)))>::type>(t);
293 }
294 
295 template <class T> T *addressof(T &arg) {
296     return reinterpret_cast<T *>(
297         &const_cast<char &>(reinterpret_cast<const volatile char &>(arg)));
298 }
299 
300 template <class T> struct span {
301   template<size_t _ArrayExtent>
302 	span(const T (&__arr)[_ArrayExtent]) noexcept;
303 };
304 
305 } // namespace foo
306 } // namespace std
307 
308 namespace move_forward_et_al_examples {
309   struct S {
310     S &self() [[clang::lifetimebound]] { return *this; }
311   };
312 
313   S &&Move = std::move(S{}); // expected-warning {{temporary bound to local reference 'Move' will be destroyed at the end of the full-expression}}
314   S MoveOk = std::move(S{});
315 
316   S &&Forward = std::forward<S &&>(S{}); // expected-warning {{temporary bound to local reference 'Forward' will be destroyed at the end of the full-expression}}
317   S ForwardOk = std::forward<S &&>(S{});
318 
319   S &&ForwardLike = std::forward_like<int&&>(S{}); // expected-warning {{temporary bound to local reference 'ForwardLike' will be destroyed at the end of the full-expression}}
320   S ForwardLikeOk = std::forward_like<int&&>(S{});
321 
322   const S &Const = std::as_const(S{}.self()); // expected-warning {{temporary bound to local reference 'Const' will be destroyed at the end of the full-expression}}
323   const S ConstOk = std::as_const(S{}.self());
324 
325   S &&MoveIfNoExcept = std::move_if_noexcept(S{}.self()); // expected-warning {{temporary bound to local reference 'MoveIfNoExcept' will be destroyed at the end of the full-expression}}
326   S MoveIfNoExceptOk = std::move_if_noexcept(S{}.self());
327 
328   S *AddressOf = std::addressof(S{}.self()); // expected-warning {{temporary whose address is used as value of local variable 'AddressOf' will be destroyed at the end of the full-expression}}
329   S X;
330   S *AddressOfOk = std::addressof(X);
331 } // namespace move_forward_et_al_examples
332 
333 namespace ctor_cases {
334 std::basic_string_view<char> test1() {
335   char abc[10];
336   return abc;  // expected-warning {{address of stack memory associated with local variable}}
337 }
338 
339 std::span<int> test2() {
340   int abc[10];
341   return abc; // expected-warning {{address of stack memory associated with local variable}}
342 }
343 } // namespace ctor_cases
344 
345 namespace GH106372 {
346 class [[gsl::Owner]] Foo {};
347 class [[gsl::Pointer]] FooView {};
348 
349 class NonAnnotatedFoo {};
350 class NonAnnotatedFooView {};
351 
352 template <typename T>
353 struct StatusOr {
354   template <typename U = T>
355   StatusOr& operator=(U&& v [[clang::lifetimebound]]);
356 };
357 
358 void test(StatusOr<FooView> foo1, StatusOr<NonAnnotatedFooView> foo2) {
359   foo1 = Foo(); // expected-warning {{object backing foo1 will be destroyed at the end}}
360   // This warning is triggered by the lifetimebound annotation, regardless of whether the class type is annotated with GSL.
361   foo2 = NonAnnotatedFoo(); // expected-warning {{object backing foo2 will be destroyed at the end}}
362 }
363 } // namespace GH106372
364