clang 24.0.0git
GCDAntipatternChecker.cpp
Go to the documentation of this file.
1//===- GCDAntipatternChecker.cpp ---------------------------------*- 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 GCDAntipatternChecker which checks against a common
10// antipattern when synchronous API is emulated from asynchronous callbacks
11// using a semaphore:
12//
13// dispatch_semaphore_t sema = dispatch_semaphore_create(0);
14//
15// AnyCFunctionCall(^{
16// // code…
17// dispatch_semaphore_signal(sema);
18// })
19// dispatch_semaphore_wait(sema, *)
20//
21// Such code is a common performance problem, due to inability of GCD to
22// properly handle QoS when a combination of queues and semaphores is used.
23// Good code would either use asynchronous API (when available), or perform
24// the necessary action in asynchronous callback.
25//
26// Currently, the check is performed using a simple heuristical AST pattern
27// matching.
28//
29//===----------------------------------------------------------------------===//
30
37#include "llvm/Support/Debug.h"
38
39using namespace clang;
40using namespace ento;
41using namespace ast_matchers;
42
43namespace {
44
45// ID of a node at which the diagnostic would be emitted.
46const char *WarnAtNode = "waitcall";
47
48static auto findGCDAntiPatternWithSemaphore() -> decltype(compoundStmt());
49static auto findGCDAntiPatternWithGroup() -> decltype(compoundStmt());
50
51class GCDAntipatternChecker : public Checker<check::ASTCodeBody> {
52 // Building the matchers is expensive, so build them once per checker instead
53 // of once per function body.
54 const StatementMatcher SemaphoreMatcherM = findGCDAntiPatternWithSemaphore();
55 const StatementMatcher GroupMatcherM = findGCDAntiPatternWithGroup();
56
57public:
58 void checkASTCodeBody(const Decl *D,
59 AnalysisManager &AM,
60 BugReporter &BR) const;
61};
62
63decltype(auto) callsName(const char *FunctionName) {
64 return callee(functionDecl(hasName(FunctionName)));
65}
66
67decltype(auto) equalsBoundArgDecl(int ArgIdx, const char *DeclName) {
68 return hasArgument(ArgIdx, ignoringParenCasts(declRefExpr(
69 to(varDecl(equalsBoundNode(DeclName))))));
70}
71
72decltype(auto) bindAssignmentToDecl(const char *DeclName) {
73 return hasLHS(ignoringParenImpCasts(
74 declRefExpr(to(varDecl().bind(DeclName)))));
75}
76
77/// The pattern is very common in tests, and it is OK to use it there.
78/// We have to heuristics for detecting tests: method name starts with "test"
79/// (used in XCTest), and a class name contains "mock" or "test" (used in
80/// helpers which are not tests themselves, but used exclusively in tests).
81static bool isTest(const Decl *D) {
82 if (const auto* ND = dyn_cast<NamedDecl>(D)) {
83 std::string DeclName = ND->getNameAsString();
84 if (StringRef(DeclName).starts_with("test"))
85 return true;
86 }
87 if (const auto *OD = dyn_cast<ObjCMethodDecl>(D)) {
88 if (const auto *CD = dyn_cast<ObjCContainerDecl>(OD->getParent())) {
89 std::string ContainerName = CD->getNameAsString();
90 StringRef CN(ContainerName);
91 if (CN.contains_insensitive("test") || CN.contains_insensitive("mock"))
92 return true;
93 }
94 }
95 return false;
96}
97
98static auto findGCDAntiPatternWithSemaphore() -> decltype(compoundStmt()) {
99
100 const char *SemaphoreBinding = "semaphore_name";
101 auto SemaphoreCreateM = callExpr(allOf(
102 callsName("dispatch_semaphore_create"),
103 hasArgument(0, ignoringParenCasts(integerLiteral(equals(0))))));
104
105 auto SemaphoreBindingM = anyOf(
107 varDecl(hasDescendant(SemaphoreCreateM)).bind(SemaphoreBinding)),
108 forEachDescendant(binaryOperator(bindAssignmentToDecl(SemaphoreBinding),
109 hasRHS(SemaphoreCreateM))));
110
111 auto HasBlockArgumentM = hasAnyArgument(hasType(
112 hasCanonicalType(blockPointerType())
113 ));
114
115 auto ArgCallsSignalM = hasAnyArgument(stmt(hasDescendant(callExpr(
116 allOf(
117 callsName("dispatch_semaphore_signal"),
118 equalsBoundArgDecl(0, SemaphoreBinding)
119 )))));
120
121 auto HasBlockAndCallsSignalM = allOf(HasBlockArgumentM, ArgCallsSignalM);
122
123 auto HasBlockCallingSignalM =
125 stmt(anyOf(
126 callExpr(HasBlockAndCallsSignalM),
127 objcMessageExpr(HasBlockAndCallsSignalM)
128 )));
129
130 auto SemaphoreWaitM = forEachDescendant(
131 callExpr(
132 allOf(
133 callsName("dispatch_semaphore_wait"),
134 equalsBoundArgDecl(0, SemaphoreBinding)
135 )
136 ).bind(WarnAtNode));
137
138 return compoundStmt(
139 SemaphoreBindingM, HasBlockCallingSignalM, SemaphoreWaitM);
140}
141
142static auto findGCDAntiPatternWithGroup() -> decltype(compoundStmt()) {
143
144 const char *GroupBinding = "group_name";
145 auto DispatchGroupCreateM = callExpr(callsName("dispatch_group_create"));
146
147 auto GroupBindingM = anyOf(
149 varDecl(hasDescendant(DispatchGroupCreateM)).bind(GroupBinding)),
150 forEachDescendant(binaryOperator(bindAssignmentToDecl(GroupBinding),
151 hasRHS(DispatchGroupCreateM))));
152
153 auto GroupEnterM = forEachDescendant(
154 stmt(callExpr(allOf(callsName("dispatch_group_enter"),
155 equalsBoundArgDecl(0, GroupBinding)))));
156
157 auto HasBlockArgumentM = hasAnyArgument(hasType(
158 hasCanonicalType(blockPointerType())
159 ));
160
161 auto ArgCallsSignalM = hasAnyArgument(stmt(hasDescendant(callExpr(
162 allOf(
163 callsName("dispatch_group_leave"),
164 equalsBoundArgDecl(0, GroupBinding)
165 )))));
166
167 auto HasBlockAndCallsLeaveM = allOf(HasBlockArgumentM, ArgCallsSignalM);
168
169 auto AcceptsBlockM =
171 stmt(anyOf(
172 callExpr(HasBlockAndCallsLeaveM),
173 objcMessageExpr(HasBlockAndCallsLeaveM)
174 )));
175
176 auto GroupWaitM = forEachDescendant(
177 callExpr(
178 allOf(
179 callsName("dispatch_group_wait"),
180 equalsBoundArgDecl(0, GroupBinding)
181 )
182 ).bind(WarnAtNode));
183
184 return compoundStmt(GroupBindingM, GroupEnterM, AcceptsBlockM, GroupWaitM);
185}
186
187static void emitDiagnostics(const BoundNodes &Nodes,
188 const char* Type,
189 BugReporter &BR,
191 const GCDAntipatternChecker *Checker) {
192 const auto *SW = Nodes.getNodeAs<CallExpr>(WarnAtNode);
193 assert(SW);
194
195 std::string Diagnostics;
196 llvm::raw_string_ostream OS(Diagnostics);
197 OS << "Waiting on a callback using a " << Type << " creates useless threads "
198 << "and is subject to priority inversion; consider "
199 << "using a synchronous API or changing the caller to be asynchronous";
200
202 ADC->getDecl(),
203 Checker,
204 /*Name=*/"GCD performance anti-pattern",
205 /*BugCategory=*/"Performance",
206 OS.str(),
208 SW->getSourceRange());
209}
210
211void GCDAntipatternChecker::checkASTCodeBody(const Decl *D,
212 AnalysisManager &AM,
213 BugReporter &BR) const {
214 if (isTest(D))
215 return;
216
217 AnalysisDeclContext *ADC = AM.getAnalysisDeclContext(D);
218
219 auto Matches = match(SemaphoreMatcherM, *D->getBody(), AM.getASTContext());
220 for (BoundNodes Match : Matches)
221 emitDiagnostics(Match, "semaphore", BR, ADC, this);
222
223 Matches = match(GroupMatcherM, *D->getBody(), AM.getASTContext());
224 for (BoundNodes Match : Matches)
225 emitDiagnostics(Match, "group", BR, ADC, this);
226}
227
228} // end of anonymous namespace
229
230void ento::registerGCDAntipattern(CheckerManager &Mgr) {
231 Mgr.registerChecker<GCDAntipatternChecker>();
232}
233
234bool ento::shouldRegisterGCDAntipattern(const CheckerManager &mgr) {
235 return true;
236}
static void emitDiagnostics(BoundNodes &Match, const Decl *D, BugReporter &BR, AnalysisManager &AM, const ObjCAutoreleaseWriteChecker *Checker)
AnalysisDeclContext contains the context data for the function, method or block under analysis.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition DeclBase.h:1106
The base class of the type hierarchy.
Definition TypeBase.h:1879
Maps string IDs to AST nodes matched by parts of a matcher.
const T * getNodeAs(StringRef ID) const
Returns the AST node bound to ID.
ASTContext & getASTContext() override
AnalysisDeclContext * getAnalysisDeclContext(const Decl *D)
BugReporter is a utility class for generating PathDiagnostics for analysis.
const SourceManager & getSourceManager()
void EmitBasicReport(const Decl *DeclWithIssue, const CheckerFrontend *Checker, StringRef BugName, StringRef BugCategory, StringRef BugStr, PathDiagnosticLocation Loc, ArrayRef< SourceRange > Ranges={}, ArrayRef< FixItHint > Fixits={})
CHECKER * registerChecker(AT &&...Args)
Register a single-part checker (derived from Checker): construct its singleton instance,...
Simple checker classes that implement one frontend (i.e.
Definition Checker.h:565
static PathDiagnosticLocation createBegin(const Decl *D, const SourceManager &SM)
Create a location for the beginning of the declaration.
const internal::VariadicDynCastAllOfMatcher< Decl, VarDecl > varDecl
Matches variable declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, DeclRefExpr > declRefExpr
Matches expressions that refer to declarations.
const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher > hasDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
internal::Matcher< NamedDecl > hasName(StringRef Name)
Matches NamedDecl nodes that have the specified name.
const internal::VariadicDynCastAllOfMatcher< Stmt, CallExpr > callExpr
Matches call expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CompoundStmt > compoundStmt
Matches compound statements.
const AstTypeMatcher< BlockPointerType > blockPointerType
const internal::ArgumentAdaptingMatcherFunc< internal::ForEachDescendantMatcher > forEachDescendant
Matches AST nodes that have descendant AST nodes that match the provided matcher.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
const internal::VariadicDynCastAllOfMatcher< Stmt, ObjCMessageExpr > objcMessageExpr
Matches ObjectiveC Message invocation expressions.
internal::Matcher< Stmt > StatementMatcher
const internal::VariadicDynCastAllOfMatcher< Stmt, BinaryOperator > binaryOperator
Matches binary operator expressions.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> allOf
Matches if all given matchers match.
const internal::VariadicDynCastAllOfMatcher< Decl, FunctionDecl > functionDecl
Matches function declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, IntegerLiteral > integerLiteral
Matches integer literals of all sizes / encodings, e.g.
const internal::VariadicAllOfMatcher< Stmt > stmt
Matches statements.
const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits< unsigned >::max()> anyOf
Matches if any of the given matchers matches.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
bool equals(const til::SExpr *E1, const til::SExpr *E2)
Top level wrappers for InstallAPI frontend operations.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:824