Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[clang] Add new warning: not eliding copy on return (missed NRVO) #139973

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
May 16, 2025

Conversation

grigorypas
Copy link
Contributor

This PR aims at adding warning similar to the one in GCC (-Wnrvo) that targets missed opportunities for Named Return Value Optimization (NRVO). The warning is not enabled by default.

cc: @WenleiHe

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang:frontend Language frontend issues, e.g. anything involving "Sema" labels May 14, 2025
@llvmbot
Copy link
Member

llvmbot commented May 14, 2025

@llvm/pr-subscribers-clang

Author: Grigory Pastukhov (grigorypas)

Changes

This PR aims at adding warning similar to the one in GCC (-Wnrvo) that targets missed opportunities for Named Return Value Optimization (NRVO). The warning is not enabled by default.

cc: @WenleiHe


Full diff: https://github.com/llvm/llvm-project/pull/139973.diff

3 Files Affected:

  • (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4)
  • (modified) clang/lib/Sema/SemaDecl.cpp (+4-1)
  • (added) clang/test/SemaCXX/warn-nrvo.cpp (+16)
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 6e940a318b61d..f47d1447d5b60 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12417,6 +12417,10 @@ def warn_zero_as_null_pointer_constant : Warning<
   "zero as null pointer constant">,
   InGroup<DiagGroup<"zero-as-null-pointer-constant">>, DefaultIgnore;
 
+def warn_not_eliding_copy_on_return : Warning<
+  "not eliding copy on return">, 
+  InGroup<DiagGroup<"nrvo">>, DefaultIgnore;
+
 def err_nullability_cs_multilevel : Error<
   "nullability keyword %0 cannot be applied to multi-level pointer type %1">;
 def note_nullability_type_specifier : Note<
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index a7d59ec232b64..6dae243b520f0 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -16093,8 +16093,11 @@ void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
 
   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
-      if (!NRVOCandidate->isNRVOVariable())
+      if (!NRVOCandidate->isNRVOVariable()) {
+        Diag(Returns[I]->getRetValue()->getExprLoc(),
+             diag::warn_not_eliding_copy_on_return);
         Returns[I]->setNRVOCandidate(nullptr);
+      }
     }
   }
 }
diff --git a/clang/test/SemaCXX/warn-nrvo.cpp b/clang/test/SemaCXX/warn-nrvo.cpp
new file mode 100644
index 0000000000000..4552891fd4ab6
--- /dev/null
+++ b/clang/test/SemaCXX/warn-nrvo.cpp
@@ -0,0 +1,16 @@
+// RUN: %clang_cc1 -fsyntax-only -Wnrvo -verify %s
+struct MyClass {
+    int value;
+    int c;
+    MyClass(int v) : value(v), c(0) {}
+    MyClass(const MyClass& other) : value(other.value) { c++; }
+};
+
+MyClass create_object(bool condition) {
+    MyClass obj1(1);
+    MyClass obj2(2);
+    if (condition) {
+        return obj1; // expected-warning{{not eliding copy on return}}
+    }
+    return obj2; // expected-warning{{not eliding copy on return}}
+}

Copy link
Contributor

@mizvekov mizvekov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. This needs a few more tests.

  • A few tests to make sure we don't produce false positives.
  • Tests with function templates with placeholder return types.
    We should never be performing copy elision for these, due to implementation limitations.

@grigorypas
Copy link
Contributor Author

grigorypas commented May 15, 2025

Thanks. This needs a few more tests.

  • A few tests to make sure we don't produce false positives.
  • Tests with function templates with placeholder return types.
    We should never be performing copy elision for these, due to implementation limitations.

Thank you for your feedback. I added more tests. By "function templates with placeholder return types", do you mean something similar to create_object4 in my test case?

@mizvekov
Copy link
Contributor

Thank you for your feedback. I added more tests. By "function templates with placeholder return types", do you mean something similar to create_object4 in my test case?

Yep. That's what I meant.

@mizvekov
Copy link
Contributor

Thanks!

You should make sure to include a release note before merging.

Also, perhaps these should be remarks instead of warnings.
Seems like a better fit to me, it would be similar to remarks we provide about function inlining.
Did you consider that?

FYI @AaronBallman

Copy link
Contributor

@mizvekov mizvekov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you also include a few tests which show whether we suppress the warning on disabled branches of an 'if constexpr'?

Beware we also have bugs and odd cases in this area:

  • It should be possible to NRVO a variable which you don't actually return, by retuning it only on disabled branches.
    It would be interesting to see what the warning does in this case.
  • You can generate bad code by returning a variable with the wrong type from a disabled branch.

@AaronBallman
Copy link
Collaborator

Thanks!

You should make sure to include a release note before merging.

Also, perhaps these should be remarks instead of warnings. Seems like a better fit to me, it would be similar to remarks we provide about function inlining. Did you consider that?

FYI @AaronBallman

Remarks are used when there's something to report but it's not about the code being dubious. NRVO issues straddle the line between dubious code and not dubious code (code could rely on NRVO for correctness). But because GCC already has -Wnrvo and this aims to match their behavior, I think going with the warning flag makes more sense.

@grigorypas grigorypas force-pushed the add-wnrvo-to-clang branch from 7cff5fc to 50449ad Compare May 15, 2025 22:17
@grigorypas
Copy link
Contributor Author

Can you also include a few tests which show whether we suppress the warning on disabled branches of an 'if constexpr'?

Beware we also have bugs and odd cases in this area:

  • It should be possible to NRVO a variable which you don't actually return, by retuning it only on disabled branches.
    It would be interesting to see what the warning does in this case.
  • You can generate bad code by returning a variable with the wrong type from a disabled branch.

I added several tests with dead branches. I noticed that Clang missed NRVO opportunity in create_object5 test. I wonder if it is a know issue or not. GCC seems to handle it.

Copy link
Contributor

@mizvekov mizvekov left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, Thanks!

I added several tests with dead branches. I noticed that Clang missed NRVO opportunity in create_object5 test. I wonder if it is a know issue or not. GCC seems to handle it.

Yeah I think so, the current NRVO algorithm itself is extremely naive, and on top of that we don't run the NRVO propagation on template instantiation, as that depends on Parser infrastructure which is not available anymore after parsing.

So as far as clang is concerned, this only considers the initial template parse, and at that point all branches are possible.

@grigorypas
Copy link
Contributor Author

@mizvekov Could you please merge if it is good to go? I don't have write access.

@mizvekov mizvekov merged commit 48587f3 into llvm:main May 16, 2025
12 checks passed
Copy link

@grigorypas Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang:frontend Language frontend issues, e.g. anything involving "Sema" clang Clang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants
Morty Proxy This is a proxified and sanitized view of the page, visit original site.