1 //=== LLVMConventionsChecker.cpp - Check LLVM codebase conventions ---*- C++ -*-
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines LLVMConventionsChecker, a bunch of small little checks
11 // for checking specific coding conventions in the LLVM/Clang codebase.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/StaticAnalyzer/Core/Checker.h"
17 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "llvm/ADT/SmallString.h"
22 using namespace clang;
25 //===----------------------------------------------------------------------===//
26 // Generic type checking routines.
27 //===----------------------------------------------------------------------===//
29 static bool IsLLVMStringRef(QualType T) {
30 const RecordType *RT = T->getAs<RecordType>();
34 return StringRef(QualType(RT, 0).getAsString()) ==
38 /// Check whether the declaration is semantically inside the top-level
39 /// namespace named by ns.
40 static bool InNamespace(const Decl *D, StringRef NS) {
41 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext());
44 const IdentifierInfo *II = ND->getIdentifier();
45 if (!II || !II->getName().equals(NS))
47 return isa<TranslationUnitDecl>(ND->getDeclContext());
50 static bool IsStdString(QualType T) {
51 if (const ElaboratedType *QT = T->getAs<ElaboratedType>())
52 T = QT->getNamedType();
54 const TypedefType *TT = T->getAs<TypedefType>();
58 const TypedefNameDecl *TD = TT->getDecl();
60 if (!InNamespace(TD, "std"))
63 return TD->getName() == "string";
66 static bool IsClangType(const RecordDecl *RD) {
67 return RD->getName() == "Type" && InNamespace(RD, "clang");
70 static bool IsClangDecl(const RecordDecl *RD) {
71 return RD->getName() == "Decl" && InNamespace(RD, "clang");
74 static bool IsClangStmt(const RecordDecl *RD) {
75 return RD->getName() == "Stmt" && InNamespace(RD, "clang");
78 static bool IsClangAttr(const RecordDecl *RD) {
79 return RD->getName() == "Attr" && InNamespace(RD, "clang");
82 static bool IsStdVector(QualType T) {
83 const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
87 TemplateName TM = TS->getTemplateName();
88 TemplateDecl *TD = TM.getAsTemplateDecl();
90 if (!TD || !InNamespace(TD, "std"))
93 return TD->getName() == "vector";
96 static bool IsSmallVector(QualType T) {
97 const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
101 TemplateName TM = TS->getTemplateName();
102 TemplateDecl *TD = TM.getAsTemplateDecl();
104 if (!TD || !InNamespace(TD, "llvm"))
107 return TD->getName() == "SmallVector";
110 //===----------------------------------------------------------------------===//
111 // CHECK: a StringRef should not be bound to a temporary std::string whose
112 // lifetime is shorter than the StringRef's.
113 //===----------------------------------------------------------------------===//
116 class StringRefCheckerVisitor : public StmtVisitor<StringRefCheckerVisitor> {
118 const Decl *DeclWithIssue;
120 StringRefCheckerVisitor(const Decl *declWithIssue, BugReporter &br)
121 : BR(br), DeclWithIssue(declWithIssue) {}
122 void VisitChildren(Stmt *S) {
123 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
125 if (Stmt *child = *I)
128 void VisitStmt(Stmt *S) { VisitChildren(S); }
129 void VisitDeclStmt(DeclStmt *DS);
131 void VisitVarDecl(VarDecl *VD);
133 } // end anonymous namespace
135 static void CheckStringRefAssignedTemporary(const Decl *D, BugReporter &BR) {
136 StringRefCheckerVisitor walker(D, BR);
137 walker.Visit(D->getBody());
140 void StringRefCheckerVisitor::VisitDeclStmt(DeclStmt *S) {
143 for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end();I!=E; ++I)
144 if (VarDecl *VD = dyn_cast<VarDecl>(*I))
148 void StringRefCheckerVisitor::VisitVarDecl(VarDecl *VD) {
149 Expr *Init = VD->getInit();
153 // Pattern match for:
154 // StringRef x = call() (where call returns std::string)
155 if (!IsLLVMStringRef(VD->getType()))
157 ExprWithCleanups *Ex1 = dyn_cast<ExprWithCleanups>(Init);
160 CXXConstructExpr *Ex2 = dyn_cast<CXXConstructExpr>(Ex1->getSubExpr());
161 if (!Ex2 || Ex2->getNumArgs() != 1)
163 ImplicitCastExpr *Ex3 = dyn_cast<ImplicitCastExpr>(Ex2->getArg(0));
166 CXXConstructExpr *Ex4 = dyn_cast<CXXConstructExpr>(Ex3->getSubExpr());
167 if (!Ex4 || Ex4->getNumArgs() != 1)
169 ImplicitCastExpr *Ex5 = dyn_cast<ImplicitCastExpr>(Ex4->getArg(0));
172 CXXBindTemporaryExpr *Ex6 = dyn_cast<CXXBindTemporaryExpr>(Ex5->getSubExpr());
173 if (!Ex6 || !IsStdString(Ex6->getType()))
176 // Okay, badness! Report an error.
177 const char *desc = "StringRef should not be bound to temporary "
178 "std::string that it outlives";
179 PathDiagnosticLocation VDLoc =
180 PathDiagnosticLocation::createBegin(VD, BR.getSourceManager());
181 BR.EmitBasicReport(DeclWithIssue, desc, "LLVM Conventions", desc,
182 VDLoc, Init->getSourceRange());
185 //===----------------------------------------------------------------------===//
186 // CHECK: Clang AST nodes should not have fields that can allocate
188 //===----------------------------------------------------------------------===//
190 static bool AllocatesMemory(QualType T) {
191 return IsStdVector(T) || IsStdString(T) || IsSmallVector(T);
194 // This type checking could be sped up via dynamic programming.
195 static bool IsPartOfAST(const CXXRecordDecl *R) {
196 if (IsClangStmt(R) || IsClangType(R) || IsClangDecl(R) || IsClangAttr(R))
199 for (CXXRecordDecl::base_class_const_iterator I = R->bases_begin(),
200 E = R->bases_end(); I!=E; ++I) {
201 CXXBaseSpecifier BS = *I;
202 QualType T = BS.getType();
203 if (const RecordType *baseT = T->getAs<RecordType>()) {
204 CXXRecordDecl *baseD = cast<CXXRecordDecl>(baseT->getDecl());
205 if (IsPartOfAST(baseD))
214 class ASTFieldVisitor {
215 SmallVector<FieldDecl*, 10> FieldChain;
216 const CXXRecordDecl *Root;
219 ASTFieldVisitor(const CXXRecordDecl *root, BugReporter &br)
220 : Root(root), BR(br) {}
222 void Visit(FieldDecl *D);
223 void ReportError(QualType T);
225 } // end anonymous namespace
227 static void CheckASTMemory(const CXXRecordDecl *R, BugReporter &BR) {
231 for (RecordDecl::field_iterator I = R->field_begin(), E = R->field_end();
233 ASTFieldVisitor walker(R, BR);
238 void ASTFieldVisitor::Visit(FieldDecl *D) {
239 FieldChain.push_back(D);
241 QualType T = D->getType();
243 if (AllocatesMemory(T))
246 if (const RecordType *RT = T->getAs<RecordType>()) {
247 const RecordDecl *RD = RT->getDecl()->getDefinition();
248 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
253 FieldChain.pop_back();
256 void ASTFieldVisitor::ReportError(QualType T) {
257 SmallString<1024> buf;
258 llvm::raw_svector_ostream os(buf);
260 os << "AST class '" << Root->getName() << "' has a field '"
261 << FieldChain.front()->getName() << "' that allocates heap memory";
262 if (FieldChain.size() > 1) {
263 os << " via the following chain: ";
265 for (SmallVectorImpl<FieldDecl*>::iterator I=FieldChain.begin(),
266 E=FieldChain.end(); I!=E; ++I) {
271 os << (*I)->getName();
274 os << " (type " << FieldChain.back()->getType().getAsString() << ")";
277 // Note that this will fire for every translation unit that uses this
278 // class. This is suboptimal, but at least scan-build will merge
279 // duplicate HTML reports. In the future we need a unified way of merging
280 // duplicate reports across translation units. For C++ classes we cannot
281 // just report warnings when we see an out-of-line method definition for a
282 // class, as that heuristic doesn't always work (the complete definition of
283 // the class may be in the header file, for example).
284 PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
285 FieldChain.front(), BR.getSourceManager());
286 BR.EmitBasicReport(Root, "AST node allocates heap memory", "LLVM Conventions",
290 //===----------------------------------------------------------------------===//
291 // LLVMConventionsChecker
292 //===----------------------------------------------------------------------===//
295 class LLVMConventionsChecker : public Checker<
296 check::ASTDecl<CXXRecordDecl>,
297 check::ASTCodeBody > {
299 void checkASTDecl(const CXXRecordDecl *R, AnalysisManager& mgr,
300 BugReporter &BR) const {
301 if (R->isCompleteDefinition())
302 CheckASTMemory(R, BR);
305 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
306 BugReporter &BR) const {
307 CheckStringRefAssignedTemporary(D, BR);
312 void ento::registerLLVMConventionsChecker(CheckerManager &mgr) {
313 mgr.registerChecker<LLVMConventionsChecker>();