| 1 |
// RUN: %clang_cc1 -fsyntax-only -Wnrvo -Wno-return-mismatch -verify %s |
| 2 |
struct MyClass { |
| 3 |
int value; |
| 4 |
int c; |
| 5 |
MyClass(int v) : value(v), c(0) {} |
| 6 |
MyClass(const MyClass& other) : value(other.value) { c++; } |
| 7 |
}; |
| 8 |
|
| 9 |
MyClass create_object(bool condition) { |
| 10 |
MyClass obj1(1); |
| 11 |
MyClass obj2(2); |
| 12 |
if (condition) { |
| 13 |
return obj1; // expected-warning{{not eliding copy on return}} |
| 14 |
} |
| 15 |
return obj2; // expected-warning{{not eliding copy on return}} |
| 16 |
} |
| 17 |
|
| 18 |
MyClass create_object2(){ |
| 19 |
MyClass obj(1); |
| 20 |
return obj; // no warning |
| 21 |
} |
| 22 |
|
| 23 |
template<typename T> |
| 24 |
T create_object3(){ |
| 25 |
T obj(1); |
| 26 |
return obj; // no warning |
| 27 |
} |
| 28 |
|
| 29 |
// Known issue: if a function template uses a |
| 30 |
// deduced return type (i.e. auto or decltype(auto)), |
| 31 |
// then NRVO is not applied for any instantiation of |
| 32 |
// that function template |
| 33 |
// (see https://github.com/llvm/llvm-project/issues/95280). |
| 34 |
template<typename T> |
| 35 |
auto create_object4(){ |
| 36 |
T obj(1); |
| 37 |
return obj; // expected-warning{{not eliding copy on return}} |
| 38 |
} |
| 39 |
|
| 40 |
template<bool F> |
| 41 |
MyClass create_object5(){ |
| 42 |
MyClass obj1(1); |
| 43 |
if constexpr (F){ |
| 44 |
MyClass obj2(2); |
| 45 |
return obj2; // no warning |
| 46 |
} |
| 47 |
// Missed NRVO optimization by clang |
| 48 |
return obj1; // expected-warning{{not eliding copy on return}} |
| 49 |
} |
| 50 |
|
| 51 |
constexpr bool Flag = false; |
| 52 |
|
| 53 |
MyClass create_object6(){ |
| 54 |
MyClass obj1(1); |
| 55 |
if constexpr (Flag){ |
| 56 |
MyClass obj2(2); |
| 57 |
return obj2; // expected-warning{{not eliding copy on return}} |
| 58 |
} |
| 59 |
return obj1; // no warning |
| 60 |
} |
| 61 |
|
| 62 |
void create_object7(){ |
| 63 |
if constexpr (Flag){ |
| 64 |
MyClass obj1(1); |
| 65 |
return obj1; // no warning |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
void init_templates(){ |
| 70 |
create_object3<MyClass>(); // no warning |
| 71 |
create_object4<MyClass>(); // expected-note {{in instantiation of function template specialization 'create_object4<MyClass>' requested here}} |
| 72 |
create_object5<false>(); // expected-note {{in instantiation of function template specialization 'create_object5<false>' requested here}} |
| 73 |
} |