Debian Codegraph @

src/checks/manuallevel/container-inside-loop.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2016 Sergio Martins <[email protected]>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #include "container-inside-loop.h"
8 #include "ClazyContext.h"
9 #include "LoopUtils.h"
10 #include "StmtBodyRange.h"
11 #include "StringUtils.h"
12 #include "Utils.h"
13 #include "clazy_stl.h"
14
15 #include <clang/AST/Decl.h>
16 #include <clang/AST/ExprCXX.h>
17 #include <clang/AST/ParentMap.h>
18 #include <clang/AST/Stmt.h>
19 #include <clang/Basic/LLVM.h>
20 #include <llvm/Support/Casting.h>
21
22 using namespace clang;
23
24 void ContainerInsideLoop::VisitStmt(clang::Stmt *stmt)
25 {
26 auto *ctorExpr = dyn_cast<CXXConstructExpr>(stmt);
27 if (!ctorExpr) {
28 return;
29 }
30
31 CXXConstructorDecl *ctor = ctorExpr->getConstructor();
32 if (!ctor || !clazy::equalsAny(clazy::classNameFor(ctor), {"QVector", "std::vector", "QList"})) {
33 return;
34 }
35
36 auto *declStm = dyn_cast_or_null<DeclStmt>(m_context->parentMap->getParent(stmt));
37 if (!declStm || !declStm->isSingleDecl()) {
38 return;
39 }
40
41 Stmt *loopStmt = clazy::isInLoop(m_context->parentMap, stmt);
42 if (!loopStmt) {
43 return;
44 }
45
46 auto *varDecl = dyn_cast<VarDecl>(declStm->getSingleDecl());
47 if (!varDecl || Utils::isInitializedExternally(varDecl)) {
48 return;
49 }
50
51 if (Utils::isPassedToFunction(StmtBodyRange(loopStmt), varDecl, true)) {
52 return;
53 }
54
55 emitWarning(stmt->getBeginLoc(), "container inside loop causes unneeded allocations");
56 }