Debian Codegraph @

src/checks/manuallevel/heap-allocated-small-trivial-type.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2019 Sergio Martins <[email protected]>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #include "heap-allocated-small-trivial-type.h"
8 #include "ClazyContext.h"
9 #include "QtUtils.h"
10 #include "StmtBodyRange.h"
11 #include "TypeUtils.h"
12 #include "Utils.h"
13
14 #include <clang/AST/AST.h>
15
16 using namespace clang;
17
18 void HeapAllocatedSmallTrivialType::VisitDecl(clang::Decl *decl)
19 {
20 auto *varDecl = dyn_cast<VarDecl>(decl);
21 if (!varDecl) {
22 return;
23 }
24
25 Expr *init = varDecl->getInit();
26 if (!init) {
27 return;
28 }
29
30 auto *newExpr = dyn_cast<CXXNewExpr>(init);
31 if (!newExpr || newExpr->getNumPlacementArgs() > 0) { // Placement new, user probably knows what he's doing
32 return;
33 }
34
35 if (newExpr->isArray()) {
36 return;
37 }
38
39 DeclContext *context = varDecl->getDeclContext();
40 FunctionDecl *fDecl = context ? dyn_cast<FunctionDecl>(context) : nullptr;
41 if (!fDecl) {
42 return;
43 }
44
45 QualType qualType = newExpr->getType()->getPointeeType();
46 if (clazy::isSmallTrivial(m_context, qualType)) {
47 if (clazy::contains(qualType.getAsString(), "Private")) {
48 // Possibly a pimpl, forward declared in header
49 return;
50 }
51
52 auto *body = fDecl->getBody();
53 if (Utils::isAssignedTo(body, varDecl) || Utils::isPassedToFunction(StmtBodyRange(body), varDecl, false) || Utils::isReturned(body, varDecl)) {
54 return;
55 }
56
57 emitWarning(init, "Don't heap-allocate small trivially copyable/destructible types: " + qualType.getAsString(lo()));
58 }
59 }