clang 24.0.0git
CheckerHelpers.cpp
Go to the documentation of this file.
1//===---- CheckerHelpers.cpp - Helper functions for checkers ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines several static functions for use in checkers.
10//
11//===----------------------------------------------------------------------===//
12
14#include "clang/AST/Decl.h"
15#include "clang/AST/Expr.h"
20#include "llvm/ADT/STLExtras.h"
21#include <iterator>
22#include <optional>
23
24namespace clang {
25
26namespace ento {
27
28// Returns true if any non-null child of S satisfies Pred.
29static bool anyChild(const Stmt *S, bool (*Pred)(const Stmt *)) {
30 return llvm::any_of(S->children(), [Pred](const Stmt *Child) {
31 return Child && Pred(Child);
32 });
33}
34
35// Recursively find any substatements containing macros
36bool containsMacro(const Stmt *S) {
37 if (S->getBeginLoc().isMacroID())
38 return true;
39
40 if (S->getEndLoc().isMacroID())
41 return true;
42
43 return anyChild(S, containsMacro);
44}
45
46// Recursively find any substatements containing enum constants
47bool containsEnum(const Stmt *S) {
48 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
49
50 if (DR && isa<EnumConstantDecl>(DR->getDecl()))
51 return true;
52
53 return anyChild(S, containsEnum);
54}
55
56// Recursively find any substatements containing static vars
57bool containsStaticLocal(const Stmt *S) {
58 const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(S);
59
60 if (DR)
61 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl()))
62 if (VD->isStaticLocal())
63 return true;
64
66}
67
68// Recursively find any substatements containing __builtin_offsetof
70 if (isa<OffsetOfExpr>(S))
71 return true;
72
74}
75
76// Extract lhs and rhs from assignment statement
77std::pair<const clang::VarDecl *, const clang::Expr *>
79 const VarDecl *VD = nullptr;
80 const Expr *RHS = nullptr;
81
82 if (auto Assign = dyn_cast_or_null<BinaryOperator>(S)) {
83 if (Assign->isAssignmentOp()) {
84 // Ordinary assignment
85 RHS = Assign->getRHS();
86 if (auto DE = dyn_cast_or_null<DeclRefExpr>(Assign->getLHS()))
87 VD = dyn_cast_or_null<VarDecl>(DE->getDecl());
88 }
89 } else if (auto PD = dyn_cast_or_null<DeclStmt>(S)) {
90 // Initialization
91 assert(PD->isSingleDecl() && "We process decls one by one");
92 VD = cast<VarDecl>(PD->getSingleDecl());
93 RHS = VD->getAnyInitializer();
94 }
95
96 return std::make_pair(VD, RHS);
97}
98
100 const auto *AttrType = Type->getAs<AttributedType>();
101 if (!AttrType)
103 if (AttrType->getAttrKind() == attr::TypeNullable)
105 else if (AttrType->getAttrKind() == attr::TypeNonNull)
108}
109
110std::optional<int> tryExpandAsInteger(StringRef Macro, const Preprocessor &PP) {
111 const auto *MacroII = PP.getIdentifierInfo(Macro);
112 if (!MacroII)
113 return std::nullopt;
114 const MacroInfo *MI = PP.getMacroInfo(MacroII);
115 if (!MI)
116 return std::nullopt;
117
118 // Filter out parens.
119 std::vector<Token> FilteredTokens;
120 FilteredTokens.reserve(MI->tokens().size());
121 auto IsNotParen = [](const Token &T) {
122 return !T.isOneOf(tok::l_paren, tok::r_paren);
123 };
124 llvm::copy_if(MI->tokens(), std::back_inserter(FilteredTokens), IsNotParen);
125
126 if (FilteredTokens.empty())
127 return std::nullopt;
128
129 // Parse an integer at the end of the macro definition.
130 const Token &T = FilteredTokens.back();
131
132 if (!T.isLiteral())
133 return std::nullopt;
134
135 bool InvalidSpelling = false;
136 SmallVector<char> Buffer(T.getLength());
137 // `Preprocessor::getSpelling` can get the spelling of the token regardless of
138 // whether the macro is defined in a PCH or not:
139 StringRef ValueStr = PP.getSpelling(T, Buffer, &InvalidSpelling);
140
141 if (InvalidSpelling)
142 return std::nullopt;
143
144 llvm::APSInt IntValue(/*BitWidth=*/0, /*isUnsigned=*/true);
145 constexpr unsigned AutoSenseRadix = 0;
146 if (ValueStr.getAsInteger(AutoSenseRadix,
147 static_cast<llvm::APInt &>(IntValue)))
148 return std::nullopt;
149
150 // Parse an optional minus sign.
151 size_t Size = FilteredTokens.size();
152 if (Size >= 2) {
153 if (FilteredTokens[Size - 2].is(tok::minus)) {
154 // Make sure there's space for a sign bit
155 if (IntValue.isSignBitSet())
156 IntValue = IntValue.extend(IntValue.getBitWidth() + 1);
157 IntValue.setIsUnsigned(false);
158 IntValue = -IntValue;
159 }
160 }
161
162 // System headers may spell a negative int as a literal above INT_MAX (e.g.
163 // 0xFFFFFFFF), so accept every value that fits into the bits of an int.
164 const APSIntType IntType(PP.getTargetInfo().getIntWidth(),
165 /*Unsigned=*/false);
166 if (IntType.testInRange(IntValue, /*AllowMixedSign=*/true) !=
168 return std::nullopt;
169 return IntType.convert(IntValue).getExtValue();
170}
171
173 bool IsBinary) {
174 llvm::StringMap<BinaryOperatorKind> BinOps{
175#define BINARY_OPERATION(Name, Spelling) {Spelling, BO_##Name},
176#include "clang/AST/OperationKinds.def"
177 };
178 llvm::StringMap<UnaryOperatorKind> UnOps{
179#define UNARY_OPERATION(Name, Spelling) {Spelling, UO_##Name},
180#include "clang/AST/OperationKinds.def"
181 };
182
183 switch (OOK) {
184#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
185 case OO_##Name: \
186 if (IsBinary) { \
187 auto BinOpIt = BinOps.find(Spelling); \
188 if (BinOpIt != BinOps.end()) \
189 return OperatorKind(BinOpIt->second); \
190 else \
191 llvm_unreachable("operator was expected to be binary but is not"); \
192 } else { \
193 auto UnOpIt = UnOps.find(Spelling); \
194 if (UnOpIt != UnOps.end()) \
195 return OperatorKind(UnOpIt->second); \
196 else \
197 llvm_unreachable("operator was expected to be unary but is not"); \
198 } \
199 break;
200#include "clang/Basic/OperatorKinds.def"
201 default:
202 llvm_unreachable("unexpected operator kind");
203 }
204}
205
206std::optional<SVal> getPointeeVal(SVal PtrSVal, ProgramStateRef State) {
207 if (const auto *Ptr = PtrSVal.getAsRegion()) {
208 return State->getSVal(Ptr);
209 }
210 return std::nullopt;
211}
212
214 const DeclContext *DC = D->getDeclContext();
215 while (DC) {
216 if (const auto *NS = dyn_cast<NamespaceDecl>(DC);
217 NS && NS->isStdNamespace())
218 return true;
219 DC = DC->getParent();
220 }
221 return false;
222}
223
224} // namespace ento
225} // namespace clang
bool is(tok::TokenKind Kind) const
Defines the clang::Preprocessor interface.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1468
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2113
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
DeclContext * getDeclContext()
Definition DeclBase.h:458
This represents one expression.
Definition Expr.h:114
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
ArrayRef< Token > tokens() const
Definition MacroInfo.h:250
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
const TargetInfo & getTargetInfo() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
A (possibly-)qualified type.
Definition TypeBase.h:938
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
child_range children()
Definition Stmt.cpp:304
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition TargetInfo.h:538
Token - This structure provides full information about a lexed token.
Definition Token.h:36
The base class of the type hierarchy.
Definition TypeBase.h:1879
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
Represents a variable declaration or definition.
Definition Decl.h:934
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
A record of the "type" of an APSInt, used for conversions.
Definition APSIntType.h:19
@ RTR_Within
Value is representable using this type.
Definition APSIntType.h:78
SVal - This represents a symbolic expression, which can be either an L-value or an R-value.
Definition SVals.h:57
const MemRegion * getAsRegion() const
Definition SVals.cpp:119
Defines the clang::TargetInfo interface.
bool containsEnum(const Stmt *S)
Nullability getNullabilityAnnotation(QualType Type)
Get nullability annotation for a given type.
bool isWithinStdNamespace(const Decl *D)
Returns true if declaration D is in std namespace or any nested namespace or class scope.
IntrusiveRefCntPtr< const ProgramState > ProgramStateRef
bool containsStaticLocal(const Stmt *S)
std::pair< const clang::VarDecl *, const clang::Expr * > parseAssignment(const Stmt *S)
OperatorKind operationKindFromOverloadedOperator(OverloadedOperatorKind OOK, bool IsBinary)
bool containsBuiltinOffsetOf(const Stmt *S)
std::optional< SVal > getPointeeVal(SVal PtrSVal, ProgramStateRef State)
static bool anyChild(const Stmt *S, bool(*Pred)(const Stmt *))
std::optional< int > tryExpandAsInteger(StringRef Macro, const Preprocessor &PP)
Try to parse the value of a defined preprocessor macro.
bool containsMacro(const Stmt *S)
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
bool isa(CodeGen::Address addr)
Definition Address.h:330
U cast(CodeGen::Address addr)
Definition Address.h:327