Debian Codegraph @

src/checks/level1/foreach.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2015 Klarälvdalens Datakonsult AB a KDAB Group company [email protected]
3 SPDX-FileContributor: Sérgio Martins <[email protected]>
4
5 SPDX-FileCopyrightText: 2015 Sergio Martins <[email protected]>
6
7 SPDX-License-Identifier: LGPL-2.0-or-later
8 */
9
10 #include "foreach.h"
11 #include "ClazyContext.h"
12 #include "HierarchyUtils.h"
13 #include "PreProcessorVisitor.h"
14 #include "QtUtils.h"
15 #include "StringUtils.h"
16 #include "TypeUtils.h"
17 #include "Utils.h"
18 #include "clazy_stl.h"
19
20 #include <clang/AST/Decl.h>
21 #include <clang/AST/DeclCXX.h>
22 #include <clang/AST/Expr.h>
23 #include <clang/AST/ExprCXX.h>
24 #include <clang/AST/Stmt.h>
25 #include <clang/AST/Type.h>
26 #include <clang/Basic/LLVM.h>
27 #include <llvm/ADT/StringRef.h>
28 #include <llvm/Support/Casting.h>
29
30 #include <unordered_map>
31 #include <vector>
32
33 using namespace clang;
34
35 void Foreach::VisitStmt(clang::Stmt *stmt)
36 {
37 const PreProcessorVisitor *preProcessorVisitor = m_context->preprocessorVisitor;
38 if (!preProcessorVisitor || preProcessorVisitor->qtVersion() >= 50900) {
39 // Disabled since 5.9 because the Q_FOREACH internals changed.
40 // Not worth fixing it because range-loop is recommended
41 return;
42 }
43
44 auto *forStm = dyn_cast<ForStmt>(stmt);
45 if (forStm) {
46 m_lastForStmt = forStm;
47 return;
48 }
49
50 if (!m_lastForStmt) {
51 return;
52 }
53
54 auto *constructExpr = dyn_cast<CXXConstructExpr>(stmt);
55 if (!constructExpr || constructExpr->getNumArgs() < 1) {
56 return;
57 }
58
59 const CXXConstructorDecl *constructorDecl = constructExpr->getConstructor();
60 if (!constructorDecl || clazy::name(constructorDecl) != "QForeachContainer") {
61 return;
62 }
63
64 std::vector<DeclRefExpr *> declRefExprs;
65 clazy::getChilds<DeclRefExpr>(constructExpr, declRefExprs);
66 if (declRefExprs.empty()) {
67 return;
68 }
69
70 // Get the container value declaration
71 DeclRefExpr *declRefExpr = declRefExprs.front();
72 auto *valueDecl = dyn_cast<ValueDecl>(declRefExpr->getDecl());
73 if (!valueDecl) {
74 return;
75 }
76
77 QualType containerQualType = constructExpr->getArg(0)->getType();
78 const Type *containerType = containerQualType.getTypePtrOrNull();
79 CXXRecordDecl *const containerRecord = containerType ? containerType->getAsCXXRecordDecl() : nullptr;
80
81 if (!containerRecord) {
82 return;
83 }
84
85 auto *rootBaseClass = Utils::rootBaseClass(containerRecord);
86 StringRef containerClassName = clazy::name(rootBaseClass);
87 const bool isQtContainer = clazy::isQtIterableClass(containerClassName);
88 if (containerClassName.empty()) {
89 emitWarning(stmt->getBeginLoc(), "internal error, couldn't get class name of foreach container, please report a bug");
90 return;
91 }
92 if (!isQtContainer) {
93 emitWarning(stmt->getBeginLoc(), "foreach with STL container causes deep-copy (" + rootBaseClass->getQualifiedNameAsString() + ')');
94 return;
95 } else if (containerClassName == "QVarLengthArray") {
96 emitWarning(stmt->getBeginLoc(), "foreach with QVarLengthArray causes deep-copy");
97 return;
98 }
99
100 checkBigTypeMissingRef();
101
102 if (isa<MaterializeTemporaryExpr>(constructExpr->getArg(0))) { // Nothing else to check
103 return;
104 }
105
106 // const containers are fine
107 if (valueDecl->getType().isConstQualified()) {
108 return;
109 }
110
111 // Now look inside the for statement for detachments
112 if (containsDetachments(m_lastForStmt, valueDecl)) {
113 emitWarning(stmt->getBeginLoc(), "foreach container detached");
114 }
115 }
116
117 void Foreach::checkBigTypeMissingRef()
118 {
119 // Get the inner forstm
120 std::vector<ForStmt *> forStatements;
121 clazy::getChilds<ForStmt>(m_lastForStmt->getBody(), forStatements);
122 if (forStatements.empty()) {
123 return;
124 }
125
126 // Get the variable declaration (lhs of foreach)
127 std::vector<DeclStmt *> varDecls;
128 clazy::getChilds<DeclStmt>(forStatements.at(0), varDecls);
129 if (varDecls.empty()) {
130 return;
131 }
132
133 Decl *decl = varDecls.at(0)->getSingleDecl();
134 VarDecl *varDecl = decl ? dyn_cast<VarDecl>(decl) : nullptr;
135 if (!varDecl) {
136 return;
137 }
138
139 clazy::QualTypeClassification classif;
140 bool success = clazy::classifyQualType(m_context, varDecl->getType(), varDecl, /*by-ref*/ classif, forStatements.at(0));
141 if (!success) {
142 return;
143 }
144
145 if (classif.passBigTypeByConstRef || classif.passNonTriviallyCopyableByConstRef || classif.passSmallTrivialByValue) {
146 std::string error;
147 const std::string paramStr = varDecl->getType().getAsString();
148 if (classif.passBigTypeByConstRef) {
149 error = "Missing reference in foreach with sizeof(T) = ";
150 error += std::to_string(classif.size_of_T) + " bytes (" + paramStr + ')';
151 } else if (classif.passNonTriviallyCopyableByConstRef) {
152 error = "Missing reference in foreach with non trivial type (" + paramStr + ')';
153 } else if (classif.passSmallTrivialByValue) {
154 // error = "Pass small and trivially-copyable type by value (" + paramStr + ')';
155 // Don't warn. The compiler can (and most do) optimize this and generate the same code
156 return;
157 }
158
159 emitWarning(varDecl->getBeginLoc(), error);
160 }
161 }
162
163 bool Foreach::containsDetachments(Stmt *stm, clang::ValueDecl *containerValueDecl)
164 {
165 if (!stm) {
166 return false;
167 }
168
169 auto *memberExpr = dyn_cast<MemberExpr>(stm);
170 if (memberExpr) {
171 ValueDecl *valDecl = memberExpr->getMemberDecl();
172 if (valDecl && valDecl->isCXXClassMember()) {
173 DeclContext *declContext = valDecl->getDeclContext();
174 auto *recordDecl = dyn_cast<CXXRecordDecl>(declContext);
175 if (recordDecl) {
176 const std::string className = Utils::rootBaseClass(recordDecl)->getQualifiedNameAsString();
177 const std::unordered_map<std::string, std::vector<StringRef>> &detachingMethodsMap = clazy::detachingMethods();
178 if (detachingMethodsMap.find(className) != detachingMethodsMap.end()) {
179 const std::string functionName = valDecl->getNameAsString();
180 const auto &allowedFunctions = detachingMethodsMap.at(className);
181 if (clazy::contains(allowedFunctions, functionName)) {
182 Expr *expr = memberExpr->getBase();
183
184 if (expr) {
185 auto *refExpr = dyn_cast<DeclRefExpr>(expr);
186 if (!refExpr) {
187 auto *s = clazy::getFirstChildAtDepth(expr, 1);
188 refExpr = dyn_cast<DeclRefExpr>(s);
189 if (refExpr) {
190 if (refExpr->getDecl()
191 == containerValueDecl) { // Finally, check if this non-const member call is on the same container we're iterating
192 return true;
193 }
194 }
195 }
196 }
197 }
198 }
199 }
200 }
201 }
202
203 const auto children = stm->children();
204 return std::any_of(children.begin(), children.end(), [this, containerValueDecl](Stmt *child) {
205 return this->containsDetachments(child, containerValueDecl);
206 });
207 }