clang-tools 22.0.0git
DefaultOperatorNewOnOveralignedTypeCheck.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#include "clang/Basic/TargetInfo.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang::tidy::bugprone {
17
19 MatchFinder *Finder) {
20 Finder->addMatcher(
21 cxxNewExpr(unless(hasAnyPlacementArg(anything()))).bind("new"), this);
22}
23
25 const MatchFinder::MatchResult &Result) {
26 // Get the found 'new' expression.
27 const auto *NewExpr = Result.Nodes.getNodeAs<CXXNewExpr>("new");
28
29 const QualType T = NewExpr->getAllocatedType();
30 // Dependent types do not have fixed alignment.
31 if (T->isDependentType())
32 return;
33 const TagDecl *D = T->getAsTagDecl();
34 // Alignment can not be obtained for undefined type.
35 if (!D || !D->isCompleteDefinition())
36 return;
37
38 const ASTContext &Context = D->getASTContext();
39
40 // Check if no alignment was specified for the type.
41 if (!Context.isAlignmentRequired(T))
42 return;
43
44 // The user-specified alignment (in bits).
45 const unsigned SpecifiedAlignment = D->getMaxAlignment();
46 // Double-check if no alignment was specified.
47 if (!SpecifiedAlignment)
48 return;
49 // The alignment used by default 'operator new' (in bits).
50 const unsigned DefaultNewAlignment = Context.getTargetInfo().getNewAlign();
51
52 const bool OverAligned = SpecifiedAlignment > DefaultNewAlignment;
53 const bool HasDefaultOperatorNew =
54 !NewExpr->getOperatorNew() || NewExpr->getOperatorNew()->isImplicit();
55
56 const unsigned CharWidth = Context.getTargetInfo().getCharWidth();
57 if (HasDefaultOperatorNew && OverAligned)
58 diag(NewExpr->getBeginLoc(),
59 "allocation function returns a pointer with alignment %0 but the "
60 "over-aligned type being allocated requires alignment %1")
61 << (DefaultNewAlignment / CharWidth)
62 << (SpecifiedAlignment / CharWidth);
63}
64
65} // namespace clang::tidy::bugprone
void check(const ast_matchers::MatchFinder::MatchResult &Result) override