NewDeleteOverloadsCheck.cpp 7.2 KB

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