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 
10 #include "NewDeleteOverloadsCheck.h"
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 
AST_MATCHER(FunctionDecl,isPlacementOverload)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 
getCorrespondingOverload(const FunctionDecl * FD)65 OverloadedOperatorKind getCorrespondingOverload(const FunctionDecl *FD) {
66   switch (FD->getOverloadedOperator()) {
67   default:
68     break;
69   case OO_New:
70     return OO_Delete;
71   case OO_Delete:
72     return OO_New;
73   case OO_Array_New:
74     return OO_Array_Delete;
75   case OO_Array_Delete:
76     return OO_Array_New;
77   }
78   llvm_unreachable("Not an overloaded allocation operator");
79 }
80 
getOperatorName(OverloadedOperatorKind K)81 const char *getOperatorName(OverloadedOperatorKind K) {
82   switch (K) {
83   default:
84     break;
85   case OO_New:
86     return "operator new";
87   case OO_Delete:
88     return "operator delete";
89   case OO_Array_New:
90     return "operator new[]";
91   case OO_Array_Delete:
92     return "operator delete[]";
93   }
94   llvm_unreachable("Not an overloaded allocation operator");
95 }
96 
areCorrespondingOverloads(const FunctionDecl * LHS,const FunctionDecl * RHS)97 bool areCorrespondingOverloads(const FunctionDecl *LHS,
98                                const FunctionDecl *RHS) {
99   return RHS->getOverloadedOperator() == getCorrespondingOverload(LHS);
100 }
101 
hasCorrespondingOverloadInBaseClass(const CXXMethodDecl * MD,const CXXRecordDecl * RD=nullptr)102 bool hasCorrespondingOverloadInBaseClass(const CXXMethodDecl *MD,
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 &&
108           areCorrespondingOverloads(MD, BMD))
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())
123       if (hasCorrespondingOverloadInBaseClass(MD, BaseRD))
124         return true;
125   }
126 
127   return false;
128 }
129 
130 } // anonymous namespace
131 
registerMatchers(MatchFinder * Finder)132 void NewDeleteOverloadsCheck::registerMatchers(MatchFinder *Finder) {
133   if (!getLangOpts().CPlusPlus)
134     return;
135 
136   // Match all operator new and operator delete overloads (including the array
137   // forms). Do not match implicit operators, placement operators, or
138   // deleted/private operators.
139   //
140   // Technically, trivially-defined operator delete seems like a reasonable
141   // thing to also skip. e.g., void operator delete(void *) {}
142   // However, I think it's more reasonable to warn in this case as the user
143   // should really be writing that as a deleted function.
144   Finder->addMatcher(
145       functionDecl(unless(anyOf(isImplicit(), isPlacementOverload(),
146                                 isDeleted(), cxxMethodDecl(isPrivate()))),
147                    anyOf(hasOverloadedOperatorName("new"),
148                          hasOverloadedOperatorName("new[]"),
149                          hasOverloadedOperatorName("delete"),
150                          hasOverloadedOperatorName("delete[]")))
151           .bind("func"),
152       this);
153 }
154 
check(const MatchFinder::MatchResult & Result)155 void NewDeleteOverloadsCheck::check(const MatchFinder::MatchResult &Result) {
156   // Add any matches we locate to the list of things to be checked at the
157   // end of the translation unit.
158   const auto *FD = Result.Nodes.getNodeAs<FunctionDecl>("func");
159   const CXXRecordDecl *RD = nullptr;
160   if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
161     RD = MD->getParent();
162   Overloads[RD].push_back(FD);
163 }
164 
onEndOfTranslationUnit()165 void NewDeleteOverloadsCheck::onEndOfTranslationUnit() {
166   // Walk over the list of declarations we've found to see if there is a
167   // corresponding overload at the same declaration context or within a base
168   // class. If there is not, add the element to the list of declarations to
169   // diagnose.
170   SmallVector<const FunctionDecl *, 4> Diagnose;
171   for (const auto &RP : Overloads) {
172     // We don't care about the CXXRecordDecl key in the map; we use it as a way
173     // to shard the overloads by declaration context to reduce the algorithmic
174     // complexity when searching for corresponding free store functions.
175     for (const auto *Overload : RP.second) {
176       const auto *Match =
177           std::find_if(RP.second.begin(), RP.second.end(),
178                        [&Overload](const FunctionDecl *FD) {
179                          if (FD == Overload)
180                            return false;
181                          // If the declaration contexts don't match, we don't
182                          // need to check any further.
183                          if (FD->getDeclContext() != Overload->getDeclContext())
184                            return false;
185 
186                          // Since the declaration contexts match, see whether
187                          // the current element is the corresponding operator.
188                          if (!areCorrespondingOverloads(Overload, FD))
189                            return false;
190 
191                          return true;
192                        });
193 
194       if (Match == RP.second.end()) {
195         // Check to see if there is a corresponding overload in a base class
196         // context. If there isn't, or if the overload is not a class member
197         // function, then we should diagnose.
198         const auto *MD = dyn_cast<CXXMethodDecl>(Overload);
199         if (!MD || !hasCorrespondingOverloadInBaseClass(MD))
200           Diagnose.push_back(Overload);
201       }
202     }
203   }
204 
205   for (const auto *FD : Diagnose)
206     diag(FD->getLocation(), "declaration of %0 has no matching declaration "
207                             "of '%1' at the same scope")
208         << FD << getOperatorName(getCorrespondingOverload(FD));
209 }
210 
211 } // namespace misc
212 } // namespace tidy
213 } // namespace clang
214