← Back to Pull requests

[clang-tidy] Don't suggest const on `std::moved` locals in templates … #226577

Merged
daniel-petrovic merged 3 files (58 lines) on Oct 24, 2026 15:31 UTC
View on GitHub
daniel-petrovic daniel-petrovic commented on Sep 25, 2026 19:46 UTC
Author

[clang-tidy] Don't suggest const on std::moved locals in templates

Skip diagnostics in template instantiations for locals that are used as arguments of std::move.
Reason: for some instantiations the move may be converted to copy so the variable may look unmutated and flagged, whereas for other template instantiations the real move semantics may apply.

Fixes: #225395

Assisted by Gemini for constructing the matcher.

Diff: 58 lines (+53 / -5) across 3 files Reviewer: zeyi2 Review duration: 41505m
All Vouch review confidence checks passed
Residual risk 0.04 = Change Risk (0.35) × (1 − Review Confidence (0.88)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.35 · 58 lines diff across 3 files
0.35
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.83 · 5 substantive comment(s)
0.83
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
87%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.244
Ai Authored ai_authored
0.050
Real PR Conversation Timeline
15 items
llvmorg-github-actions[bot] llvmorg-github-actions[bot] commented on Sep 25, 2026 20:06 UTC
Bot

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang-tidy

@llvm/pr-subscribers-clang-tools-extra

Author: Daniel Petrovic (daniel-petrovic)

<details>
<summary>Changes</summary>

[clang-tidy] Don't suggest const on std::moved locals in templates

Skip diagnostics in template instantiations for locals that are used as arguments of std::move.
Reason: for some instantiations the move may be converted to copy so the variable may look unmutated and flagged, whereas for other template instantiations the real move semantics may apply.

Fixes: #<!-- -->225395

Assisted by: Gemini to construct the correct matcher.

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

2 Files Affected:

  • (modified) clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp (+26-3)

  • (modified) clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp (+24)
  • ``````

    diff --git a/clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp b/clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp
    index 57c2bda6c3fd5..3ca76ba915c70 100644
    --- a/clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp
    +++ b/clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp
    @@ -199,6 +199,24 @@ void ConstCorrectnessCheck::registerMatchers(MatchFinder *Finder) {
       }
     }
     
    +static bool isStdMoveOperand(const VarDecl *Variable, const FunctionDecl *Func,
    +                             ASTContext &Context) {
    +  if (Func->isTemplateInstantiation())
    +    if (const Stmt *Body = Func->getBody()) {
    +      // Match on the instantiated body where `std::move` is resolved to a
    +      // concrete function and the argument references the instantiated
    +      // variable.
    +      const auto Moves =
    +          match(stmt(forEachDescendant(
    +                    callExpr(callee(functionDecl(hasName("std::move"))),
    +                             hasArgument(0, ignoringImpCasts(declRefExpr(
    +                                                to(equalsNode(Variable)))))))),
    +                *Body, Context);
    +      return !Moves.empty();
    +    }
    +  return false;
    +}
    +
     static void addConstFixits(const DiagnosticBuilder &Diag,
                                const VarDecl *Variable,
                                const FunctionDecl *Function,
    @@ -255,9 +273,6 @@ void ConstCorrectnessCheck::check(const MatchFinder::MatchResult &Result) {
       /// dependent. Variables like 'int x = 42;' in a template that can become
       /// const emit multiple warnings otherwise.
       bool IsNormalVariableInTemplate = Function->isTemplateInstantiation();
    -  if (IsNormalVariableInTemplate &&
    -      TemplateDiagnosticsCache.contains(Variable->getBeginLoc()))
    -    return;
     
       VariableCategory VC = VariableCategory::Value;
       const QualType VT = Variable->getType();
    @@ -269,6 +284,14 @@ void ConstCorrectnessCheck::check(const MatchFinder::MatchResult &Result) {
                ArrayT && ArrayT->getElementType()->isPointerType())
         VC = VariableCategory::Pointer;
     
    +  if (IsNormalVariableInTemplate && VC != VariableCategory::Pointer &&
    +      isStdMoveOperand(Variable, Function, *Result.Context))
    +    return;
    +
    +  if (IsNormalVariableInTemplate &&
    +      TemplateDiagnosticsCache.contains(Variable->getBeginLoc()))
    +    return;
    +
       const auto CheckValue = [&]() {
         // Offload const-analysis to utility function.
         if (isMutated(Variable, LocalScope, Function, Result.Context))
    diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
    index 98bf27033c3b5..c952dce7b99c5 100644
    --- a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
    +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp
    @@ -6,6 +6,9 @@
     // RUN:   misc-const-correctness.TransformPointersAsValues: false} \
     // RUN:   }" -- -fno-delayed-template-parsing
     
    +#include <string>
    +#include <utility>
    +
     template <typename T>
     void type_dependent_variables() {
       T value = 42;
    @@ -27,6 +30,27 @@ void instantiate_template_cases() {
       type_dependent_variables<float>();
     }
     
    +namespace gh225395 {
    +// The variable 'tmp' is passed to std::move in the template definition, so it
    +// may be moved-from for some instantiations (e.g. std::string) but std::move
    +// degenerates into a copy for others (e.g. int). No warning may be emitted
    +// since the fix-it would apply to the template code and break the move for
    +// types with real move semantics.
    +template <typename T> void my_swap(T &t1, T &t2) {
    +  auto tmp = std::move(t1);
    +  t1 = std::move(t2);
    +  t2 = std::move(tmp);
    +}
    +void instantiate() {
    +  std::string a;
    +  std::string b;
    +  my_swap(a, b);
    +  int x = 0;
    +  int y = 0;
    +  my_swap(x, y);
    +}
    +} // namespace gh225395
    +
     namespace gh57297{
     // The expression to check may not be the dependent operand in a dependent
     // operator.
    
    
    ``````

    </details>

    EugeneZelenko EugeneZelenko commented on Sep 27, 2026 02:04 UTC
    Contributor

    Please mention changes in Release Notes.

    zeyi2 zeyi2 commented on code on Sep 27, 2026 11:51 UTC
    Code Review
    clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp:1
    @@ -199,6 +199,25 @@ void ConstCorrectnessCheck::registerMatchers(MatchFinder *Finder) {
       }
     }
     
    +static bool isStdMoveOperandInTemplate(const VarDecl *Variable,
    +                                       const FunctionDecl *Func,
    +                                       ASTContext &Context) {
    +  if (Func->isTemplateInstantiation())
    +    if (const Stmt *Body = Func->getBody()) {
    +      // Match on the instantiated body where `std::move` is resolved to a
    +      // concrete function and the argument references the instantiated
    +      // variable.
    +      const auto Moves =
    +          match(stmt(forEachDescendant(
    +                    callExpr(callee(functionDecl(hasName("std::move"))),
    +                             hasArgument(0, ignoringImpCasts(declRefExpr(

    Could we use ignoringParenImpCasts here?

    daniel-petrovic daniel-petrovic commented on code on Sep 27, 2026 12:40 UTC
    Code Review
    clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp:1
    @@ -199,6 +199,25 @@ void ConstCorrectnessCheck::registerMatchers(MatchFinder *Finder) {
       }
     }
     
    +static bool isStdMoveOperandInTemplate(const VarDecl *Variable,
    +                                       const FunctionDecl *Func,
    +                                       ASTContext &Context) {
    +  if (Func->isTemplateInstantiation())
    +    if (const Stmt *Body = Func->getBody()) {
    +      // Match on the instantiated body where `std::move` is resolved to a
    +      // concrete function and the argument references the instantiated
    +      // variable.
    +      const auto Moves =
    +          match(stmt(forEachDescendant(
    +                    callExpr(callee(functionDecl(hasName("std::move"))),
    +                             hasArgument(0, ignoringImpCasts(declRefExpr(

    Could we use ignoringParenImpCasts here?

    Thanks for the hint. I think so - updated ( it looks like we could, but there seems to be no difference). I tested std::move((tmp)) but both ignoringImpCasts and ignoringParenImpCasts match it. Is there a specific case you're thinking of where ignoringParenImpCasts would be needed here ?

    compare e.g.:
    ignoringImpCasts: https://godbolt.org/z/57TvGcP1P and ignoringParenImpCasts: https://godbolt.org/z/6sY8veKbT -> can see no matcher difference regardless of paren-nesting level

    daniel-petrovic daniel-petrovic commented on Oct 08, 2026 19:51 UTC
    Author

    @vbvictor @zeyi2 ping : Could you take a quick look on this ? thx

    zeyi2 zeyi2 commented on code on Oct 22, 2026 14:11 UTC
    Code Review
    clang-tools-extra/clang-tidy/misc/ConstCorrectnessCheck.cpp:1
    @@ -199,6 +199,25 @@ void ConstCorrectnessCheck::registerMatchers(MatchFinder *Finder) {
       }
     }
     
    +static bool isStdMoveOperandInTemplate(const VarDecl *Variable,
    +                                       const FunctionDecl *Func,
    +                                       ASTContext &Context) {
    +  if (Func->isTemplateInstantiation())
    +    if (const Stmt *Body = Func->getBody()) {
    +      // Match on the instantiated body where `std::move` is resolved to a
    +      // concrete function and the argument references the instantiated
    +      // variable.
    +      const auto Moves =
    +          match(stmt(forEachDescendant(
    +                    callExpr(callee(functionDecl(hasName("std::move"))),
    +                             hasArgument(0, ignoringImpCasts(declRefExpr(

    Is there a specific case you're thinking of where ignoringParenImpCasts would be needed here ?

    No specific case in mind when I wrote the comment. It was mostly a minor robustness/style nit, as we've had quite a few false positives in clang-tidy caused by matchers not stripping parentheses.

    zeyi2 zeyi2 commented on code on Oct 22, 2026 14:20 UTC
    Code Review
    clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp:1
    @@ -27,6 +30,27 @@ void instantiate_template_cases() {
       type_dependent_variables<float>();
     }
     
    +namespace gh225395 {
    +// The variable 'tmp' is passed to std::move in the template definition, so it

    Nit: Could we shorten or remove this comment? IMO it's a bit verbose for a test, and we generally try to keep comments in our tests concise.

    zeyi2 zeyi2 approved these changes on Oct 22, 2026 14:21 UTC
    Approved Reviewer

    Sorry for the late review ><

    LGTM with a nit. Thanks for working on this!

    daniel-petrovic daniel-petrovic commented on code on Oct 24, 2026 05:39 UTC
    Code Review
    clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-templates.cpp:1
    @@ -27,6 +30,27 @@ void instantiate_template_cases() {
       type_dependent_variables<float>();
     }
     
    +namespace gh225395 {
    +// The variable 'tmp' is passed to std::move in the template definition, so it

    Thanks for reviewing! Sure, I've removed the comment.

    zeyi2 zeyi2 commented on code on Oct 24, 2026 15:05 UTC
    Code Review
    clang-tools-extra/docs/ReleaseNotes.md:1
    @@ -10,8 +10,8 @@ myst:
     % ReleaseNotes.md and ReleaseNotesTemplate.txt.
     
     {#extra-clang-tools-release-releasenotestitle}
    -# Extra Clang Tools {{env.config.release}} {{ (('(In-Progress) ' if env.app.tags.has('PreRelease') else '') ~ 'Release Notes') }}
     

    zeyi2 zeyi2 commented on code on Oct 24, 2026 15:05 UTC
    Code Review
    clang-tools-extra/docs/ReleaseNotes.md:1
    @@ -42,6 +42,7 @@ the current one. To see the release notes for a specific release, please
     see the [releases page](https://llvm.org/releases/).
     
     {#what-s-new-in-extra-clang-tools-release}
    +

    zeyi2 zeyi2 approved these changes on Oct 24, 2026 15:06 UTC
    Approved Reviewer

    Approved these changes.

    zeyi2 zeyi2 commented on code on Oct 24, 2026 15:08 UTC
    Code Review
    clang-tools-extra/docs/ReleaseNotes.md:1
    @@ -12,7 +12,6 @@ myst:
     {#extra-clang-tools-release-releasenotestitle}
     # Extra Clang Tools {{env.config.release}} {{ (('(In-Progress) ' if env.app.tags.has('PreRelease') else '') ~ 'Release Notes') }}
     
    -
     Written by the [LLVM Team](https://llvm.org/)

    
    Written by the [LLVM Team](https://llvm.org/)
    

    zeyi2 zeyi2 commented on Oct 24, 2026 15:09 UTC
    Contributor

    Sorry for the noise. I've cleaned up the unrelated changes in the release notes, and this PR is now ready to merge.

    Thanks for working on this!

    Reviewers
    Assignees
    daniel-petrovic daniel-petrovic
    Labels
    risk: low confidence: 87.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 35.3% (MEDIUM) · Higher = larger blast radius
    35.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 87.6% · Lower = rushed or shallow review
    87.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 4.4% · Safe to merge
    4.4%