-
Notifications
You must be signed in to change notification settings - Fork 13.7k
[clang-tidy] Add check performance-lost-std-move #139525
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
base: main
Are you sure you want to change the base?
Changes from all commits
3abbce9
4a1a77b
f74066d
edd4800
5359c69
5bb6af6
592d79b
1710c2f
b4824ef
60e4aca
a27b1b3
6aacd41
71cd708
402ba55
fdf01b6
24357a2
b48425b
986d6aa
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,186 @@ | ||
//===--- LostStdMoveCheck.cpp - clang-tidy --------------------------------===// | ||
// | ||
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
// See https://llvm.org/LICENSE.txt for license information. | ||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#include "LostStdMoveCheck.h" | ||
#include "clang/ASTMatchers/ASTMatchFinder.h" | ||
#include "clang/Lex/Lexer.h" | ||
|
||
using namespace clang::ast_matchers; | ||
|
||
namespace clang::tidy::performance { | ||
|
||
template <typename Node> | ||
void extractNodesByIdTo(ArrayRef<BoundNodes> Matches, StringRef ID, | ||
llvm::SmallPtrSet<const Node *, 16> &Nodes) { | ||
for (const BoundNodes &Match : Matches) | ||
Nodes.insert(Match.getNodeAs<Node>(ID)); | ||
} | ||
|
||
static llvm::SmallPtrSet<const DeclRefExpr *, 16> | ||
allDeclRefExprsHonourLambda(const VarDecl &VarDecl, const Decl &Decl, | ||
ASTContext &Context) { | ||
auto Matches = match( | ||
decl(forEachDescendant( | ||
declRefExpr(to(varDecl(equalsNode(&VarDecl))), | ||
|
||
unless(hasAncestor(lambdaExpr(hasAnyCapture(lambdaCapture( | ||
capturesVar(varDecl(equalsNode(&VarDecl)))))))) | ||
|
||
) | ||
.bind("declRef"))), | ||
Decl, Context); | ||
llvm::SmallPtrSet<const DeclRefExpr *, 16> DeclRefs; | ||
extractNodesByIdTo(Matches, "declRef", DeclRefs); | ||
return DeclRefs; | ||
} | ||
|
||
static const Expr *getLastVarUsage(const VarDecl &Var, const Decl &Func, | ||
ASTContext &Context) { | ||
auto Exprs = allDeclRefExprsHonourLambda(Var, Func, Context); | ||
|
||
const Expr *LastExpr = nullptr; | ||
for (const clang::DeclRefExpr *Expr : Exprs) { | ||
if (!LastExpr) | ||
LastExpr = Expr; | ||
|
||
if (LastExpr->getBeginLoc() < Expr->getBeginLoc()) | ||
LastExpr = Expr; | ||
} | ||
|
||
return LastExpr; | ||
} | ||
|
||
AST_MATCHER(CXXRecordDecl, hasTrivialMoveConstructor) { | ||
return Node.hasDefinition() && Node.hasTrivialMoveConstructor(); | ||
} | ||
|
||
void LostStdMoveCheck::registerMatchers(MatchFinder *Finder) { | ||
auto ReturnParent = | ||
hasParent(expr(hasParent(cxxConstructExpr(hasParent(returnStmt()))))); | ||
|
||
auto OutermostExpr = expr(unless(hasParent(expr()))); | ||
auto LeafStatement = stmt(OutermostExpr); | ||
|
||
Finder->addMatcher( | ||
declRefExpr( | ||
// not "return x;" | ||
unless(ReturnParent), | ||
|
||
unless(hasType(namedDecl(hasName("::std::string_view")))), | ||
|
||
// non-trivial type | ||
hasType(hasCanonicalType(hasDeclaration(cxxRecordDecl()))), | ||
|
||
// non-trivial X(X&&) | ||
unless(hasType(hasCanonicalType( | ||
hasDeclaration(cxxRecordDecl(hasTrivialMoveConstructor()))))), | ||
|
||
// Not in a cycle | ||
unless(hasAncestor(forStmt())), | ||
|
||
unless(hasAncestor(doStmt())), | ||
|
||
unless(hasAncestor(whileStmt())), | ||
|
||
// Not in a body of lambda | ||
unless(hasAncestor(compoundStmt(hasAncestor(lambdaExpr())))), | ||
|
||
// only non-X& | ||
unless(hasDeclaration( | ||
varDecl(hasType(qualType(lValueReferenceType()))))), | ||
|
||
hasAncestor(LeafStatement.bind("leaf_statement")), | ||
|
||
hasDeclaration( | ||
varDecl(hasAncestor(functionDecl().bind("func"))).bind("decl")), | ||
|
||
anyOf( | ||
|
||
// f(x) | ||
hasParent(expr(hasParent(cxxConstructExpr())).bind("use_parent")), | ||
|
||
// f((x)) | ||
hasParent(parenExpr(hasParent( | ||
expr(hasParent(cxxConstructExpr())).bind("use_parent")))) | ||
|
||
) | ||
|
||
) | ||
.bind("use"), | ||
this); | ||
} | ||
|
||
void LostStdMoveCheck::check(const MatchFinder::MatchResult &Result) { | ||
const auto *MatchedDecl = Result.Nodes.getNodeAs<VarDecl>("decl"); | ||
const auto *MatchedFunc = Result.Nodes.getNodeAs<FunctionDecl>("func"); | ||
const auto *MatchedUse = Result.Nodes.getNodeAs<Expr>("use"); | ||
const auto *MatchedUseCall = Result.Nodes.getNodeAs<CallExpr>("use_parent"); | ||
const auto *MatchedLeafStatement = | ||
Result.Nodes.getNodeAs<Stmt>("leaf_statement"); | ||
|
||
if (!MatchedDecl->hasLocalStorage()) | ||
return; | ||
|
||
if (MatchedUseCall) { | ||
return; | ||
} | ||
|
||
const Expr *LastUsage = | ||
getLastVarUsage(*MatchedDecl, *MatchedFunc, *Result.Context); | ||
|
||
if (LastUsage && LastUsage->getBeginLoc() > MatchedUse->getBeginLoc()) { | ||
// "use" is not the last reference to x | ||
return; | ||
} | ||
|
||
if (LastUsage && | ||
LastUsage->getSourceRange() != MatchedUse->getSourceRange()) { | ||
return; | ||
} | ||
|
||
// Calculate X usage count in the statement | ||
llvm::SmallPtrSet<const DeclRefExpr *, 16> DeclRefs; | ||
ArrayRef<BoundNodes> Matches = match( | ||
findAll(declRefExpr( | ||
|
||
to(varDecl(equalsNode(MatchedDecl))), | ||
|
||
unless(hasAncestor(lambdaExpr(hasAnyCapture(lambdaCapture( | ||
capturesVar(varDecl(equalsNode(MatchedDecl)))))))) | ||
|
||
) | ||
.bind("ref")), | ||
*MatchedLeafStatement, *Result.Context); | ||
extractNodesByIdTo(Matches, "ref", DeclRefs); | ||
if (DeclRefs.size() > 1) { | ||
// Unspecified order of evaluation, e.g. f(x, x) | ||
return; | ||
} | ||
|
||
const SourceManager &Source = Result.Context->getSourceManager(); | ||
const auto Range = | ||
CharSourceRange::getTokenRange(MatchedUse->getSourceRange()); | ||
const StringRef NeedleExprCode = | ||
Lexer::getSourceText(Range, Source, Result.Context->getLangOpts()); | ||
|
||
if (NeedleExprCode == "=") { | ||
|
||
diag(MatchedUse->getBeginLoc(), "could be std::move()") | ||
<< FixItHint::CreateInsertion(MatchedUse->getBeginLoc(), | ||
(MatchedDecl->getName() + | ||
" = std::move(" + | ||
MatchedDecl->getName() + "),") | ||
.str()); | ||
} else { | ||
diag(MatchedUse->getBeginLoc(), "could be std::move()") | ||
<< FixItHint::CreateReplacement( | ||
Range, ("std::move(" + NeedleExprCode + ")").str()); | ||
} | ||
} | ||
|
||
} // namespace clang::tidy::performance |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
//===--- LostStdMoveCheck.h - clang-tidy ------------------------*- C++ -*-===// | ||
// | ||
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||
// See https://llvm.org/LICENSE.txt for license information. | ||
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_LOSTSTDMOVECHECK_H | ||
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_LOSTSTDMOVECHECK_H | ||
|
||
#include "../ClangTidyCheck.h" | ||
|
||
namespace clang::tidy::performance { | ||
|
||
/// Warns if copy constructor is used instead of std::move() and suggests a fix. | ||
/// It honours cycles, lambdas, and unspecified call order in compound | ||
/// expressions. | ||
/// | ||
/// For the user-facing documentation see: | ||
/// http://clang.llvm.org/extra/clang-tidy/checks/performance/lost-std-move.html | ||
class LostStdMoveCheck : public ClangTidyCheck { | ||
public: | ||
LostStdMoveCheck(StringRef Name, ClangTidyContext *Context) | ||
: ClangTidyCheck(Name, Context) {} | ||
void registerMatchers(ast_matchers::MatchFinder *Finder) override; | ||
void check(const ast_matchers::MatchFinder::MatchResult &Result) override; | ||
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { | ||
return LangOpts.CPlusPlus11; | ||
} | ||
}; | ||
|
||
} // namespace clang::tidy::performance | ||
|
||
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_PERFORMANCE_LOSTSTDMOVECHECK_H |
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -136,6 +136,12 @@ New checks | |||||
Finds unintended character output from ``unsigned char`` and ``signed char`` | ||||||
to an ``ostream``. | ||||||
|
||||||
- New :doc:`performance-lost-std-move | ||||||
<clang-tidy/checks/performance/lost-std-move>` check. | ||||||
|
||||||
Warns if copy constructor is used instead of std::move() and suggests a fix. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
It honours cycles, lambdas, and unspecified call order in compound expressions. | ||||||
|
||||||
- New :doc:`portability-avoid-pragma-once | ||||||
<clang-tidy/checks/portability/avoid-pragma-once>` check. | ||||||
|
||||||
|
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
@@ -0,0 +1,32 @@ | ||||||
.. title:: clang-tidy - performance-lost-std-move | ||||||
|
||||||
performance-lost-std-move | ||||||
========================= | ||||||
|
||||||
Warns if copy constructor is used instead of std::move() and suggests a fix. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
It honours cycles, lambdas, and unspecified call order in compound expressions. | ||||||
|
||||||
.. code-block:: c++ | ||||||
|
||||||
void f(X); | ||||||
|
||||||
void g(X x) { | ||||||
f(x); // warning: Could be std::move() [performance-lost-std-move] | ||||||
} | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Give examples when check will not warn |
||||||
|
||||||
It finds the last local variable usage, and if it is a copy, emits a warning. | ||||||
The check is based on pure AST matching and doesn't take into account any data flow information. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please follow 80-characters limit. |
||||||
Thus, it doesn't catch assign-after-copy cases. | ||||||
Also it doesn't notice variable references "behind the scenes": | ||||||
|
||||||
.. code-block:: c++ | ||||||
|
||||||
void f(X); | ||||||
|
||||||
void g(X x) { | ||||||
auto &y = x; | ||||||
f(x); // emits a warning... | ||||||
y.f(); // ...but it is still used | ||||||
} | ||||||
Comment on lines
+19
to
+30
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I strongly oppose this design decision. In this check we should minimize the number of false-positives (and not leave any known false-positives). It's better to have false-negatives than false-positives, so an easy solution to this case could be: There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The problem is that any binding to a reference should skip the check. E.g.
I'm afraid too many cases are skipped due to this problem. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We can distinguish cases where a variable was an initializer to In your 3-liner example, it may be easy to spot a false-positive, but if May other reviews share their opinions on this matter. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Would it be a compromise to enable this via an option that is disabled by default? |
||||||
|
||||||
Such rare cases should be silenced using `// NOLINT`. | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should general functionality be mentioned? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Excessive newline. Same in other places.