clang-tools 22.0.0git
PassByValueCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 "PassByValueCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/AST/RecursiveASTVisitor.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/Lexer.h"
16#include "clang/Lex/Preprocessor.h"
17
18using namespace clang::ast_matchers;
19using namespace llvm;
20
21namespace clang::tidy::modernize {
22
23static bool isFirstFriendOfSecond(const CXXRecordDecl *Friend,
24 const CXXRecordDecl *Class) {
25 return llvm::any_of(
26 Class->friends(), [Friend](FriendDecl *FriendDecl) -> bool {
27 if (const TypeSourceInfo *FriendTypeSource =
28 FriendDecl->getFriendType()) {
29 const QualType FriendType = FriendTypeSource->getType();
30 return FriendType->getAsCXXRecordDecl() == Friend;
31 }
32 return false;
33 });
34}
35
36namespace {
37/// Matches move-constructible classes whose constructor can be called inside
38/// a CXXRecordDecl with a bound ID.
39///
40/// Given
41/// \code
42/// // POD types are trivially move constructible.
43/// struct Foo { int a; };
44///
45/// struct Bar {
46/// Bar(Bar &&) = deleted;
47/// int a;
48/// };
49///
50/// class Buz {
51/// Buz(Buz &&);
52/// int a;
53/// friend class Outer;
54/// };
55///
56/// class Outer {
57/// };
58/// \endcode
59/// recordDecl(isMoveConstructibleInBoundCXXRecordDecl("Outer"))
60/// matches "Foo", "Buz".
61AST_MATCHER_P(CXXRecordDecl, isMoveConstructibleInBoundCXXRecordDecl, StringRef,
62 RecordDeclID) {
63 return Builder->removeBindings(
64 [this,
65 &Node](const ast_matchers::internal::BoundNodesMap &Nodes) -> bool {
66 const auto *BoundClass =
67 Nodes.getNode(this->RecordDeclID).get<CXXRecordDecl>();
68 for (const CXXConstructorDecl *Ctor : Node.ctors())
69 if (Ctor->isMoveConstructor() && !Ctor->isDeleted() &&
70 (Ctor->getAccess() == AS_public ||
71 (BoundClass && isFirstFriendOfSecond(BoundClass, &Node))))
72 return false;
73 return true;
74 });
75}
76} // namespace
77
78static TypeMatcher notTemplateSpecConstRefType() {
79 return lValueReferenceType(
80 pointee(unless(templateSpecializationType()), isConstQualified()));
81}
82
83static TypeMatcher nonConstValueType() {
84 return qualType(unless(anyOf(referenceType(), isConstQualified())));
85}
86
87/// Whether or not \p ParamDecl is used exactly one time in \p Ctor.
88///
89/// Checks both in the init-list and the body of the constructor.
90static bool paramReferredExactlyOnce(const CXXConstructorDecl *Ctor,
91 const ParmVarDecl *ParamDecl) {
92 /// \c clang::RecursiveASTVisitor that checks that the given
93 /// \c ParmVarDecl is used exactly one time.
94 ///
95 /// \see ExactlyOneUsageVisitor::hasExactlyOneUsageIn()
96 class ExactlyOneUsageVisitor
97 : public RecursiveASTVisitor<ExactlyOneUsageVisitor> {
98 friend class RecursiveASTVisitor<ExactlyOneUsageVisitor>;
99
100 public:
101 ExactlyOneUsageVisitor(const ParmVarDecl *ParamDecl)
102 : ParamDecl(ParamDecl) {}
103
104 /// Whether or not the parameter variable is referred only once in
105 /// the
106 /// given constructor.
107 bool hasExactlyOneUsageIn(const CXXConstructorDecl *Ctor) {
108 Count = 0U;
109 TraverseDecl(const_cast<CXXConstructorDecl *>(Ctor));
110 return Count == 1U;
111 }
112
113 private:
114 /// Counts the number of references to a variable.
115 ///
116 /// Stops the AST traversal if more than one usage is found.
117 bool VisitDeclRefExpr(DeclRefExpr *D) {
118 if (const ParmVarDecl *To = dyn_cast<ParmVarDecl>(D->getDecl())) {
119 if (To == ParamDecl) {
120 ++Count;
121 if (Count > 1U) {
122 // No need to look further, used more than once.
123 return false;
124 }
125 }
126 }
127 return true;
128 }
129
130 const ParmVarDecl *ParamDecl;
131 unsigned Count = 0U;
132 };
133
134 return ExactlyOneUsageVisitor(ParamDecl).hasExactlyOneUsageIn(Ctor);
135}
136
137/// Returns true if the given constructor is part of a lvalue/rvalue reference
138/// pair, i.e. `Param` is of lvalue reference type, and there exists another
139/// constructor such that:
140/// - it has the same number of parameters as `Ctor`.
141/// - the parameter at the same index as `Param` is an rvalue reference
142/// of the same pointee type
143/// - all other parameters have the same type as the corresponding parameter in
144/// `Ctor` or are rvalue references with the same pointee type.
145/// Examples:
146/// A::A(const B& Param)
147/// A::A(B&&)
148///
149/// A::A(const B& Param, const C&)
150/// A::A(B&& Param, C&&)
151///
152/// A::A(const B&, const C& Param)
153/// A::A(B&&, C&& Param)
154///
155/// A::A(const B&, const C& Param)
156/// A::A(const B&, C&& Param)
157///
158/// A::A(const B& Param, int)
159/// A::A(B&& Param, int)
160static bool hasRValueOverload(const CXXConstructorDecl *Ctor,
161 const ParmVarDecl *Param) {
162 if (!Param->getType().getCanonicalType()->isLValueReferenceType()) {
163 // The parameter is passed by value.
164 return false;
165 }
166 const int ParamIdx = Param->getFunctionScopeIndex();
167 const CXXRecordDecl *Record = Ctor->getParent();
168
169 // Check whether a ctor `C` forms a pair with `Ctor` under the aforementioned
170 // rules.
171 const auto IsRValueOverload = [&Ctor, ParamIdx](const CXXConstructorDecl *C) {
172 if (C == Ctor || C->isDeleted() ||
173 C->getNumParams() != Ctor->getNumParams())
174 return false;
175 for (int I = 0, E = C->getNumParams(); I < E; ++I) {
176 const clang::QualType CandidateParamType =
177 C->parameters()[I]->getType().getCanonicalType();
178 const clang::QualType CtorParamType =
179 Ctor->parameters()[I]->getType().getCanonicalType();
180 const bool IsLValueRValuePair =
181 CtorParamType->isLValueReferenceType() &&
182 CandidateParamType->isRValueReferenceType() &&
183 CandidateParamType->getPointeeType()->getUnqualifiedDesugaredType() ==
184 CtorParamType->getPointeeType()->getUnqualifiedDesugaredType();
185 if (I == ParamIdx) {
186 // The parameter of interest must be paired.
187 if (!IsLValueRValuePair)
188 return false;
189 } else {
190 // All other parameters can be similar or paired.
191 if (!(CandidateParamType == CtorParamType || IsLValueRValuePair))
192 return false;
193 }
194 }
195 return true;
196 };
197
198 return llvm::any_of(Record->ctors(), IsRValueOverload);
199}
200
201/// Find all references to \p ParamDecl across all of the
202/// redeclarations of \p Ctor.
203static SmallVector<const ParmVarDecl *, 2>
204collectParamDecls(const CXXConstructorDecl *Ctor,
205 const ParmVarDecl *ParamDecl) {
206 SmallVector<const ParmVarDecl *, 2> Results;
207 const unsigned ParamIdx = ParamDecl->getFunctionScopeIndex();
208
209 for (const FunctionDecl *Redecl : Ctor->redecls())
210 Results.push_back(Redecl->getParamDecl(ParamIdx));
211 return Results;
212}
213
215 : ClangTidyCheck(Name, Context),
216 Inserter(Options.getLocalOrGlobal("IncludeStyle",
217 utils::IncludeSorter::IS_LLVM),
218 areDiagsSelfContained()),
219 ValuesOnly(Options.get("ValuesOnly", false)) {}
220
222 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
223 Options.store(Opts, "ValuesOnly", ValuesOnly);
224}
225
226void PassByValueCheck::registerMatchers(MatchFinder *Finder) {
227 Finder->addMatcher(
228 traverse(
229 TK_AsIs,
230 cxxConstructorDecl(
231 ofClass(cxxRecordDecl().bind("outer")),
232 forEachConstructorInitializer(
233 cxxCtorInitializer(
234 unless(isBaseInitializer()),
235 // Clang builds a CXXConstructExpr only when it knows
236 // which constructor will be called. In dependent contexts
237 // a ParenListExpr is generated instead of a
238 // CXXConstructExpr, filtering out templates automatically
239 // for us.
240 withInitializer(cxxConstructExpr(
241 has(ignoringParenImpCasts(declRefExpr(to(
242 parmVarDecl(
243 hasType(qualType(
244 // Match only const-ref or a non-const
245 // value parameters. Rvalues,
246 // TemplateSpecializationValues and
247 // const-values shouldn't be modified.
248 ValuesOnly
252 .bind("Param"))))),
253 hasDeclaration(cxxConstructorDecl(
254 isCopyConstructor(), unless(isDeleted()),
255 hasDeclContext(cxxRecordDecl(
256 isMoveConstructibleInBoundCXXRecordDecl(
257 "outer"))))))))
258 .bind("Initializer")))
259 .bind("Ctor")),
260 this);
261}
262
263void PassByValueCheck::registerPPCallbacks(const SourceManager &SM,
264 Preprocessor *PP,
265 Preprocessor *ModuleExpanderPP) {
266 Inserter.registerPreprocessor(PP);
267}
268
269void PassByValueCheck::check(const MatchFinder::MatchResult &Result) {
270 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("Ctor");
271 const auto *ParamDecl = Result.Nodes.getNodeAs<ParmVarDecl>("Param");
272 const auto *Initializer =
273 Result.Nodes.getNodeAs<CXXCtorInitializer>("Initializer");
274 const SourceManager &SM = *Result.SourceManager;
275
276 // If the parameter is used or anything other than the copy, do not apply
277 // the changes.
278 if (!paramReferredExactlyOnce(Ctor, ParamDecl))
279 return;
280
281 // If the parameter is trivial to copy, don't move it. Moving a trivially
282 // copyable type will cause a problem with performance-move-const-arg
283 if (ParamDecl->getType().getNonReferenceType().isTriviallyCopyableType(
284 *Result.Context))
285 return;
286
287 // Do not trigger if we find a paired constructor with an rvalue.
288 if (hasRValueOverload(Ctor, ParamDecl))
289 return;
290
291 auto Diag = diag(ParamDecl->getBeginLoc(), "pass by value and use std::move");
292
293 // If we received a `const&` type, we need to rewrite the function
294 // declarations.
295 if (ParamDecl->getType()->isLValueReferenceType()) {
296 // Check if we can succesfully rewrite all declarations of the constructor.
297 for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) {
298 const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc();
299 auto RefTL = ParamTL.getAs<ReferenceTypeLoc>();
300 if (RefTL.isNull()) {
301 // We cannot rewrite this instance. The type is probably hidden behind
302 // some `typedef`. Do not offer a fix-it in this case.
303 return;
304 }
305 }
306 // Rewrite all declarations.
307 for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) {
308 const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc();
309 auto RefTL = ParamTL.getAs<ReferenceTypeLoc>();
310
311 const TypeLoc ValueTL = RefTL.getPointeeLoc();
312 const CharSourceRange TypeRange = CharSourceRange::getTokenRange(
313 ParmDecl->getBeginLoc(), ParamTL.getEndLoc());
314 std::string ValueStr =
315 Lexer::getSourceText(
316 CharSourceRange::getTokenRange(ValueTL.getSourceRange()), SM,
317 getLangOpts())
318 .str();
319 ValueStr += ' ';
320 Diag << FixItHint::CreateReplacement(TypeRange, ValueStr);
321 }
322 }
323
324 // Use std::move in the initialization list.
325 Diag << FixItHint::CreateInsertion(Initializer->getRParenLoc(), ")")
326 << FixItHint::CreateInsertion(
327 Initializer->getLParenLoc().getLocWithOffset(1), "std::move(")
328 << Inserter.createIncludeInsertion(
329 Result.SourceManager->getFileID(Initializer->getSourceLocation()),
330 "<utility>");
331}
332
333} // namespace clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
PassByValueCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
static SmallVector< const ParmVarDecl *, 2 > collectParamDecls(const CXXConstructorDecl *Ctor, const ParmVarDecl *ParamDecl)
Find all references to ParamDecl across all of the redeclarations of Ctor.
static bool hasRValueOverload(const CXXConstructorDecl *Ctor, const ParmVarDecl *Param)
Returns true if the given constructor is part of a lvalue/rvalue reference pair, i....
static bool isFirstFriendOfSecond(const CXXRecordDecl *Friend, const CXXRecordDecl *Class)
static bool paramReferredExactlyOnce(const CXXConstructorDecl *Ctor, const ParmVarDecl *ParamDecl)
Whether or not ParamDecl is used exactly one time in Ctor.
static TypeMatcher nonConstValueType()
static TypeMatcher notTemplateSpecConstRefType()
Some operations such as code completion produce a set of candidates.
Definition Generators.h:145
llvm::StringMap< ClangTidyValue > OptionMap