1 //===---- CheckerHelpers.cpp - Helper functions for checkers ----*- 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 file defines several static functions for use in checkers.
12 //===----------------------------------------------------------------------===//
14 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/Expr.h"
18 // Recursively find any substatements containing macros
19 bool clang::ento::containsMacro(const Stmt *S) {
20 if (S->getLocStart().isMacroID())
23 if (S->getLocEnd().isMacroID())
26 for (const Stmt *Child : S->children())
27 if (Child && containsMacro(Child))
33 // Recursively find any substatements containing enum constants
34 bool clang::ento::containsEnum(const Stmt *S) {
35 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
37 if (DR && isa<EnumConstantDecl>(DR->getDecl()))
40 for (const Stmt *Child : S->children())
41 if (Child && containsEnum(Child))
47 // Recursively find any substatements containing static vars
48 bool clang::ento::containsStaticLocal(const Stmt *S) {
49 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
52 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
53 if (VD->isStaticLocal())
56 for (const Stmt *Child : S->children())
57 if (Child && containsStaticLocal(Child))
63 // Recursively find any substatements containing __builtin_offsetof
64 bool clang::ento::containsBuiltinOffsetOf(const Stmt *S) {
65 if (isa<OffsetOfExpr>(S))
68 for (const Stmt *Child : S->children())
69 if (Child && containsBuiltinOffsetOf(Child))
75 // Extract lhs and rhs from assignment statement
76 std::pair<const clang::VarDecl *, const clang::Expr *>
77 clang::ento::parseAssignment(const Stmt *S) {
78 const VarDecl *VD = nullptr;
79 const Expr *RHS = nullptr;
81 if (auto Assign = dyn_cast_or_null<BinaryOperator>(S)) {
82 if (Assign->isAssignmentOp()) {
83 // Ordinary assignment
84 RHS = Assign->getRHS();
85 if (auto DE = dyn_cast_or_null<DeclRefExpr>(Assign->getLHS()))
86 VD = dyn_cast_or_null<VarDecl>(DE->getDecl());
88 } else if (auto PD = dyn_cast_or_null<DeclStmt>(S)) {
90 assert(PD->isSingleDecl() && "We process decls one by one");
91 VD = dyn_cast_or_null<VarDecl>(PD->getSingleDecl());
92 RHS = VD->getAnyInitializer();
95 return std::make_pair(VD, RHS);