clang-tools 22.0.0git
MakeSmartPtrCheck.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 "MakeSmartPtrCheck.h"
10#include "../utils/TypeTraits.h"
11#include "clang/Frontend/CompilerInstance.h"
12#include "clang/Lex/Lexer.h"
13#include "clang/Lex/Preprocessor.h"
14
15using namespace clang::ast_matchers;
16
17namespace clang::tidy::modernize {
18
19static constexpr char ConstructorCall[] = "constructorCall";
20static constexpr char DirectVar[] = "directVar";
21static constexpr char ResetCall[] = "resetCall";
22static constexpr char NewExpression[] = "newExpression";
23
24static std::string getNewExprName(const CXXNewExpr *NewExpr,
25 const SourceManager &SM,
26 const LangOptions &Lang) {
27 const StringRef WrittenName = Lexer::getSourceText(
28 CharSourceRange::getTokenRange(
29 NewExpr->getAllocatedTypeSourceInfo()->getTypeLoc().getSourceRange()),
30 SM, Lang);
31 if (NewExpr->isArray())
32 return (WrittenName + "[]").str();
33 return WrittenName.str();
34}
35
36const char MakeSmartPtrCheck::PointerType[] = "pointerType";
37
39 StringRef MakeSmartPtrFunctionName)
40 : ClangTidyCheck(Name, Context),
41 Inserter(Options.getLocalOrGlobal("IncludeStyle",
42 utils::IncludeSorter::IS_LLVM),
43 areDiagsSelfContained()),
44 MakeSmartPtrFunctionHeader(
45 Options.get("MakeSmartPtrFunctionHeader", "<memory>")),
46 MakeSmartPtrFunctionName(
47 Options.get("MakeSmartPtrFunction", MakeSmartPtrFunctionName)),
48 IgnoreMacros(Options.get("IgnoreMacros", true)),
49 IgnoreDefaultInitialization(
50 Options.get("IgnoreDefaultInitialization", true)) {}
51
53 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
54 Options.store(Opts, "MakeSmartPtrFunctionHeader", MakeSmartPtrFunctionHeader);
55 Options.store(Opts, "MakeSmartPtrFunction", MakeSmartPtrFunctionName);
56 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
57 Options.store(Opts, "IgnoreDefaultInitialization",
58 IgnoreDefaultInitialization);
59}
60
62 const LangOptions &LangOpts) const {
63 return LangOpts.CPlusPlus11;
64}
65
66void MakeSmartPtrCheck::registerPPCallbacks(const SourceManager &SM,
67 Preprocessor *PP,
68 Preprocessor *ModuleExpanderPP) {
69 Inserter.registerPreprocessor(PP);
70}
71
72void MakeSmartPtrCheck::registerMatchers(ast_matchers::MatchFinder *Finder) {
73 // Calling make_smart_ptr from within a member function of a type with a
74 // private or protected constructor would be ill-formed.
75 auto CanCallCtor = unless(has(ignoringImpCasts(
76 cxxConstructExpr(hasDeclaration(decl(unless(isPublic())))))));
77
78 auto IsPlacement = hasAnyPlacementArg(anything());
79
80 Finder->addMatcher(
81 traverse(TK_AsIs,
82 cxxConstructExpr(
83 anyOf(hasParent(cxxBindTemporaryExpr()),
84 hasParent(varDecl().bind(DirectVar))),
85 hasType(getSmartPointerTypeMatcher()), argumentCountIs(1),
86 hasArgument(
87 0, cxxNewExpr(hasType(pointsTo(qualType(hasCanonicalType(
88 equalsBoundNode(PointerType))))),
89 CanCallCtor, unless(IsPlacement))
90 .bind(NewExpression)),
91 unless(isInTemplateInstantiation()))
92 .bind(ConstructorCall)),
93 this);
94
95 Finder->addMatcher(
96 traverse(
97 TK_AsIs,
98 cxxMemberCallExpr(
99 unless(isInTemplateInstantiation()),
100 hasArgument(0, cxxNewExpr(CanCallCtor, unless(IsPlacement))
101 .bind(NewExpression)),
102 callee(cxxMethodDecl(hasName("reset"))),
103 anyOf(thisPointerType(getSmartPointerTypeMatcher()),
104 on(ignoringImplicit(anyOf(
106 hasType(pointsTo(getSmartPointerTypeMatcher())))))))
107 .bind(ResetCall)),
108 this);
109}
110
111void MakeSmartPtrCheck::check(const MatchFinder::MatchResult &Result) {
112 // 'smart_ptr' refers to 'std::shared_ptr' or 'std::unique_ptr' or other
113 // pointer, 'make_smart_ptr' refers to 'std::make_shared' or
114 // 'std::make_unique' or other function that creates smart_ptr.
115
116 SourceManager &SM = *Result.SourceManager;
117 const auto *Construct =
118 Result.Nodes.getNodeAs<CXXConstructExpr>(ConstructorCall);
119 const auto *DVar = Result.Nodes.getNodeAs<VarDecl>(DirectVar);
120 const auto *Reset = Result.Nodes.getNodeAs<CXXMemberCallExpr>(ResetCall);
121 const auto *Type = Result.Nodes.getNodeAs<QualType>(PointerType);
122 const auto *New = Result.Nodes.getNodeAs<CXXNewExpr>(NewExpression);
123
124 // Skip when this is a new-expression with `auto`, e.g. new auto(1)
125 if (New->getType()->getPointeeType()->getContainedAutoType())
126 return;
127
128 // Be conservative for cases where we construct and default initialize.
129 //
130 // For example,
131 // P.reset(new int) // check fix: P = std::make_unique<int>()
132 // P.reset(new int[5]) // check fix: P = std::make_unique<int []>(5)
133 //
134 // The fix of the check has side effect, it introduces value initialization
135 // which maybe unexpected and cause performance regression.
136 const bool Initializes = New->hasInitializer() ||
138 New->getAllocatedType(), *Result.Context);
139 if (!Initializes && IgnoreDefaultInitialization)
140 return;
141 if (Construct)
142 checkConstruct(SM, Result.Context, Construct, DVar, Type, New);
143 else if (Reset)
144 checkReset(SM, Result.Context, Reset, New);
145}
146
147void MakeSmartPtrCheck::checkConstruct(SourceManager &SM, ASTContext *Ctx,
148 const CXXConstructExpr *Construct,
149 const VarDecl *DVar,
150 const QualType *Type,
151 const CXXNewExpr *New) {
152 const SourceLocation ConstructCallStart = Construct->getExprLoc();
153 const bool InMacro = ConstructCallStart.isMacroID();
154
155 if (InMacro && IgnoreMacros)
156 return;
157
158 bool Invalid = false;
159 const StringRef ExprStr = Lexer::getSourceText(
160 CharSourceRange::getCharRange(
161 ConstructCallStart, Construct->getParenOrBraceRange().getBegin()),
162 SM, getLangOpts(), &Invalid);
163 if (Invalid)
164 return;
165
166 auto Diag = diag(ConstructCallStart, "use %0 instead")
167 << MakeSmartPtrFunctionName;
168
169 // Disable the fix in macros.
170 if (InMacro)
171 return;
172
173 if (!replaceNew(Diag, New, SM, Ctx))
174 return;
175
176 // Find the location of the template's left angle.
177 const size_t LAngle = ExprStr.find('<');
178 SourceLocation ConstructCallEnd;
179 if (LAngle == StringRef::npos) {
180 // If the template argument is missing (because it is part of the alias)
181 // we have to add it back.
182 ConstructCallEnd = ConstructCallStart.getLocWithOffset(ExprStr.size());
183 Diag << FixItHint::CreateInsertion(
184 ConstructCallEnd, "<" + getNewExprName(New, SM, getLangOpts()) + ">");
185 } else {
186 ConstructCallEnd = ConstructCallStart.getLocWithOffset(LAngle);
187 }
188
189 std::string FinalMakeSmartPtrFunctionName = MakeSmartPtrFunctionName.str();
190 if (DVar)
191 FinalMakeSmartPtrFunctionName =
192 ExprStr.str() + " = " + MakeSmartPtrFunctionName.str();
193
194 Diag << FixItHint::CreateReplacement(
195 CharSourceRange::getCharRange(ConstructCallStart, ConstructCallEnd),
196 FinalMakeSmartPtrFunctionName);
197
198 // If the smart_ptr is built with brace enclosed direct initialization, use
199 // parenthesis instead.
200 if (Construct->isListInitialization()) {
201 const SourceRange BraceRange = Construct->getParenOrBraceRange();
202 Diag << FixItHint::CreateReplacement(
203 CharSourceRange::getCharRange(
204 BraceRange.getBegin(), BraceRange.getBegin().getLocWithOffset(1)),
205 "(");
206 Diag << FixItHint::CreateReplacement(
207 CharSourceRange::getCharRange(BraceRange.getEnd(),
208 BraceRange.getEnd().getLocWithOffset(1)),
209 ")");
210 }
211
212 insertHeader(Diag, SM.getFileID(ConstructCallStart));
213}
214
215void MakeSmartPtrCheck::checkReset(SourceManager &SM, ASTContext *Ctx,
216 const CXXMemberCallExpr *Reset,
217 const CXXNewExpr *New) {
218 const auto *Expr = cast<MemberExpr>(Reset->getCallee());
219 const SourceLocation OperatorLoc = Expr->getOperatorLoc();
220 const SourceLocation ResetCallStart = Reset->getExprLoc();
221 const SourceLocation ExprStart = Expr->getBeginLoc();
222 const SourceLocation ExprEnd =
223 Lexer::getLocForEndOfToken(Expr->getEndLoc(), 0, SM, getLangOpts());
224
225 const bool InMacro = ExprStart.isMacroID();
226
227 if (InMacro && IgnoreMacros)
228 return;
229
230 // There are some cases where we don't have operator ("." or "->") of the
231 // "reset" expression, e.g. call "reset()" method directly in the subclass of
232 // "std::unique_ptr<>". We skip these cases.
233 if (OperatorLoc.isInvalid())
234 return;
235
236 auto Diag = diag(ResetCallStart, "use %0 instead")
237 << MakeSmartPtrFunctionName;
238
239 // Disable the fix in macros.
240 if (InMacro)
241 return;
242
243 if (!replaceNew(Diag, New, SM, Ctx))
244 return;
245
246 Diag << FixItHint::CreateReplacement(
247 CharSourceRange::getCharRange(OperatorLoc, ExprEnd),
248 (llvm::Twine(" = ") + MakeSmartPtrFunctionName + "<" +
249 getNewExprName(New, SM, getLangOpts()) + ">")
250 .str());
251
252 if (Expr->isArrow())
253 Diag << FixItHint::CreateInsertion(ExprStart, "*");
254
255 insertHeader(Diag, SM.getFileID(OperatorLoc));
256}
257
258bool MakeSmartPtrCheck::replaceNew(DiagnosticBuilder &Diag,
259 const CXXNewExpr *New, SourceManager &SM,
260 ASTContext *Ctx) {
261 auto SkipParensParents = [&](const Expr *E) {
262 const TraversalKindScope RAII(*Ctx, TK_AsIs);
263
264 for (const Expr *OldE = nullptr; E != OldE;) {
265 OldE = E;
266 for (const auto &Node : Ctx->getParents(*E)) {
267 if (const Expr *Parent = Node.get<ParenExpr>()) {
268 E = Parent;
269 break;
270 }
271 }
272 }
273 return E;
274 };
275
276 const SourceRange NewRange = SkipParensParents(New)->getSourceRange();
277 const SourceLocation NewStart = NewRange.getBegin();
278 const SourceLocation NewEnd = NewRange.getEnd();
279
280 // Skip when the source location of the new expression is invalid.
281 if (NewStart.isInvalid() || NewEnd.isInvalid())
282 return false;
283
284 std::string ArraySizeExpr;
285 if (const auto *ArraySize = New->getArraySize().value_or(nullptr)) {
286 ArraySizeExpr = Lexer::getSourceText(CharSourceRange::getTokenRange(
287 ArraySize->getSourceRange()),
288 SM, getLangOpts())
289 .str();
290 }
291 // Returns true if the given constructor expression has any braced-init-list
292 // argument, e.g.
293 // Foo({1, 2}, 1) => true
294 // Foo(Bar{1, 2}) => true
295 // Foo(1) => false
296 // Foo{1} => false
297 auto HasListIntializedArgument = [](const CXXConstructExpr *CE) {
298 for (const auto *Arg : CE->arguments()) {
299 Arg = Arg->IgnoreImplicit();
300
301 if (isa<CXXStdInitializerListExpr>(Arg) || isa<InitListExpr>(Arg))
302 return true;
303 // Check whether we implicitly construct a class from a
304 // std::initializer_list.
305 if (const auto *CEArg = dyn_cast<CXXConstructExpr>(Arg)) {
306 // Strip the elidable move constructor, it is present in the AST for
307 // C++11/14, e.g. Foo(Bar{1, 2}), the move constructor is around the
308 // init-list constructor.
309 if (CEArg->isElidable()) {
310 if (const auto *TempExp = CEArg->getArg(0)) {
311 if (const auto *UnwrappedCE =
312 dyn_cast<CXXConstructExpr>(TempExp->IgnoreImplicit()))
313 CEArg = UnwrappedCE;
314 }
315 }
316 if (CEArg->isStdInitListInitialization())
317 return true;
318 }
319 }
320 return false;
321 };
322 switch (New->getInitializationStyle()) {
323 case CXXNewInitializationStyle::None: {
324 if (ArraySizeExpr.empty()) {
325 Diag << FixItHint::CreateRemoval(SourceRange(NewStart, NewEnd));
326 } else {
327 // New array expression without written initializer:
328 // smart_ptr<Foo[]>(new Foo[5]);
329 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd),
330 ArraySizeExpr);
331 }
332 break;
333 }
334 case CXXNewInitializationStyle::Parens: {
335 // FIXME: Add fixes for constructors with parameters that can be created
336 // with a C++11 braced-init-list (e.g. std::vector, std::map).
337 // Unlike ordinal cases, braced list can not be deduced in
338 // std::make_smart_ptr, we need to specify the type explicitly in the fixes:
339 // struct S { S(std::initializer_list<int>, int); };
340 // struct S2 { S2(std::vector<int>); };
341 // struct S3 { S3(S2, int); };
342 // smart_ptr<S>(new S({1, 2, 3}, 1)); // C++98 call-style initialization
343 // smart_ptr<S>(new S({}, 1));
344 // smart_ptr<S2>(new S2({1})); // implicit conversion:
345 // // std::initializer_list => std::vector
346 // smart_ptr<S3>(new S3({1, 2}, 3));
347 // The above samples have to be replaced with:
348 // std::make_smart_ptr<S>(std::initializer_list<int>({1, 2, 3}), 1);
349 // std::make_smart_ptr<S>(std::initializer_list<int>({}), 1);
350 // std::make_smart_ptr<S2>(std::vector<int>({1}));
351 // std::make_smart_ptr<S3>(S2{1, 2}, 3);
352 if (const auto *CE = New->getConstructExpr()) {
353 if (HasListIntializedArgument(CE))
354 return false;
355 }
356 if (ArraySizeExpr.empty()) {
357 const SourceRange InitRange = New->getDirectInitRange();
358 Diag << FixItHint::CreateRemoval(
359 SourceRange(NewStart, InitRange.getBegin()));
360 Diag << FixItHint::CreateRemoval(SourceRange(InitRange.getEnd(), NewEnd));
361 } else {
362 // New array expression with default/value initialization:
363 // smart_ptr<Foo[]>(new int[5]());
364 // smart_ptr<Foo[]>(new Foo[5]());
365 Diag << FixItHint::CreateReplacement(SourceRange(NewStart, NewEnd),
366 ArraySizeExpr);
367 }
368 break;
369 }
370 case CXXNewInitializationStyle::Braces: {
371 // Range of the substring that we do not want to remove.
372 SourceRange InitRange;
373 if (const auto *NewConstruct = New->getConstructExpr()) {
374 if (NewConstruct->isStdInitListInitialization() ||
375 HasListIntializedArgument(NewConstruct)) {
376 // FIXME: Add fixes for direct initialization with the initializer-list
377 // constructor. Similar to the above CallInit case, the type has to be
378 // specified explicitly in the fixes.
379 // struct S { S(std::initializer_list<int>); };
380 // struct S2 { S2(S, int); };
381 // smart_ptr<S>(new S{1, 2, 3}); // C++11 direct list-initialization
382 // smart_ptr<S>(new S{}); // use initializer-list constructor
383 // smart_ptr<S2>()new S2{ {1,2}, 3 }; // have a list-initialized arg
384 // The above cases have to be replaced with:
385 // std::make_smart_ptr<S>(std::initializer_list<int>({1, 2, 3}));
386 // std::make_smart_ptr<S>(std::initializer_list<int>({}));
387 // std::make_smart_ptr<S2>(S{1, 2}, 3);
388 return false;
389 }
390 // Direct initialization with ordinary constructors.
391 // struct S { S(int x); S(); };
392 // smart_ptr<S>(new S{5});
393 // smart_ptr<S>(new S{}); // use default constructor
394 // The arguments in the initialization list are going to be forwarded to
395 // the constructor, so this has to be replaced with:
396 // std::make_smart_ptr<S>(5);
397 // std::make_smart_ptr<S>();
398 InitRange = SourceRange(
399 NewConstruct->getParenOrBraceRange().getBegin().getLocWithOffset(1),
400 NewConstruct->getParenOrBraceRange().getEnd().getLocWithOffset(-1));
401 } else {
402 // Aggregate initialization.
403 // smart_ptr<Pair>(new Pair{first, second});
404 // Has to be replaced with:
405 // smart_ptr<Pair>(Pair{first, second});
406 //
407 // The fix (std::make_unique) needs to see copy/move constructor of
408 // Pair. If we found any invisible or deleted copy/move constructor, we
409 // stop generating fixes -- as the C++ rule is complicated and we are less
410 // certain about the correct fixes.
411 if (const CXXRecordDecl *RD = New->getType()->getPointeeCXXRecordDecl()) {
412 if (llvm::any_of(RD->ctors(), [](const CXXConstructorDecl *Ctor) {
413 return Ctor->isCopyOrMoveConstructor() &&
414 (Ctor->isDeleted() || Ctor->getAccess() == AS_private);
415 })) {
416 return false;
417 }
418 }
419 InitRange = SourceRange(
420 New->getAllocatedTypeSourceInfo()->getTypeLoc().getBeginLoc(),
421 New->getInitializer()->getSourceRange().getEnd());
422 }
423 Diag << FixItHint::CreateRemoval(
424 CharSourceRange::getCharRange(NewStart, InitRange.getBegin()));
425 Diag << FixItHint::CreateRemoval(
426 SourceRange(InitRange.getEnd().getLocWithOffset(1), NewEnd));
427 break;
428 }
429 }
430 return true;
431}
432
433void MakeSmartPtrCheck::insertHeader(DiagnosticBuilder &Diag, FileID FD) {
434 if (MakeSmartPtrFunctionHeader.empty())
435 return;
436 Diag << Inserter.createIncludeInsertion(FD, MakeSmartPtrFunctionHeader);
437}
438
439} // namespace clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
virtual SmartPtrTypeMatcher getSmartPointerTypeMatcher() const =0
Returns matcher that match with different smart pointer types.
MakeSmartPtrCheck(StringRef Name, ClangTidyContext *Context, StringRef MakeSmartPtrFunctionName)
void check(const ast_matchers::MatchFinder::MatchResult &Result) final
bool isLanguageVersionSupported(const LangOptions &LangOpts) const override
Returns whether the C++ version is compatible with current check.
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) final
static std::string getNewExprName(const CXXNewExpr *NewExpr, const SourceManager &SM, const LangOptions &Lang)
static constexpr char ResetCall[]
static constexpr char NewExpression[]
static constexpr char DirectVar[]
static constexpr char ConstructorCall[]
bool isTriviallyDefaultConstructible(QualType Type, const ASTContext &Context)
Returns true if Type is trivially default constructible.
llvm::StringMap< ClangTidyValue > OptionMap