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 ASTContext &Ctx = Node.getASTContext();
55 if (Ctx.getLangOpts().SizedDeallocation &&
56 Ctx.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 for (const auto &BS : RD->bases()) {
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 auto *BaseRD = BS.getType()->getAsCXXRecordDecl())
124 return true;
125 }
126
127 return false;
128}
129
131 // Match all operator new and operator delete overloads (including the array
132 // forms). Do not match implicit operators, placement operators, or
133 // deleted/private operators.
134 //
135 // Technically, trivially-defined operator delete seems like a reasonable
136 // thing to also skip. e.g., void operator delete(void *) {}
137 // However, I think it's more reasonable to warn in this case as the user
138 // should really be writing that as a deleted function.
139 Finder->addMatcher(
140 functionDecl(unless(anyOf(isImplicit(), isPlacementOverload(),
141 isDeleted(), cxxMethodDecl(isPrivate()))),
142 anyOf(hasOverloadedOperatorName("new"),
143 hasOverloadedOperatorName("new[]"),
144 hasOverloadedOperatorName("delete"),
145 hasOverloadedOperatorName("delete[]")))
146 .bind("func"),
147 this);
148}
149
150void NewDeleteOverloadsCheck::check(const MatchFinder::MatchResult &Result) {
151 // Add any matches we locate to the list of things to be checked at the
152 // end of the translation unit.
153 const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func");
154 const CXXRecordDecl *RD = nullptr;
155 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
156 RD = MD->getParent();
157 Overloads[RD].push_back(FD);
158}
159
161 // Walk over the list of declarations we've found to see if there is a
162 // corresponding overload at the same declaration context or within a base
163 // class. If there is not, add the element to the list of declarations to
164 // diagnose.
165 SmallVector<const FunctionDecl *, 4> Diagnose;
166 for (const auto &RP : Overloads) {
167 // We don't care about the CXXRecordDecl key in the map; we use it as a way
168 // to shard the overloads by declaration context to reduce the algorithmic
169 // complexity when searching for corresponding free store functions.
170 for (const auto *Overload : RP.second) {
171 const auto *Match =
172 llvm::find_if(RP.second, [&Overload](const FunctionDecl *FD) {
173 if (FD == Overload)
174 return false;
175 // If the declaration contexts don't match, we don't
176 // need to check any further.
177 if (FD->getDeclContext() != Overload->getDeclContext())
178 return false;
179
180 // Since the declaration contexts match, see whether
181 // the current element is the corresponding operator.
182 if (!areCorrespondingOverloads(Overload, FD))
183 return false;
184
185 return true;
186 });
187
188 if (Match == RP.second.end()) {
189 // Check to see if there is a corresponding overload in a base class
190 // context. If there isn't, or if the overload is not a class member
191 // function, then we should diagnose.
192 const auto *MD = dyn_cast<CXXMethodDecl>(Overload);
194 Diagnose.push_back(Overload);
195 }
196 }
197 }
198
199 for (const auto *FD : Diagnose)
200 diag(FD->getLocation(), "declaration of %0 has no matching declaration "
201 "of '%1' at the same scope")
203}
204
205} // 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)