xref: /llvm-project/clang-tools-extra/clang-tidy/bugprone/MoveForwardingReferenceCheck.cpp (revision 7d2ea6c422d3f5712b7253407005e1a465a76946)
1 //===--- MoveForwardingReferenceCheck.cpp - clang-tidy --------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "MoveForwardingReferenceCheck.h"
10 #include "clang/Lex/Lexer.h"
11 #include "llvm/Support/raw_ostream.h"
12 
13 #include <algorithm>
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang::tidy::bugprone {
18 
replaceMoveWithForward(const UnresolvedLookupExpr * Callee,const ParmVarDecl * ParmVar,const TemplateTypeParmDecl * TypeParmDecl,DiagnosticBuilder & Diag,const ASTContext & Context)19 static void replaceMoveWithForward(const UnresolvedLookupExpr *Callee,
20                                    const ParmVarDecl *ParmVar,
21                                    const TemplateTypeParmDecl *TypeParmDecl,
22                                    DiagnosticBuilder &Diag,
23                                    const ASTContext &Context) {
24   const SourceManager &SM = Context.getSourceManager();
25   const LangOptions &LangOpts = Context.getLangOpts();
26 
27   CharSourceRange CallRange =
28       Lexer::makeFileCharRange(CharSourceRange::getTokenRange(
29                                    Callee->getBeginLoc(), Callee->getEndLoc()),
30                                SM, LangOpts);
31 
32   if (CallRange.isValid()) {
33     const std::string TypeName =
34         (TypeParmDecl->getIdentifier() && !TypeParmDecl->isImplicit())
35             ? TypeParmDecl->getName().str()
36             : (llvm::Twine("decltype(") + ParmVar->getName() + ")").str();
37 
38     const std::string ForwardName =
39         (llvm::Twine("forward<") + TypeName + ">").str();
40 
41     // Create a replacement only if we see a "standard" way of calling
42     // std::move(). This will hopefully prevent erroneous replacements if the
43     // code does unusual things (e.g. create an alias for std::move() in
44     // another namespace).
45     NestedNameSpecifier *NNS = Callee->getQualifier();
46     if (!NNS) {
47       // Called as "move" (i.e. presumably the code had a "using std::move;").
48       // We still conservatively put a "std::" in front of the forward because
49       // we don't know whether the code also had a "using std::forward;".
50       Diag << FixItHint::CreateReplacement(CallRange, "std::" + ForwardName);
51     } else if (const NamespaceDecl *Namespace = NNS->getAsNamespace()) {
52       if (Namespace->getName() == "std") {
53         if (!NNS->getPrefix()) {
54           // Called as "std::move".
55           Diag << FixItHint::CreateReplacement(CallRange,
56                                                "std::" + ForwardName);
57         } else if (NNS->getPrefix()->getKind() == NestedNameSpecifier::Global) {
58           // Called as "::std::move".
59           Diag << FixItHint::CreateReplacement(CallRange,
60                                                "::std::" + ForwardName);
61         }
62       }
63     }
64   }
65 }
66 
registerMatchers(MatchFinder * Finder)67 void MoveForwardingReferenceCheck::registerMatchers(MatchFinder *Finder) {
68   // Matches a ParmVarDecl for a forwarding reference, i.e. a non-const rvalue
69   // reference of a function template parameter type.
70   auto ForwardingReferenceParmMatcher =
71       parmVarDecl(
72           hasType(qualType(rValueReferenceType(),
73                            references(templateTypeParmType(hasDeclaration(
74                                templateTypeParmDecl().bind("type-parm-decl")))),
75                            unless(references(qualType(isConstQualified()))))))
76           .bind("parm-var");
77 
78   Finder->addMatcher(
79       callExpr(callee(unresolvedLookupExpr(
80                           hasAnyDeclaration(namedDecl(
81                               hasUnderlyingDecl(hasName("::std::move")))))
82                           .bind("lookup")),
83                argumentCountIs(1),
84                hasArgument(0, ignoringParenImpCasts(declRefExpr(
85                                   to(ForwardingReferenceParmMatcher)))))
86           .bind("call-move"),
87       this);
88 }
89 
check(const MatchFinder::MatchResult & Result)90 void MoveForwardingReferenceCheck::check(
91     const MatchFinder::MatchResult &Result) {
92   const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>("call-move");
93   const auto *UnresolvedLookup =
94       Result.Nodes.getNodeAs<UnresolvedLookupExpr>("lookup");
95   const auto *ParmVar = Result.Nodes.getNodeAs<ParmVarDecl>("parm-var");
96   const auto *TypeParmDecl =
97       Result.Nodes.getNodeAs<TemplateTypeParmDecl>("type-parm-decl");
98 
99   // Get the FunctionDecl and FunctionTemplateDecl containing the function
100   // parameter.
101   const auto *FuncForParam = dyn_cast<FunctionDecl>(ParmVar->getDeclContext());
102   if (!FuncForParam)
103     return;
104   const FunctionTemplateDecl *FuncTemplate =
105       FuncForParam->getDescribedFunctionTemplate();
106   if (!FuncTemplate)
107     return;
108 
109   // Check that the template type parameter belongs to the same function
110   // template as the function parameter of that type. (This implies that type
111   // deduction will happen on the type.)
112   const TemplateParameterList *Params = FuncTemplate->getTemplateParameters();
113   if (!llvm::is_contained(*Params, TypeParmDecl))
114     return;
115 
116   auto Diag = diag(CallMove->getExprLoc(),
117                    "forwarding reference passed to std::move(), which may "
118                    "unexpectedly cause lvalues to be moved; use "
119                    "std::forward() instead");
120 
121   replaceMoveWithForward(UnresolvedLookup, ParmVar, TypeParmDecl, Diag,
122                          *Result.Context);
123 }
124 
125 } // namespace clang::tidy::bugprone
126