clang-tools 22.0.0git
UseEmplaceCheck.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 "UseEmplaceCheck.h"
11using namespace clang::ast_matchers;
12
13namespace clang::tidy::modernize {
14
15namespace {
16AST_MATCHER_P(InitListExpr, initCountLeq, unsigned, N) {
17 return Node.getNumInits() <= N;
18}
19
20// Identical to hasAnyName, except it does not take template specifiers into
21// account. This is used to match the functions names as in
22// DefaultEmplacyFunctions below without caring about the template types of the
23// containers.
24AST_MATCHER_P(NamedDecl, hasAnyNameIgnoringTemplates, std::vector<StringRef>,
25 Names) {
26 const std::string FullName = "::" + Node.getQualifiedNameAsString();
27
28 // This loop removes template specifiers by only keeping characters not within
29 // template brackets. We keep a depth count to handle nested templates. For
30 // example, it'll transform a::b<c<d>>::e<f> to simply a::b::e.
31 std::string FullNameTrimmed;
32 int Depth = 0;
33 for (const auto &Character : FullName) {
34 if (Character == '<') {
35 ++Depth;
36 } else if (Character == '>') {
37 --Depth;
38 } else if (Depth == 0) {
39 FullNameTrimmed.append(1, Character);
40 }
41 }
42
43 // This loop is taken from HasNameMatcher::matchesNodeFullSlow in
44 // clang/lib/ASTMatchers/ASTMatchersInternal.cpp and checks whether
45 // FullNameTrimmed matches any of the given Names.
46 const StringRef FullNameTrimmedRef = FullNameTrimmed;
47 for (const StringRef Pattern : Names) {
48 if (Pattern.starts_with("::")) {
49 if (FullNameTrimmed == Pattern)
50 return true;
51 } else if (FullNameTrimmedRef.ends_with(Pattern) &&
52 FullNameTrimmedRef.drop_back(Pattern.size()).ends_with("::")) {
53 return true;
54 }
55 }
56
57 return false;
58}
59
60// Checks if the given matcher is the last argument of the given CallExpr.
61AST_MATCHER_P(CallExpr, hasLastArgument,
62 clang::ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
63 if (Node.getNumArgs() == 0)
64 return false;
65
66 return InnerMatcher.matches(*Node.getArg(Node.getNumArgs() - 1), Finder,
67 Builder);
68}
69
70// Checks if the given member call has the same number of arguments as the
71// function had parameters defined (this is useful to check if there is only one
72// variadic argument).
73AST_MATCHER(CXXMemberCallExpr, hasSameNumArgsAsDeclNumParams) {
74 if (const FunctionTemplateDecl *Primary =
75 Node.getMethodDecl()->getPrimaryTemplate())
76 return Node.getNumArgs() == Primary->getTemplatedDecl()->getNumParams();
77
78 return Node.getNumArgs() == Node.getMethodDecl()->getNumParams();
79}
80
81AST_MATCHER(DeclRefExpr, hasExplicitTemplateArgs) {
82 return Node.hasExplicitTemplateArgs();
83}
84
85// Helper Matcher which applies the given QualType Matcher either directly or by
86// resolving a pointer type to its pointee. Used to match v.push_back() as well
87// as p->push_back().
88auto hasTypeOrPointeeType(
89 const ast_matchers::internal::Matcher<QualType> &TypeMatcher) {
90 return anyOf(hasType(TypeMatcher),
91 hasType(pointerType(pointee(TypeMatcher))));
92}
93
94// Matches if the node has canonical type matching any of the given names.
95auto hasWantedType(llvm::ArrayRef<StringRef> TypeNames) {
96 return hasCanonicalType(hasDeclaration(cxxRecordDecl(hasAnyName(TypeNames))));
97}
98
99// Matches member call expressions of the named method on the listed container
100// types.
101auto cxxMemberCallExprOnContainer(StringRef MethodName,
102 llvm::ArrayRef<StringRef> ContainerNames) {
103 return cxxMemberCallExpr(
104 hasDeclaration(functionDecl(hasName(MethodName))),
105 on(hasTypeOrPointeeType(hasWantedType(ContainerNames))));
106}
107
108const auto DefaultContainersWithPushBack =
109 "::std::vector; ::std::list; ::std::deque";
110const auto DefaultContainersWithPush =
111 "::std::stack; ::std::queue; ::std::priority_queue";
112const auto DefaultContainersWithPushFront =
113 "::std::forward_list; ::std::list; ::std::deque";
114const auto DefaultSmartPointers =
115 "::std::shared_ptr; ::std::unique_ptr; ::std::auto_ptr; ::std::weak_ptr";
116const auto DefaultTupleTypes = "::std::pair; ::std::tuple";
117const auto DefaultTupleMakeFunctions = "::std::make_pair; ::std::make_tuple";
118const auto DefaultEmplacyFunctions =
119 "vector::emplace_back; vector::emplace;"
120 "deque::emplace; deque::emplace_front; deque::emplace_back;"
121 "forward_list::emplace_after; forward_list::emplace_front;"
122 "list::emplace; list::emplace_back; list::emplace_front;"
123 "set::emplace; set::emplace_hint;"
124 "map::emplace; map::emplace_hint;"
125 "multiset::emplace; multiset::emplace_hint;"
126 "multimap::emplace; multimap::emplace_hint;"
127 "unordered_set::emplace; unordered_set::emplace_hint;"
128 "unordered_map::emplace; unordered_map::emplace_hint;"
129 "unordered_multiset::emplace; unordered_multiset::emplace_hint;"
130 "unordered_multimap::emplace; unordered_multimap::emplace_hint;"
131 "stack::emplace; queue::emplace; priority_queue::emplace";
132} // namespace
133
135 : ClangTidyCheck(Name, Context), IgnoreImplicitConstructors(Options.get(
136 "IgnoreImplicitConstructors", false)),
137 ContainersWithPushBack(utils::options::parseStringList(Options.get(
138 "ContainersWithPushBack", DefaultContainersWithPushBack))),
139 ContainersWithPush(utils::options::parseStringList(
140 Options.get("ContainersWithPush", DefaultContainersWithPush))),
141 ContainersWithPushFront(utils::options::parseStringList(Options.get(
142 "ContainersWithPushFront", DefaultContainersWithPushFront))),
143 SmartPointers(utils::options::parseStringList(
144 Options.get("SmartPointers", DefaultSmartPointers))),
145 TupleTypes(utils::options::parseStringList(
146 Options.get("TupleTypes", DefaultTupleTypes))),
147 TupleMakeFunctions(utils::options::parseStringList(
148 Options.get("TupleMakeFunctions", DefaultTupleMakeFunctions))),
149 EmplacyFunctions(utils::options::parseStringList(
150 Options.get("EmplacyFunctions", DefaultEmplacyFunctions))) {}
151
152void UseEmplaceCheck::registerMatchers(MatchFinder *Finder) {
153 // FIXME: Bunch of functionality that could be easily added:
154 // + add handling of `insert` for stl associative container, but be careful
155 // because this requires special treatment (it could cause performance
156 // regression)
157 // + match for emplace calls that should be replaced with insertion
158 auto CallPushBack =
159 cxxMemberCallExprOnContainer("push_back", ContainersWithPushBack);
160 auto CallPush = cxxMemberCallExprOnContainer("push", ContainersWithPush);
161 auto CallPushFront =
162 cxxMemberCallExprOnContainer("push_front", ContainersWithPushFront);
163
164 auto CallEmplacy = cxxMemberCallExpr(
165 hasDeclaration(
166 functionDecl(hasAnyNameIgnoringTemplates(EmplacyFunctions))),
167 on(hasTypeOrPointeeType(
168 hasCanonicalType(hasDeclaration(has(typedefNameDecl(
169 hasName("value_type"),
170 hasType(hasCanonicalType(recordType().bind("value_type"))))))))));
171
172 // We can't replace push_backs of smart pointer because
173 // if emplacement fails (f.e. bad_alloc in vector) we will have leak of
174 // passed pointer because smart pointer won't be constructed
175 // (and destructed) as in push_back case.
176 auto IsCtorOfSmartPtr =
177 hasDeclaration(cxxConstructorDecl(ofClass(hasAnyName(SmartPointers))));
178
179 // Bitfields binds only to consts and emplace_back take it by universal ref.
180 auto BitFieldAsArgument = hasAnyArgument(
181 ignoringImplicit(memberExpr(hasDeclaration(fieldDecl(isBitField())))));
182
183 // Initializer list can't be passed to universal reference.
184 auto InitializerListAsArgument = hasAnyArgument(
185 ignoringImplicit(allOf(cxxConstructExpr(isListInitialization()),
186 unless(cxxTemporaryObjectExpr()))));
187
188 // We could have leak of resource.
189 auto NewExprAsArgument = hasAnyArgument(ignoringImplicit(cxxNewExpr()));
190 // We would call another constructor.
191 auto ConstructingDerived =
192 hasParent(implicitCastExpr(hasCastKind(CastKind::CK_DerivedToBase)));
193
194 // emplace_back can't access private or protected constructors.
195 auto IsPrivateOrProtectedCtor =
196 hasDeclaration(cxxConstructorDecl(anyOf(isPrivate(), isProtected())));
197
198 auto HasInitList = anyOf(has(ignoringImplicit(initListExpr())),
199 has(cxxStdInitializerListExpr()));
200
201 // FIXME: Discard 0/NULL (as nullptr), static inline const data members,
202 // overloaded functions and template names.
203 auto SoughtConstructExpr =
204 cxxConstructExpr(
205 unless(anyOf(IsCtorOfSmartPtr, HasInitList, BitFieldAsArgument,
206 InitializerListAsArgument, NewExprAsArgument,
207 ConstructingDerived, IsPrivateOrProtectedCtor)))
208 .bind("ctor");
209 auto HasConstructExpr = has(ignoringImplicit(SoughtConstructExpr));
210
211 // allow for T{} to be replaced, even if no CTOR is declared
212 auto HasConstructInitListExpr = has(initListExpr(
213 initCountLeq(1), anyOf(allOf(has(SoughtConstructExpr),
214 has(cxxConstructExpr(argumentCountIs(0)))),
215 has(cxxBindTemporaryExpr(
216 has(SoughtConstructExpr),
217 has(cxxConstructExpr(argumentCountIs(0))))))));
218 auto HasBracedInitListExpr =
219 anyOf(has(cxxBindTemporaryExpr(HasConstructInitListExpr)),
220 HasConstructInitListExpr);
221
222 auto MakeTuple = ignoringImplicit(
223 callExpr(callee(expr(ignoringImplicit(declRefExpr(
224 unless(hasExplicitTemplateArgs()),
225 to(functionDecl(hasAnyName(TupleMakeFunctions))))))))
226 .bind("make"));
227
228 // make_something can return type convertible to container's element type.
229 // Allow the conversion only on containers of pairs.
230 auto MakeTupleCtor = ignoringImplicit(cxxConstructExpr(
231 has(materializeTemporaryExpr(MakeTuple)),
232 hasDeclaration(cxxConstructorDecl(ofClass(hasAnyName(TupleTypes))))));
233
234 auto SoughtParam =
235 materializeTemporaryExpr(
236 anyOf(has(MakeTuple), has(MakeTupleCtor), HasConstructExpr,
237 HasBracedInitListExpr,
238 has(cxxFunctionalCastExpr(HasConstructExpr)),
239 has(cxxFunctionalCastExpr(HasBracedInitListExpr))))
240 .bind("temporary_expr");
241
242 auto HasConstructExprWithValueTypeType =
243 has(ignoringImplicit(cxxConstructExpr(
244 SoughtConstructExpr,
245 hasType(hasCanonicalType(type(equalsBoundNode("value_type")))))));
246
247 auto HasBracedInitListWithValueTypeType = anyOf(
248 allOf(HasConstructInitListExpr,
249 has(initListExpr(hasType(
250 hasCanonicalType(type(equalsBoundNode("value_type"))))))),
251 has(cxxBindTemporaryExpr(HasConstructInitListExpr,
252 has(initListExpr(hasType(hasCanonicalType(
253 type(equalsBoundNode("value_type")))))))));
254
255 auto HasConstructExprWithValueTypeTypeAsLastArgument = hasLastArgument(
256 materializeTemporaryExpr(
257 anyOf(HasConstructExprWithValueTypeType,
258 HasBracedInitListWithValueTypeType,
259 has(cxxFunctionalCastExpr(HasConstructExprWithValueTypeType)),
260 has(cxxFunctionalCastExpr(HasBracedInitListWithValueTypeType))))
261 .bind("temporary_expr"));
262
263 Finder->addMatcher(
264 traverse(TK_AsIs, cxxMemberCallExpr(CallPushBack, has(SoughtParam),
265 unless(isInTemplateInstantiation()))
266 .bind("push_back_call")),
267 this);
268
269 Finder->addMatcher(
270 traverse(TK_AsIs, cxxMemberCallExpr(CallPush, has(SoughtParam),
271 unless(isInTemplateInstantiation()))
272 .bind("push_call")),
273 this);
274
275 Finder->addMatcher(
276 traverse(TK_AsIs, cxxMemberCallExpr(CallPushFront, has(SoughtParam),
277 unless(isInTemplateInstantiation()))
278 .bind("push_front_call")),
279 this);
280
281 Finder->addMatcher(
282 traverse(TK_AsIs,
283 cxxMemberCallExpr(
284 CallEmplacy, HasConstructExprWithValueTypeTypeAsLastArgument,
285 hasSameNumArgsAsDeclNumParams(),
286 unless(isInTemplateInstantiation()))
287 .bind("emplacy_call")),
288 this);
289
290 Finder->addMatcher(
291 traverse(TK_AsIs,
292 cxxMemberCallExpr(
293 CallEmplacy,
294 on(hasType(cxxRecordDecl(has(typedefNameDecl(
295 hasName("value_type"),
296 hasType(hasCanonicalType(recordType(hasDeclaration(
297 cxxRecordDecl(hasAnyName(SmallVector<StringRef, 2>(
298 TupleTypes.begin(), TupleTypes.end())))))))))))),
299 has(MakeTuple), hasSameNumArgsAsDeclNumParams(),
300 unless(isInTemplateInstantiation()))
301 .bind("emplacy_call")),
302 this);
303}
304
305void UseEmplaceCheck::check(const MatchFinder::MatchResult &Result) {
306 const auto *PushBackCall =
307 Result.Nodes.getNodeAs<CXXMemberCallExpr>("push_back_call");
308 const auto *PushCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("push_call");
309 const auto *PushFrontCall =
310 Result.Nodes.getNodeAs<CXXMemberCallExpr>("push_front_call");
311 const auto *EmplacyCall =
312 Result.Nodes.getNodeAs<CXXMemberCallExpr>("emplacy_call");
313 const auto *CtorCall = Result.Nodes.getNodeAs<CXXConstructExpr>("ctor");
314 const auto *MakeCall = Result.Nodes.getNodeAs<CallExpr>("make");
315 const auto *TemporaryExpr =
316 Result.Nodes.getNodeAs<MaterializeTemporaryExpr>("temporary_expr");
317
318 const CXXMemberCallExpr *Call = [&]() {
319 if (PushBackCall) {
320 return PushBackCall;
321 }
322 if (PushCall) {
323 return PushCall;
324 }
325 if (PushFrontCall) {
326 return PushFrontCall;
327 }
328 return EmplacyCall;
329 }();
330
331 assert(Call && "No call matched");
332 assert((CtorCall || MakeCall) && "No push_back parameter matched");
333
334 if (IgnoreImplicitConstructors && CtorCall && CtorCall->getNumArgs() >= 1 &&
335 CtorCall->getArg(0)->getSourceRange() == CtorCall->getSourceRange())
336 return;
337
338 const auto FunctionNameSourceRange = CharSourceRange::getCharRange(
339 Call->getExprLoc(), Call->getArg(0)->getExprLoc());
340
341 auto Diag =
342 EmplacyCall
343 ? diag(TemporaryExpr ? TemporaryExpr->getBeginLoc()
344 : CtorCall ? CtorCall->getBeginLoc()
345 : MakeCall->getBeginLoc(),
346 "unnecessary temporary object created while calling %0")
347 : diag(Call->getExprLoc(), "use emplace%select{|_back|_front}0 "
348 "instead of push%select{|_back|_front}0");
349 if (EmplacyCall)
350 Diag << Call->getMethodDecl()->getName();
351 else if (PushCall)
352 Diag << 0;
353 else if (PushBackCall)
354 Diag << 1;
355 else
356 Diag << 2;
357
358 if (FunctionNameSourceRange.getBegin().isMacroID())
359 return;
360
361 if (PushBackCall) {
362 const char *EmplacePrefix = MakeCall ? "emplace_back" : "emplace_back(";
363 Diag << FixItHint::CreateReplacement(FunctionNameSourceRange,
364 EmplacePrefix);
365 } else if (PushCall) {
366 const char *EmplacePrefix = MakeCall ? "emplace" : "emplace(";
367 Diag << FixItHint::CreateReplacement(FunctionNameSourceRange,
368 EmplacePrefix);
369 } else if (PushFrontCall) {
370 const char *EmplacePrefix = MakeCall ? "emplace_front" : "emplace_front(";
371 Diag << FixItHint::CreateReplacement(FunctionNameSourceRange,
372 EmplacePrefix);
373 }
374
375 const SourceRange CallParensRange =
376 MakeCall ? SourceRange(MakeCall->getCallee()->getEndLoc(),
377 MakeCall->getRParenLoc())
378 : CtorCall->getParenOrBraceRange();
379
380 // Finish if there is no explicit constructor call.
381 if (CallParensRange.getBegin().isInvalid())
382 return;
383
384 // FIXME: Will there ever be a CtorCall, if there is no TemporaryExpr?
385 const SourceLocation ExprBegin = TemporaryExpr ? TemporaryExpr->getExprLoc()
386 : CtorCall ? CtorCall->getExprLoc()
387 : MakeCall->getExprLoc();
388
389 // Range for constructor name and opening brace.
390 const auto ParamCallSourceRange =
391 CharSourceRange::getTokenRange(ExprBegin, CallParensRange.getBegin());
392
393 // Range for constructor closing brace and end of temporary expr.
394 const auto EndCallSourceRange = CharSourceRange::getTokenRange(
395 CallParensRange.getEnd(),
396 TemporaryExpr ? TemporaryExpr->getEndLoc() : CallParensRange.getEnd());
397
398 Diag << FixItHint::CreateRemoval(ParamCallSourceRange)
399 << FixItHint::CreateRemoval(EndCallSourceRange);
400
401 if (MakeCall && EmplacyCall) {
402 // Remove extra left parenthesis
403 Diag << FixItHint::CreateRemoval(
404 CharSourceRange::getCharRange(MakeCall->getCallee()->getEndLoc(),
405 MakeCall->getArg(0)->getBeginLoc()));
406 }
407}
408
410 Options.store(Opts, "IgnoreImplicitConstructors", IgnoreImplicitConstructors);
411 Options.store(Opts, "ContainersWithPushBack",
412 utils::options::serializeStringList(ContainersWithPushBack));
413 Options.store(Opts, "ContainersWithPush",
414 utils::options::serializeStringList(ContainersWithPush));
415 Options.store(Opts, "ContainersWithPushFront",
416 utils::options::serializeStringList(ContainersWithPushFront));
417 Options.store(Opts, "SmartPointers",
419 Options.store(Opts, "TupleTypes",
421 Options.store(Opts, "TupleMakeFunctions",
422 utils::options::serializeStringList(TupleMakeFunctions));
423 Options.store(Opts, "EmplacyFunctions",
424 utils::options::serializeStringList(EmplacyFunctions));
425}
426
427} // namespace clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
UseEmplaceCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap