10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Basic/TargetInfo.h"
20 cxxNewExpr(unless(hasAnyPlacementArg(anything()))).bind(
"new"),
this);
24 const MatchFinder::MatchResult &Result) {
26 const auto *NewExpr = Result.Nodes.getNodeAs<CXXNewExpr>(
"new");
28 QualType T = NewExpr->getAllocatedType();
30 if (T->isDependentType())
32 const TagDecl *D = T->getAsTagDecl();
34 if (!D || !D->getDefinition() || !D->isCompleteDefinition())
37 ASTContext &Context = D->getASTContext();
40 if (!Context.isAlignmentRequired(T))
44 unsigned SpecifiedAlignment = D->getMaxAlignment();
46 if (!SpecifiedAlignment)
49 unsigned DefaultNewAlignment = Context.getTargetInfo().getNewAlign();
51 bool OverAligned = SpecifiedAlignment > DefaultNewAlignment;
52 bool HasDefaultOperatorNew =
53 !NewExpr->getOperatorNew() || NewExpr->getOperatorNew()->isImplicit();
55 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
56 if (HasDefaultOperatorNew && OverAligned)
57 diag(NewExpr->getBeginLoc(),
58 "allocation function returns a pointer with alignment %0 but the "
59 "over-aligned type being allocated requires alignment %1")
60 << (DefaultNewAlignment / CharWidth)
61 << (SpecifiedAlignment / CharWidth);
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.