clang-tools 22.0.0git
NewDeleteOverloadsCheck.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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::misc {
16
17namespace {
18
19AST_MATCHER(FunctionDecl, isPlacementOverload) {
20 bool New = false;
21 switch (Node.getOverloadedOperator()) {
22 default:
23 return false;
24 case OO_New:
25 case OO_Array_New:
26 New = true;
27 break;
28 case OO_Delete:
29 case OO_Array_Delete:
30 New = false;
31 break;
32 }
33
34 // Variadic functions are always placement functions.
35 if (Node.isVariadic())
36 return true;
37
38 // Placement new is easy: it always has more than one parameter (the first
39 // parameter is always the size). If it's an overload of delete or delete[]
40 // that has only one parameter, it's never a placement delete.
41 if (New)
42 return Node.getNumParams() > 1;
43 if (Node.getNumParams() == 1)
44 return false;
45
46 // Placement delete is a little more challenging. They always have more than
47 // one parameter with the first parameter being a pointer. However, the
48 // second parameter can be a size_t for sized deallocation, and that is never
49 // a placement delete operator.
50 if (Node.getNumParams() <= 1 || Node.getNumParams() > 2)
51 return true;
52
53 const auto *FPT = Node.getType()->castAs<FunctionProtoType>();
54 const ASTContext &Ctx = Node.getASTContext();
55 if (Ctx.getLangOpts().SizedDeallocation &&
56 ASTContext::hasSameType(FPT->getParamType(1), Ctx.getSizeType()))
57 return false;
58
59 return true;
60}
61
62} // namespace
63
64static OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) {
65 switch (FD->getOverloadedOperator()) {
66 default:
67 break;
68 case OO_New:
69 return OO_Delete;
70 case OO_Delete:
71 return OO_New;
72 case OO_Array_New:
73 return OO_Array_Delete;
74 case OO_Array_Delete:
75 return OO_Array_New;
76 }
77 llvm_unreachable("Not an overloaded allocation operator");
78}
79
80static const char *getOperatorName(OverloadedOperatorKind K) {
81 switch (K) {
82 default:
83 break;
84 case OO_New:
85 return "operator new";
86 case OO_Delete:
87 return "operator delete";
88 case OO_Array_New:
89 return "operator new[]";
90 case OO_Array_Delete:
91 return "operator delete[]";
92 }
93 llvm_unreachable("Not an overloaded allocation operator");
94}
95
96static bool areCorrespondingOverloads(const FunctionDecl *LHS,
97 const FunctionDecl *RHS) {
98 return RHS->getOverloadedOperator() == getCorrespondingOverload(LHS);
99}
100
101static bool
103 const CXXRecordDecl *RD = nullptr) {
104 if (RD) {
105 // Check the methods in the given class and accessible to derived classes.
106 for (const auto *BMD : RD->methods())
107 if (BMD->isOverloadedOperator() && BMD->getAccess() != AS_private &&
109 return true;
110 } else {
111 // Get the parent class of the method; we do not need to care about checking
112 // the methods in this class as the caller has already done that by looking
113 // at the declaration contexts.
114 RD = MD->getParent();
115 }
116
117 return llvm::any_of(RD->bases(), [&](const CXXBaseSpecifier &BS) {
118 // We can't say much about a dependent base class, but to avoid false
119 // positives assume it can have a corresponding overload.
120 if (BS.getType()->isDependentType())
121 return true;
122 if (const CXXRecordDecl *BaseRD = BS.getType()->getAsCXXRecordDecl())
123 return hasCorrespondingOverloadInBaseClass(MD, BaseRD);
124 return false;
125 });
126}
127
129 // Match all operator new and operator delete overloads (including the array
130 // forms). Do not match implicit operators, placement operators, or
131 // deleted/private operators.
132 //
133 // Technically, trivially-defined operator delete seems like a reasonable
134 // thing to also skip. e.g., void operator delete(void *) {}
135 // However, I think it's more reasonable to warn in this case as the user
136 // should really be writing that as a deleted function.
137 Finder->addMatcher(
138 functionDecl(unless(anyOf(isImplicit(), isPlacementOverload(),
139 isDeleted(), cxxMethodDecl(isPrivate()))),
140 anyOf(hasOverloadedOperatorName("new"),
141 hasOverloadedOperatorName("new[]"),
142 hasOverloadedOperatorName("delete"),
143 hasOverloadedOperatorName("delete[]")))
144 .bind("func"),
145 this);
146}
147
148void NewDeleteOverloadsCheck::check(const MatchFinder::MatchResult &Result) {
149 // Add any matches we locate to the list of things to be checked at the
150 // end of the translation unit.
151 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func");
152 const CXXRecordDecl *RD = nullptr;
153 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
154 RD = MD->getParent();
155 Overloads[RD].push_back(FD);
156}
157
159 // Walk over the list of declarations we've found to see if there is a
160 // corresponding overload at the same declaration context or within a base
161 // class. If there is not, add the element to the list of declarations to
162 // diagnose.
163 SmallVector<const FunctionDecl *, 4> Diagnose;
164 for (const auto &RP : Overloads) {
165 // We don't care about the CXXRecordDecl key in the map; we use it as a way
166 // to shard the overloads by declaration context to reduce the algorithmic
167 // complexity when searching for corresponding free store functions.
168 for (const auto *Overload : RP.second) {
169 const auto *Match =
170 llvm::find_if(RP.second, [&Overload](const FunctionDecl *FD) {
171 if (FD == Overload)
172 return false;
173 // If the declaration contexts don't match, we don't
174 // need to check any further.
175 if (FD->getDeclContext() != Overload->getDeclContext())
176 return false;
177
178 // Since the declaration contexts match, see whether
179 // the current element is the corresponding operator.
180 if (!areCorrespondingOverloads(Overload, FD))
181 return false;
182
183 return true;
184 });
185
186 if (Match == RP.second.end()) {
187 // Check to see if there is a corresponding overload in a base class
188 // context. If there isn't, or if the overload is not a class member
189 // function, then we should diagnose.
190 const auto *MD = dyn_cast<CXXMethodDecl>(Overload);
192 Diagnose.push_back(Overload);
193 }
194 }
195 }
196
197 for (const auto *FD : Diagnose)
198 diag(FD->getLocation(), "declaration of %0 has no matching declaration "
199 "of '%1' at the same scope")
201}
202
203} // namespace clang::tidy::misc
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
static bool areCorrespondingOverloads(const FunctionDecl *LHS, const FunctionDecl *RHS)
static OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD)
static bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD, const CXXRecordDecl *RD=nullptr)
static const char * getOperatorName(OverloadedOperatorKind K)