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