blob: b19d4a398186fd6bb2d17b9039fa6bdc36a5b506 [file] [log] [blame]
Caitlin Sadowski33208342011-09-09 16:11:56 +00001//===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
Aaron Ballmanfcd5b7e2013-06-26 19:17:19 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#thread-safety-annotation-checking
14// for more information.
Caitlin Sadowski33208342011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000020#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Analysis/Analyses/PostOrderCFGView.h"
25#include "clang/Analysis/AnalysisContext.h"
26#include "clang/Analysis/CFG.h"
27#include "clang/Analysis/CFGStmtMap.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000028#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/SourceManager.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/ImmutableMap.h"
34#include "llvm/ADT/PostOrderIterator.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000037#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000038#include <algorithm>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000039#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000040#include <vector>
41
42using namespace clang;
43using namespace thread_safety;
44
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000045// Key method definition
46ThreadSafetyHandler::~ThreadSafetyHandler() {}
47
Caitlin Sadowski33208342011-09-09 16:11:56 +000048namespace {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +000049
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000050/// SExpr implements a simple expression language that is used to store,
51/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
52/// does not capture surface syntax, and it does not distinguish between
53/// C++ concepts, like pointers and references, that have no real semantic
54/// differences. This simplicity allows SExprs to be meaningfully compared,
55/// e.g.
56/// (x) = x
57/// (*this).foo = this->foo
58/// *&a = a
Caitlin Sadowski33208342011-09-09 16:11:56 +000059///
60/// Thread-safety analysis works by comparing lock expressions. Within the
61/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
62/// a particular mutex object at run-time. Subsequent occurrences of the same
63/// expression (where "same" means syntactic equality) will refer to the same
64/// run-time object if three conditions hold:
65/// (1) Local variables in the expression, such as "x" have not changed.
66/// (2) Values on the heap that affect the expression have not changed.
67/// (3) The expression involves only pure function calls.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +000068///
Caitlin Sadowski33208342011-09-09 16:11:56 +000069/// The current implementation assumes, but does not verify, that multiple uses
70/// of the same lock expression satisfies these criteria.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000071class SExpr {
72private:
73 enum ExprOp {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +000074 EOP_Nop, ///< No-op
75 EOP_Wildcard, ///< Matches anything.
76 EOP_Universal, ///< Universal lock.
77 EOP_This, ///< This keyword.
78 EOP_NVar, ///< Named variable.
79 EOP_LVar, ///< Local variable.
80 EOP_Dot, ///< Field access
81 EOP_Call, ///< Function call
82 EOP_MCall, ///< Method call
83 EOP_Index, ///< Array index
84 EOP_Unary, ///< Unary operation
85 EOP_Binary, ///< Binary operation
86 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000087 };
88
89
90 class SExprNode {
91 private:
Ted Kremenek78094ca2012-08-22 23:50:41 +000092 unsigned char Op; ///< Opcode of the root node
93 unsigned char Flags; ///< Additional opcode-specific data
94 unsigned short Sz; ///< Number of child nodes
95 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000096
97 public:
98 SExprNode(ExprOp O, unsigned F, const void* D)
99 : Op(static_cast<unsigned char>(O)),
100 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
101 { }
102
103 unsigned size() const { return Sz; }
104 void setSize(unsigned S) { Sz = S; }
105
106 ExprOp kind() const { return static_cast<ExprOp>(Op); }
107
108 const NamedDecl* getNamedDecl() const {
109 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
110 return reinterpret_cast<const NamedDecl*>(Data);
111 }
112
113 const NamedDecl* getFunctionDecl() const {
114 assert(Op == EOP_Call || Op == EOP_MCall);
115 return reinterpret_cast<const NamedDecl*>(Data);
116 }
117
118 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
119 void setArrow(bool A) { Flags = A ? 1 : 0; }
120
121 unsigned arity() const {
122 switch (Op) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000123 case EOP_Nop: return 0;
124 case EOP_Wildcard: return 0;
125 case EOP_Universal: return 0;
126 case EOP_NVar: return 0;
127 case EOP_LVar: return 0;
128 case EOP_This: return 0;
129 case EOP_Dot: return 1;
130 case EOP_Call: return Flags+1; // First arg is function.
131 case EOP_MCall: return Flags+1; // First arg is implicit obj.
132 case EOP_Index: return 2;
133 case EOP_Unary: return 1;
134 case EOP_Binary: return 2;
135 case EOP_Unknown: return Flags;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000136 }
137 return 0;
138 }
139
140 bool operator==(const SExprNode& Other) const {
141 // Ignore flags and size -- they don't matter.
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000142 return (Op == Other.Op &&
143 Data == Other.Data);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000144 }
145
146 bool operator!=(const SExprNode& Other) const {
147 return !(*this == Other);
148 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000149
150 bool matches(const SExprNode& Other) const {
151 return (*this == Other) ||
152 (Op == EOP_Wildcard) ||
153 (Other.Op == EOP_Wildcard);
154 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000155 };
156
Caitlin Sadowski33208342011-09-09 16:11:56 +0000157
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000158 /// \brief Encapsulates the lexical context of a function call. The lexical
159 /// context includes the arguments to the call, including the implicit object
160 /// argument. When an attribute containing a mutex expression is attached to
161 /// a method, the expression may refer to formal parameters of the method.
162 /// Actual arguments must be substituted for formal parameters to derive
163 /// the appropriate mutex expression in the lexical context where the function
164 /// is called. PrevCtx holds the context in which the arguments themselves
165 /// should be evaluated; multiple calling contexts can be chained together
166 /// by the lock_returned attribute.
167 struct CallingContext {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000168 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
169 const Expr* SelfArg; // Implicit object argument -- e.g. 'this'
170 bool SelfArrow; // is Self referred to with -> or .?
171 unsigned NumArgs; // Number of funArgs
172 const Expr* const* FunArgs; // Function arguments
173 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000174
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000175 CallingContext(const NamedDecl *D = 0, const Expr *S = 0,
176 unsigned N = 0, const Expr* const *A = 0,
177 CallingContext *P = 0)
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000178 : AttrDecl(D), SelfArg(S), SelfArrow(false),
179 NumArgs(N), FunArgs(A), PrevCtx(P)
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000180 { }
181 };
182
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000183 typedef SmallVector<SExprNode, 4> NodeVector;
184
185private:
186 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
187 // the list to be traversed as a tree.
188 NodeVector NodeVec;
189
190private:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000191 unsigned makeNop() {
192 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
193 return NodeVec.size()-1;
194 }
195
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000196 unsigned makeWildcard() {
197 NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
198 return NodeVec.size()-1;
199 }
200
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000201 unsigned makeUniversal() {
202 NodeVec.push_back(SExprNode(EOP_Universal, 0, 0));
203 return NodeVec.size()-1;
204 }
205
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000206 unsigned makeNamedVar(const NamedDecl *D) {
207 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
208 return NodeVec.size()-1;
209 }
210
211 unsigned makeLocalVar(const NamedDecl *D) {
212 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
213 return NodeVec.size()-1;
214 }
215
216 unsigned makeThis() {
217 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
218 return NodeVec.size()-1;
219 }
220
221 unsigned makeDot(const NamedDecl *D, bool Arrow) {
222 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
223 return NodeVec.size()-1;
224 }
225
226 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
227 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
228 return NodeVec.size()-1;
229 }
230
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000231 // Grab the very first declaration of virtual method D
232 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
233 while (true) {
234 D = D->getCanonicalDecl();
235 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
236 E = D->end_overridden_methods();
237 if (I == E)
238 return D; // Method does not override anything
239 D = *I; // FIXME: this does not work with multiple inheritance.
240 }
241 return 0;
242 }
243
244 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
245 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, getFirstVirtualDecl(D)));
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000246 return NodeVec.size()-1;
247 }
248
249 unsigned makeIndex() {
250 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
251 return NodeVec.size()-1;
252 }
253
254 unsigned makeUnary() {
255 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
256 return NodeVec.size()-1;
257 }
258
259 unsigned makeBinary() {
260 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
261 return NodeVec.size()-1;
262 }
263
264 unsigned makeUnknown(unsigned Arity) {
265 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
266 return NodeVec.size()-1;
267 }
268
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000269 inline bool isCalleeArrow(const Expr *E) {
270 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
271 return ME ? ME->isArrow() : false;
272 }
273
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000274 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000275 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000276 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000277 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000278 ///
279 /// NDeref returns the number of Derefence and AddressOf operations
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000280 /// preceding the Expr; this is used to decide whether to pretty-print
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000281 /// SExprs with . or ->.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000282 unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx,
283 int* NDeref = 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000284 if (!Exp)
285 return 0;
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000286
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000287 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
288 const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
289 const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000290 if (PV) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000291 const FunctionDecl *FD =
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000292 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
293 unsigned i = PV->getFunctionScopeIndex();
294
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000295 if (CallCtx && CallCtx->FunArgs &&
296 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000297 // Substitute call arguments for references to function parameters
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000298 assert(i < CallCtx->NumArgs);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000299 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000300 }
301 // Map the param back to the param of the original function declaration.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000302 makeNamedVar(FD->getParamDecl(i));
303 return 1;
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000304 }
305 // Not a function parameter -- just store the reference.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000306 makeNamedVar(ND);
307 return 1;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000308 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000309 // Substitute parent for 'this'
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000310 if (CallCtx && CallCtx->SelfArg) {
311 if (!CallCtx->SelfArrow && NDeref)
312 // 'this' is a pointer, but self is not, so need to take address.
313 --(*NDeref);
314 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
315 }
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000316 else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000317 makeThis();
318 return 1;
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000319 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000320 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
321 const NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000322 int ImplicitDeref = ME->isArrow() ? 1 : 0;
323 unsigned Root = makeDot(ND, false);
324 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
325 NodeVec[Root].setArrow(ImplicitDeref > 0);
326 NodeVec[Root].setSize(Sz + 1);
327 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000328 } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000329 // When calling a function with a lock_returned attribute, replace
330 // the function call with the expression in lock_returned.
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000331 const CXXMethodDecl *MD = CMCE->getMethodDecl()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000332 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000333 CallingContext LRCallCtx(CMCE->getMethodDecl());
334 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000335 LRCallCtx.SelfArrow = isCalleeArrow(CMCE->getCallee());
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000336 LRCallCtx.NumArgs = CMCE->getNumArgs();
337 LRCallCtx.FunArgs = CMCE->getArgs();
338 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000339 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000340 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000341 // Hack to treat smart pointers and iterators as pointers;
342 // ignore any method named get().
343 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
344 CMCE->getNumArgs() == 0) {
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000345 if (NDeref && isCalleeArrow(CMCE->getCallee()))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000346 ++(*NDeref);
347 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000348 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000349 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000350 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000351 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000352 const Expr* const* CallArgs = CMCE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000353 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000354 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000355 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000356 NodeVec[Root].setSize(Sz + 1);
357 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000358 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000359 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000360 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000361 CallingContext LRCallCtx(CE->getDirectCallee());
362 LRCallCtx.NumArgs = CE->getNumArgs();
363 LRCallCtx.FunArgs = CE->getArgs();
364 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000365 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000366 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000367 // Treat smart pointers and iterators as pointers;
368 // ignore the * and -> operators.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000369 if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000370 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000371 if (k == OO_Star) {
372 if (NDeref) ++(*NDeref);
373 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
374 }
375 else if (k == OO_Arrow) {
376 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000377 }
378 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000379 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000380 unsigned Root = makeCall(NumCallArgs, 0);
381 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000382 const Expr* const* CallArgs = CE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000383 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000384 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000385 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000386 NodeVec[Root].setSize(Sz+1);
387 return Sz+1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000388 } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000389 unsigned Root = makeBinary();
390 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
391 Sz += buildSExpr(BOE->getRHS(), CallCtx);
392 NodeVec[Root].setSize(Sz);
393 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000394 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000395 // Ignore & and * operators -- they're no-ops.
396 // However, we try to figure out whether the expression is a pointer,
397 // so we can use . and -> appropriately in error messages.
398 if (UOE->getOpcode() == UO_Deref) {
399 if (NDeref) ++(*NDeref);
400 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
401 }
402 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000403 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
404 if (DRE->getDecl()->isCXXInstanceMember()) {
405 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
406 // We interpret this syntax specially, as a wildcard.
407 unsigned Root = makeDot(DRE->getDecl(), false);
408 makeWildcard();
409 NodeVec[Root].setSize(2);
410 return 2;
411 }
412 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000413 if (NDeref) --(*NDeref);
414 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
415 }
416 unsigned Root = makeUnary();
417 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
418 NodeVec[Root].setSize(Sz);
419 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000420 } else if (const ArraySubscriptExpr *ASE =
421 dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000422 unsigned Root = makeIndex();
423 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
424 Sz += buildSExpr(ASE->getIdx(), CallCtx);
425 NodeVec[Root].setSize(Sz);
426 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000427 } else if (const AbstractConditionalOperator *CE =
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000428 dyn_cast<AbstractConditionalOperator>(Exp)) {
429 unsigned Root = makeUnknown(3);
430 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
431 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
432 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
433 NodeVec[Root].setSize(Sz);
434 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000435 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000436 unsigned Root = makeUnknown(3);
437 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
438 Sz += buildSExpr(CE->getLHS(), CallCtx);
439 Sz += buildSExpr(CE->getRHS(), CallCtx);
440 NodeVec[Root].setSize(Sz);
441 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000442 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000443 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000444 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000445 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000446 } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000447 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000448 } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000449 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000450 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins0c1da202012-07-03 18:25:56 +0000451 isa<CXXNullPtrLiteralExpr>(Exp) ||
452 isa<GNUNullExpr>(Exp) ||
453 isa<CXXBoolLiteralExpr>(Exp) ||
454 isa<FloatingLiteral>(Exp) ||
455 isa<ImaginaryLiteral>(Exp) ||
456 isa<IntegerLiteral>(Exp) ||
457 isa<StringLiteral>(Exp) ||
458 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000459 makeNop();
460 return 1; // FIXME: Ignore literals for now
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000461 } else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000462 makeNop();
463 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000464 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000465 }
466
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000467 /// \brief Construct a SExpr from an expression.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000468 /// \param MutexExp The original mutex expression within an attribute
469 /// \param DeclExp An expression involving the Decl on which the attribute
470 /// occurs.
471 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000472 void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp,
473 const NamedDecl *D, VarDecl *SelfDecl = 0) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000474 CallingContext CallCtx(D);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000475
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000476 if (MutexExp) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000477 if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000478 if (SLit->getString() == StringRef("*"))
479 // The "*" expr is a universal lock, which essentially turns off
480 // checks until it is removed from the lockset.
481 makeUniversal();
482 else
483 // Ignore other string literals for now.
484 makeNop();
485 return;
486 }
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000487 }
488
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000489 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000490 if (DeclExp == 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000491 buildSExpr(MutexExp, 0);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000492 return;
493 }
494
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000495 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000496 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000497 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000498 CallCtx.SelfArg = ME->getBase();
499 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000500 } else if (const CXXMemberCallExpr *CE =
501 dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000502 CallCtx.SelfArg = CE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000503 CallCtx.SelfArrow = isCalleeArrow(CE->getCallee());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000504 CallCtx.NumArgs = CE->getNumArgs();
505 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000506 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000507 CallCtx.NumArgs = CE->getNumArgs();
508 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000509 } else if (const CXXConstructExpr *CE =
510 dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000511 CallCtx.SelfArg = 0; // Will be set below
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000512 CallCtx.NumArgs = CE->getNumArgs();
513 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +0000514 } else if (D && isa<CXXDestructorDecl>(D)) {
515 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000516 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000517 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000518
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000519 // Hack to handle constructors, where self cannot be recovered from
520 // the expression.
521 if (SelfDecl && !CallCtx.SelfArg) {
522 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
523 SelfDecl->getLocation());
524 CallCtx.SelfArg = &SelfDRE;
525
526 // If the attribute has no arguments, then assume the argument is "this".
527 if (MutexExp == 0)
528 buildSExpr(CallCtx.SelfArg, 0);
529 else // For most attributes.
530 buildSExpr(MutexExp, &CallCtx);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000531 return;
532 }
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000533
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000534 // If the attribute has no arguments, then assume the argument is "this".
535 if (MutexExp == 0)
536 buildSExpr(CallCtx.SelfArg, 0);
537 else // For most attributes.
538 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski33208342011-09-09 16:11:56 +0000539 }
540
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000541 /// \brief Get index of next sibling of node i.
542 unsigned getNextSibling(unsigned i) const {
543 return i + NodeVec[i].size();
544 }
545
Caitlin Sadowski33208342011-09-09 16:11:56 +0000546public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000547 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000548
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000549 /// \param MutexExp The original mutex expression within an attribute
550 /// \param DeclExp An expression involving the Decl on which the attribute
551 /// occurs.
552 /// \param D The declaration to which the lock/unlock attribute is attached.
553 /// Caller must check isValid() after construction.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000554 SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000555 VarDecl *SelfDecl=0) {
556 buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000557 }
558
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000559 /// Return true if this is a valid decl sequence.
560 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000561 bool isValid() const {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000562 return !NodeVec.empty();
Caitlin Sadowski33208342011-09-09 16:11:56 +0000563 }
564
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000565 bool shouldIgnore() const {
566 // Nop is a mutex that we have decided to deliberately ignore.
567 assert(NodeVec.size() > 0 && "Invalid Mutex");
568 return NodeVec[0].kind() == EOP_Nop;
569 }
570
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000571 bool isUniversal() const {
572 assert(NodeVec.size() > 0 && "Invalid Mutex");
573 return NodeVec[0].kind() == EOP_Universal;
574 }
575
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000576 /// Issue a warning about an invalid lock expression
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000577 static void warnInvalidLock(ThreadSafetyHandler &Handler,
578 const Expr *MutexExp,
579 const Expr *DeclExp, const NamedDecl* D) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000580 SourceLocation Loc;
581 if (DeclExp)
582 Loc = DeclExp->getExprLoc();
583
584 // FIXME: add a note about the attribute location in MutexExp or D
585 if (Loc.isValid())
586 Handler.handleInvalidLockExp(Loc);
587 }
588
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000589 bool operator==(const SExpr &other) const {
590 return NodeVec == other.NodeVec;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000591 }
592
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000593 bool operator!=(const SExpr &other) const {
Caitlin Sadowski33208342011-09-09 16:11:56 +0000594 return !(*this == other);
595 }
596
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000597 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
598 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchins138568b2012-09-11 23:04:49 +0000599 unsigned ni = NodeVec[i].arity();
600 unsigned nj = Other.NodeVec[j].arity();
601 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000602 bool Result = true;
603 unsigned ci = i+1; // first child of i
604 unsigned cj = j+1; // first child of j
605 for (unsigned k = 0; k < n;
606 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
607 Result = Result && matches(Other, ci, cj);
608 }
609 return Result;
610 }
611 return false;
612 }
613
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000614 // A partial match between a.mu and b.mu returns true a and b have the same
615 // type (and thus mu refers to the same mutex declaration), regardless of
616 // whether a and b are different objects or not.
617 bool partiallyMatches(const SExpr &Other) const {
618 if (NodeVec[0].kind() == EOP_Dot)
619 return NodeVec[0].matches(Other.NodeVec[0]);
620 return false;
621 }
622
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000623 /// \brief Pretty print a lock expression for use in error messages.
624 std::string toString(unsigned i = 0) const {
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000625 assert(isValid());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000626 if (i >= NodeVec.size())
627 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000628
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000629 const SExprNode* N = &NodeVec[i];
630 switch (N->kind()) {
631 case EOP_Nop:
632 return "_";
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000633 case EOP_Wildcard:
634 return "(?)";
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000635 case EOP_Universal:
636 return "*";
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000637 case EOP_This:
638 return "this";
639 case EOP_NVar:
640 case EOP_LVar: {
641 return N->getNamedDecl()->getNameAsString();
642 }
643 case EOP_Dot: {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000644 if (NodeVec[i+1].kind() == EOP_Wildcard) {
645 std::string S = "&";
646 S += N->getNamedDecl()->getQualifiedNameAsString();
647 return S;
648 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000649 std::string FieldName = N->getNamedDecl()->getNameAsString();
650 if (NodeVec[i+1].kind() == EOP_This)
651 return FieldName;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000652
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000653 std::string S = toString(i+1);
654 if (N->isArrow())
655 return S + "->" + FieldName;
656 else
657 return S + "." + FieldName;
658 }
659 case EOP_Call: {
660 std::string S = toString(i+1) + "(";
661 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000662 unsigned ci = getNextSibling(i+1);
663 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000664 S += toString(ci);
665 if (k+1 < NumArgs) S += ",";
666 }
667 S += ")";
668 return S;
669 }
670 case EOP_MCall: {
671 std::string S = "";
672 if (NodeVec[i+1].kind() != EOP_This)
673 S = toString(i+1) + ".";
674 if (const NamedDecl *D = N->getFunctionDecl())
675 S += D->getNameAsString() + "(";
676 else
677 S += "#(";
678 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000679 unsigned ci = getNextSibling(i+1);
680 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000681 S += toString(ci);
682 if (k+1 < NumArgs) S += ",";
683 }
684 S += ")";
685 return S;
686 }
687 case EOP_Index: {
688 std::string S1 = toString(i+1);
689 std::string S2 = toString(i+1 + NodeVec[i+1].size());
690 return S1 + "[" + S2 + "]";
691 }
692 case EOP_Unary: {
693 std::string S = toString(i+1);
694 return "#" + S;
695 }
696 case EOP_Binary: {
697 std::string S1 = toString(i+1);
698 std::string S2 = toString(i+1 + NodeVec[i+1].size());
699 return "(" + S1 + "#" + S2 + ")";
700 }
701 case EOP_Unknown: {
702 unsigned NumChildren = N->arity();
703 if (NumChildren == 0)
704 return "(...)";
705 std::string S = "(";
706 unsigned ci = i+1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000707 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000708 S += toString(ci);
709 if (j+1 < NumChildren) S += "#";
710 }
711 S += ")";
712 return S;
713 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000714 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000715 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000716 }
717};
718
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000719/// \brief A short list of SExprs
720class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000721public:
Aaron Ballmancea26092014-03-06 19:10:16 +0000722 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000723 void push_back_nodup(const SExpr& M) {
Aaron Ballmancea26092014-03-06 19:10:16 +0000724 if (end() == std::find(begin(), end(), M))
725 push_back(M);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000726 }
727};
728
Caitlin Sadowski33208342011-09-09 16:11:56 +0000729/// \brief This is a helper class that stores info about the most recent
730/// accquire of a Lock.
731///
732/// The main body of the analysis maps MutexIDs to LockDatas.
733struct LockData {
734 SourceLocation AcquireLoc;
735
736 /// \brief LKind stores whether a lock is held shared or exclusively.
737 /// Note that this analysis does not currently support either re-entrant
738 /// locking or lock "upgrading" and "downgrading" between exclusive and
739 /// shared.
740 ///
741 /// FIXME: add support for re-entrant locking and lock up/downgrading
742 LockKind LKind;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000743 bool Asserted; // for asserted locks
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000744 bool Managed; // for ScopedLockable objects
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000745 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski33208342011-09-09 16:11:56 +0000746
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000747 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false,
748 bool Asrt=false)
749 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000750 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000751 {}
752
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000753 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000754 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000755 UnderlyingMutex(Mu)
756 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000757
758 bool operator==(const LockData &other) const {
759 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
760 }
761
762 bool operator!=(const LockData &other) const {
763 return !(*this == other);
764 }
765
766 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000767 ID.AddInteger(AcquireLoc.getRawEncoding());
768 ID.AddInteger(LKind);
769 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000770
771 bool isAtLeast(LockKind LK) {
772 return (LK == LK_Shared) || (LKind == LK_Exclusive);
773 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000774};
775
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000776
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000777/// \brief A FactEntry stores a single fact that is known at a particular point
778/// in the program execution. Currently, this is information regarding a lock
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000779/// that is held at that point.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000780struct FactEntry {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000781 SExpr MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000782 LockData LDat;
783
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000784 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000785 : MutID(M), LDat(L)
786 { }
787};
788
789
790typedef unsigned short FactID;
791
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000792/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000793/// the analysis of a single routine.
794class FactManager {
795private:
796 std::vector<FactEntry> Facts;
797
798public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000799 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000800 Facts.push_back(FactEntry(M,L));
801 return static_cast<unsigned short>(Facts.size() - 1);
802 }
803
804 const FactEntry& operator[](FactID F) const { return Facts[F]; }
805 FactEntry& operator[](FactID F) { return Facts[F]; }
806};
807
808
809/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000810/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000811/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000812/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000813/// locks, so we can get away with doing a linear search for lookup. Note
814/// that a hashtable or map is inappropriate in this case, because lookups
815/// may involve partial pattern matches, rather than exact matches.
816class FactSet {
817private:
818 typedef SmallVector<FactID, 4> FactVec;
819
820 FactVec FactIDs;
821
822public:
823 typedef FactVec::iterator iterator;
824 typedef FactVec::const_iterator const_iterator;
825
826 iterator begin() { return FactIDs.begin(); }
827 const_iterator begin() const { return FactIDs.begin(); }
828
829 iterator end() { return FactIDs.end(); }
830 const_iterator end() const { return FactIDs.end(); }
831
832 bool isEmpty() const { return FactIDs.size() == 0; }
833
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000834 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000835 FactID F = FM.newLock(M, L);
836 FactIDs.push_back(F);
837 return F;
838 }
839
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000840 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000841 unsigned n = FactIDs.size();
842 if (n == 0)
843 return false;
844
845 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000846 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000847 FactIDs[i] = FactIDs[n-1];
848 FactIDs.pop_back();
849 return true;
850 }
851 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000852 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000853 FactIDs.pop_back();
854 return true;
855 }
856 return false;
857 }
858
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000859 // Returns an iterator
860 iterator findLockIter(FactManager &FM, const SExpr &M) {
861 for (iterator I = begin(), E = end(); I != E; ++I) {
862 const SExpr &Exp = FM[*I].MutID;
863 if (Exp.matches(M))
864 return I;
865 }
866 return end();
867 }
868
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000869 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000870 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000871 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000872 if (Exp.matches(M))
873 return &FM[*I].LDat;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000874 }
875 return 0;
876 }
877
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000878 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000879 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000880 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000881 if (Exp.matches(M) || Exp.isUniversal())
882 return &FM[*I].LDat;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000883 }
884 return 0;
885 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000886
887 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
888 for (const_iterator I=begin(), E=end(); I != E; ++I) {
889 const SExpr& Exp = FM[*I].MutID;
890 if (Exp.partiallyMatches(M)) return &FM[*I];
891 }
892 return 0;
893 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000894};
895
896
897
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000898/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski33208342011-09-09 16:11:56 +0000899/// been locked.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000900typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000901typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000902
903class LocalVariableMap;
904
Richard Smith92286672012-02-03 04:45:26 +0000905/// A side (entry or exit) of a CFG node.
906enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000907
908/// CFGBlockInfo is a struct which contains all the information that is
909/// maintained for each block in the CFG. See LocalVariableMap for more
910/// information about the contexts.
911struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000912 FactSet EntrySet; // Lockset held at entry to block
913 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000914 LocalVarContext EntryContext; // Context held at entry to block
915 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000916 SourceLocation EntryLoc; // Location of first statement in block
917 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000918 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000919 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000920
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000921 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000922 return Side == CBS_Entry ? EntrySet : ExitSet;
923 }
924 SourceLocation getLocation(CFGBlockSide Side) const {
925 return Side == CBS_Entry ? EntryLoc : ExitLoc;
926 }
927
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000928private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000929 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000930 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000931 { }
932
933public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000934 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000935};
936
937
938
939// A LocalVariableMap maintains a map from local variables to their currently
940// valid definitions. It provides SSA-like functionality when traversing the
941// CFG. Like SSA, each definition or assignment to a variable is assigned a
942// unique name (an integer), which acts as the SSA name for that definition.
943// The total set of names is shared among all CFG basic blocks.
944// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
945// with their SSA-names. Instead, we compute a Context for each point in the
946// code, which maps local variables to the appropriate SSA-name. This map
947// changes with each assignment.
948//
949// The map is computed in a single pass over the CFG. Subsequent analyses can
950// then query the map to find the appropriate Context for a statement, and use
951// that Context to look up the definitions of variables.
952class LocalVariableMap {
953public:
954 typedef LocalVarContext Context;
955
956 /// A VarDefinition consists of an expression, representing the value of the
957 /// variable, along with the context in which that expression should be
958 /// interpreted. A reference VarDefinition does not itself contain this
959 /// information, but instead contains a pointer to a previous VarDefinition.
960 struct VarDefinition {
961 public:
962 friend class LocalVariableMap;
963
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000964 const NamedDecl *Dec; // The original declaration for this variable.
965 const Expr *Exp; // The expression for this variable, OR
966 unsigned Ref; // Reference to another VarDefinition
967 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000968
969 bool isReference() { return !Exp; }
970
971 private:
972 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000973 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000974 : Dec(D), Exp(E), Ref(0), Ctx(C)
975 { }
976
977 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000978 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000979 : Dec(D), Exp(0), Ref(R), Ctx(C)
980 { }
981 };
982
983private:
984 Context::Factory ContextFactory;
985 std::vector<VarDefinition> VarDefinitions;
986 std::vector<unsigned> CtxIndices;
987 std::vector<std::pair<Stmt*, Context> > SavedContexts;
988
989public:
990 LocalVariableMap() {
991 // index 0 is a placeholder for undefined variables (aka phi-nodes).
992 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
993 }
994
995 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000996 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000997 const unsigned *i = Ctx.lookup(D);
998 if (!i)
999 return 0;
1000 assert(*i < VarDefinitions.size());
1001 return &VarDefinitions[*i];
1002 }
1003
1004 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001005 /// NULL if the expression is not statically known. If successful, also
1006 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001007 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001008 const unsigned *P = Ctx.lookup(D);
1009 if (!P)
1010 return 0;
1011
1012 unsigned i = *P;
1013 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001014 if (VarDefinitions[i].Exp) {
1015 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001016 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001017 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001018 i = VarDefinitions[i].Ref;
1019 }
1020 return 0;
1021 }
1022
1023 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1024
1025 /// Return the next context after processing S. This function is used by
1026 /// clients of the class to get the appropriate context when traversing the
1027 /// CFG. It must be called for every assignment or DeclStmt.
1028 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1029 if (SavedContexts[CtxIndex+1].first == S) {
1030 CtxIndex++;
1031 Context Result = SavedContexts[CtxIndex].second;
1032 return Result;
1033 }
1034 return C;
1035 }
1036
1037 void dumpVarDefinitionName(unsigned i) {
1038 if (i == 0) {
1039 llvm::errs() << "Undefined";
1040 return;
1041 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001042 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001043 if (!Dec) {
1044 llvm::errs() << "<<NULL>>";
1045 return;
1046 }
1047 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +00001048 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001049 }
1050
1051 /// Dumps an ASCII representation of the variable map to llvm::errs()
1052 void dump() {
1053 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001054 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001055 unsigned Ref = VarDefinitions[i].Ref;
1056
1057 dumpVarDefinitionName(i);
1058 llvm::errs() << " = ";
1059 if (Exp) Exp->dump();
1060 else {
1061 dumpVarDefinitionName(Ref);
1062 llvm::errs() << "\n";
1063 }
1064 }
1065 }
1066
1067 /// Dumps an ASCII representation of a Context to llvm::errs()
1068 void dumpContext(Context C) {
1069 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001070 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001071 D->printName(llvm::errs());
1072 const unsigned *i = C.lookup(D);
1073 llvm::errs() << " -> ";
1074 dumpVarDefinitionName(*i);
1075 llvm::errs() << "\n";
1076 }
1077 }
1078
1079 /// Builds the variable map.
1080 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1081 std::vector<CFGBlockInfo> &BlockInfo);
1082
1083protected:
1084 // Get the current context index
1085 unsigned getContextIndex() { return SavedContexts.size()-1; }
1086
1087 // Save the current context for later replay
1088 void saveContext(Stmt *S, Context C) {
1089 SavedContexts.push_back(std::make_pair(S,C));
1090 }
1091
1092 // Adds a new definition to the given context, and returns a new context.
1093 // This method should be called when declaring a new variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001094 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001095 assert(!Ctx.contains(D));
1096 unsigned newID = VarDefinitions.size();
1097 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1098 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1099 return NewCtx;
1100 }
1101
1102 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001103 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001104 unsigned newID = VarDefinitions.size();
1105 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1106 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1107 return NewCtx;
1108 }
1109
1110 // Updates a definition only if that definition is already in the map.
1111 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001112 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001113 if (Ctx.contains(D)) {
1114 unsigned newID = VarDefinitions.size();
1115 Context NewCtx = ContextFactory.remove(Ctx, D);
1116 NewCtx = ContextFactory.add(NewCtx, D, newID);
1117 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1118 return NewCtx;
1119 }
1120 return Ctx;
1121 }
1122
1123 // Removes a definition from the context, but keeps the variable name
1124 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001125 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001126 Context NewCtx = Ctx;
1127 if (NewCtx.contains(D)) {
1128 NewCtx = ContextFactory.remove(NewCtx, D);
1129 NewCtx = ContextFactory.add(NewCtx, D, 0);
1130 }
1131 return NewCtx;
1132 }
1133
1134 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001135 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001136 Context NewCtx = Ctx;
1137 if (NewCtx.contains(D)) {
1138 NewCtx = ContextFactory.remove(NewCtx, D);
1139 }
1140 return NewCtx;
1141 }
1142
1143 Context intersectContexts(Context C1, Context C2);
1144 Context createReferenceContext(Context C);
1145 void intersectBackEdge(Context C1, Context C2);
1146
1147 friend class VarMapBuilder;
1148};
1149
1150
1151// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001152CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1153 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001154}
1155
1156
1157/// Visitor which builds a LocalVariableMap
1158class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1159public:
1160 LocalVariableMap* VMap;
1161 LocalVariableMap::Context Ctx;
1162
1163 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1164 : VMap(VM), Ctx(C) {}
1165
1166 void VisitDeclStmt(DeclStmt *S);
1167 void VisitBinaryOperator(BinaryOperator *BO);
1168};
1169
1170
1171// Add new local variables to the variable map
1172void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1173 bool modifiedCtx = false;
1174 DeclGroupRef DGrp = S->getDeclGroup();
1175 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1176 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1177 Expr *E = VD->getInit();
1178
1179 // Add local variables with trivial type to the variable map
1180 QualType T = VD->getType();
1181 if (T.isTrivialType(VD->getASTContext())) {
1182 Ctx = VMap->addDefinition(VD, E, Ctx);
1183 modifiedCtx = true;
1184 }
1185 }
1186 }
1187 if (modifiedCtx)
1188 VMap->saveContext(S, Ctx);
1189}
1190
1191// Update local variable definitions in variable map
1192void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1193 if (!BO->isAssignmentOp())
1194 return;
1195
1196 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1197
1198 // Update the variable map and current context.
1199 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1200 ValueDecl *VDec = DRE->getDecl();
1201 if (Ctx.lookup(VDec)) {
1202 if (BO->getOpcode() == BO_Assign)
1203 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1204 else
1205 // FIXME -- handle compound assignment operators
1206 Ctx = VMap->clearDefinition(VDec, Ctx);
1207 VMap->saveContext(BO, Ctx);
1208 }
1209 }
1210}
1211
1212
1213// Computes the intersection of two contexts. The intersection is the
1214// set of variables which have the same definition in both contexts;
1215// variables with different definitions are discarded.
1216LocalVariableMap::Context
1217LocalVariableMap::intersectContexts(Context C1, Context C2) {
1218 Context Result = C1;
1219 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001220 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001221 unsigned i1 = I.getData();
1222 const unsigned *i2 = C2.lookup(Dec);
1223 if (!i2) // variable doesn't exist on second path
1224 Result = removeDefinition(Dec, Result);
1225 else if (*i2 != i1) // variable exists, but has different definition
1226 Result = clearDefinition(Dec, Result);
1227 }
1228 return Result;
1229}
1230
1231// For every variable in C, create a new variable that refers to the
1232// definition in C. Return a new context that contains these new variables.
1233// (We use this for a naive implementation of SSA on loop back-edges.)
1234LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1235 Context Result = getEmptyContext();
1236 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001237 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001238 unsigned i = I.getData();
1239 Result = addReference(Dec, i, Result);
1240 }
1241 return Result;
1242}
1243
1244// This routine also takes the intersection of C1 and C2, but it does so by
1245// altering the VarDefinitions. C1 must be the result of an earlier call to
1246// createReferenceContext.
1247void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1248 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001249 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001250 unsigned i1 = I.getData();
1251 VarDefinition *VDef = &VarDefinitions[i1];
1252 assert(VDef->isReference());
1253
1254 const unsigned *i2 = C2.lookup(Dec);
1255 if (!i2 || (*i2 != i1))
1256 VDef->Ref = 0; // Mark this variable as undefined
1257 }
1258}
1259
1260
1261// Traverse the CFG in topological order, so all predecessors of a block
1262// (excluding back-edges) are visited before the block itself. At
1263// each point in the code, we calculate a Context, which holds the set of
1264// variable definitions which are visible at that point in execution.
1265// Visible variables are mapped to their definitions using an array that
1266// contains all definitions.
1267//
1268// At join points in the CFG, the set is computed as the intersection of
1269// the incoming sets along each edge, E.g.
1270//
1271// { Context | VarDefinitions }
1272// int x = 0; { x -> x1 | x1 = 0 }
1273// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1274// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1275// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1276// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1277//
1278// This is essentially a simpler and more naive version of the standard SSA
1279// algorithm. Those definitions that remain in the intersection are from blocks
1280// that strictly dominate the current block. We do not bother to insert proper
1281// phi nodes, because they are not used in our analysis; instead, wherever
1282// a phi node would be required, we simply remove that definition from the
1283// context (E.g. x above).
1284//
1285// The initial traversal does not capture back-edges, so those need to be
1286// handled on a separate pass. Whenever the first pass encounters an
1287// incoming back edge, it duplicates the context, creating new definitions
1288// that refer back to the originals. (These correspond to places where SSA
1289// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001290// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001291// node was actually required.) E.g.
1292//
1293// { Context | VarDefinitions }
1294// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1295// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1296// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1297// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1298//
1299void LocalVariableMap::traverseCFG(CFG *CFGraph,
1300 PostOrderCFGView *SortedGraph,
1301 std::vector<CFGBlockInfo> &BlockInfo) {
1302 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1303
1304 CtxIndices.resize(CFGraph->getNumBlockIDs());
1305
1306 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1307 E = SortedGraph->end(); I!= E; ++I) {
1308 const CFGBlock *CurrBlock = *I;
1309 int CurrBlockID = CurrBlock->getBlockID();
1310 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1311
1312 VisitedBlocks.insert(CurrBlock);
1313
1314 // Calculate the entry context for the current block
1315 bool HasBackEdges = false;
1316 bool CtxInit = true;
1317 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1318 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1319 // if *PI -> CurrBlock is a back edge, so skip it
1320 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1321 HasBackEdges = true;
1322 continue;
1323 }
1324
1325 int PrevBlockID = (*PI)->getBlockID();
1326 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1327
1328 if (CtxInit) {
1329 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1330 CtxInit = false;
1331 }
1332 else {
1333 CurrBlockInfo->EntryContext =
1334 intersectContexts(CurrBlockInfo->EntryContext,
1335 PrevBlockInfo->ExitContext);
1336 }
1337 }
1338
1339 // Duplicate the context if we have back-edges, so we can call
1340 // intersectBackEdges later.
1341 if (HasBackEdges)
1342 CurrBlockInfo->EntryContext =
1343 createReferenceContext(CurrBlockInfo->EntryContext);
1344
1345 // Create a starting context index for the current block
1346 saveContext(0, CurrBlockInfo->EntryContext);
1347 CurrBlockInfo->EntryIndex = getContextIndex();
1348
1349 // Visit all the statements in the basic block.
1350 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1351 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1352 BE = CurrBlock->end(); BI != BE; ++BI) {
1353 switch (BI->getKind()) {
1354 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00001355 CFGStmt CS = BI->castAs<CFGStmt>();
1356 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001357 break;
1358 }
1359 default:
1360 break;
1361 }
1362 }
1363 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1364
1365 // Mark variables on back edges as "unknown" if they've been changed.
1366 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1367 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1368 // if CurrBlock -> *SI is *not* a back edge
1369 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1370 continue;
1371
1372 CFGBlock *FirstLoopBlock = *SI;
1373 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1374 Context LoopEnd = CurrBlockInfo->ExitContext;
1375 intersectBackEdge(LoopBegin, LoopEnd);
1376 }
1377 }
1378
1379 // Put an extra entry at the end of the indexed context array
1380 unsigned exitID = CFGraph->getExit().getBlockID();
1381 saveContext(0, BlockInfo[exitID].ExitContext);
1382}
1383
Richard Smith92286672012-02-03 04:45:26 +00001384/// Find the appropriate source locations to use when producing diagnostics for
1385/// each block in the CFG.
1386static void findBlockLocations(CFG *CFGraph,
1387 PostOrderCFGView *SortedGraph,
1388 std::vector<CFGBlockInfo> &BlockInfo) {
1389 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1390 E = SortedGraph->end(); I!= E; ++I) {
1391 const CFGBlock *CurrBlock = *I;
1392 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1393
1394 // Find the source location of the last statement in the block, if the
1395 // block is not empty.
1396 if (const Stmt *S = CurrBlock->getTerminator()) {
1397 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1398 } else {
1399 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1400 BE = CurrBlock->rend(); BI != BE; ++BI) {
1401 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001402 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1403 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001404 break;
1405 }
1406 }
1407 }
1408
1409 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1410 // This block contains at least one statement. Find the source location
1411 // of the first statement in the block.
1412 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1413 BE = CurrBlock->end(); BI != BE; ++BI) {
1414 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001415 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1416 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001417 break;
1418 }
1419 }
1420 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1421 CurrBlock != &CFGraph->getExit()) {
1422 // The block is empty, and has a single predecessor. Use its exit
1423 // location.
1424 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1425 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1426 }
1427 }
1428}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001429
1430/// \brief Class which implements the core thread safety analysis routines.
1431class ThreadSafetyAnalyzer {
1432 friend class BuildLockset;
1433
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001434 ThreadSafetyHandler &Handler;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001435 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001436 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001437 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001438
1439public:
1440 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1441
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001442 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1443 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001444 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001445
1446 template <typename AttrType>
1447 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001448 const NamedDecl *D, VarDecl *SelfDecl=0);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001449
1450 template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001451 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1452 const NamedDecl *D,
1453 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1454 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001455
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001456 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1457 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001458
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001459 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1460 const CFGBlock* PredBlock,
1461 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001462
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001463 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1464 SourceLocation JoinLoc,
1465 LockErrorKind LEK1, LockErrorKind LEK2,
1466 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001467
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001468 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1469 SourceLocation JoinLoc, LockErrorKind LEK1,
1470 bool Modify=true) {
1471 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001472 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001473
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001474 void runAnalysis(AnalysisDeclContext &AC);
1475};
1476
Caitlin Sadowski33208342011-09-09 16:11:56 +00001477
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001478/// \brief Add a new lock to the lockset, warning if the lock is already there.
1479/// \param Mutex -- the Mutex expression for the lock
1480/// \param LDat -- the LockData for the lock
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001481void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001482 const LockData &LDat) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001483 // FIXME: deal with acquired before/after annotations.
1484 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001485 if (Mutex.shouldIgnore())
1486 return;
1487
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001488 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001489 if (!LDat.Asserted)
1490 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001491 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001492 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001493 }
1494}
1495
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001496
1497/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenek78094ca2012-08-22 23:50:41 +00001498/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001499/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001500void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001501 const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001502 SourceLocation UnlockLoc,
1503 bool FullyRemove) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001504 if (Mutex.shouldIgnore())
1505 return;
1506
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001507 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001508 if (!LDat) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001509 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001510 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001511 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001512
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001513 if (LDat->UnderlyingMutex.isValid()) {
1514 // This is scoped lockable object, which manages the real mutex.
1515 if (FullyRemove) {
1516 // We're destroying the managing object.
1517 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001518 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1519 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001520 } else {
1521 // We're releasing the underlying mutex, but not destroying the
1522 // managing object. Warn on dual release.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001523 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001524 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001525 UnlockLoc);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001526 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001527 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1528 return;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001529 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001530 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001531 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001532}
1533
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001534
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001535/// \brief Extract the list of mutexIDs from the attribute on an expression,
1536/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001537template <typename AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001538void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001539 Expr *Exp, const NamedDecl *D,
1540 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001541 typedef typename AttrType::args_iterator iterator_type;
1542
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001543 if (Attr->args_size() == 0) {
1544 // The mutex held is the "this" object.
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001545 SExpr Mu(0, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001546 if (!Mu.isValid())
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001547 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001548 else
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001549 Mtxs.push_back_nodup(Mu);
1550 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001551 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001552
1553 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001554 SExpr Mu(*I, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001555 if (!Mu.isValid())
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001556 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001557 else
1558 Mtxs.push_back_nodup(Mu);
1559 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001560}
1561
1562
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001563/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1564/// trylock applies to the given edge, then push them onto Mtxs, discarding
1565/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001566template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001567void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1568 Expr *Exp, const NamedDecl *D,
1569 const CFGBlock *PredBlock,
1570 const CFGBlock *CurrBlock,
1571 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001572 // Find out which branch has the lock
1573 bool branch = 0;
1574 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1575 branch = BLE->getValue();
1576 }
1577 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1578 branch = ILE->getValue().getBoolValue();
1579 }
1580 int branchnum = branch ? 0 : 1;
1581 if (Neg) branchnum = !branchnum;
1582
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001583 // If we've taken the trylock branch, then add the lock
1584 int i = 0;
1585 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1586 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1587 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001588 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001589 }
1590 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001591}
1592
1593
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001594bool getStaticBooleanValue(Expr* E, bool& TCond) {
1595 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1596 TCond = false;
1597 return true;
1598 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1599 TCond = BLE->getValue();
1600 return true;
1601 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1602 TCond = ILE->getValue().getBoolValue();
1603 return true;
1604 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1605 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1606 }
1607 return false;
1608}
1609
1610
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001611// If Cond can be traced back to a function call, return the call expression.
1612// The negate variable should be called with false, and will be set to true
1613// if the function call is negated, e.g. if (!mu.tryLock(...))
1614const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1615 LocalVarContext C,
1616 bool &Negate) {
1617 if (!Cond)
1618 return 0;
1619
1620 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1621 return CallExp;
1622 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001623 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1624 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1625 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001626 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1627 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1628 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001629 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1630 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1631 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001632 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1633 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1634 return getTrylockCallExpr(E, C, Negate);
1635 }
1636 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1637 if (UOP->getOpcode() == UO_LNot) {
1638 Negate = !Negate;
1639 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1640 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001641 return 0;
1642 }
1643 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1644 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1645 if (BOP->getOpcode() == BO_NE)
1646 Negate = !Negate;
1647
1648 bool TCond = false;
1649 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1650 if (!TCond) Negate = !Negate;
1651 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1652 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001653 TCond = false;
1654 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001655 if (!TCond) Negate = !Negate;
1656 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1657 }
1658 return 0;
1659 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001660 if (BOP->getOpcode() == BO_LAnd) {
1661 // LHS must have been evaluated in a different block.
1662 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1663 }
1664 if (BOP->getOpcode() == BO_LOr) {
1665 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1666 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001667 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001668 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001669 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001670}
1671
1672
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001673/// \brief Find the lockset that holds on the edge between PredBlock
1674/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1675/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001676void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1677 const FactSet &ExitSet,
1678 const CFGBlock *PredBlock,
1679 const CFGBlock *CurrBlock) {
1680 Result = ExitSet;
1681
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001682 const Stmt *Cond = PredBlock->getTerminatorCondition();
1683 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001684 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001685
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001686 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001687 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1688 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1689
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001690 CallExpr *Exp =
1691 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001692 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001693 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001694
1695 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1696 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001697 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001698
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001699 MutexIDList ExclusiveLocksToAdd;
1700 MutexIDList SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001701
1702 // If the condition is a call to a Trylock function, then grab the attributes
1703 AttrVec &ArgAttrs = FunDecl->getAttrs();
1704 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1705 Attr *Attr = ArgAttrs[i];
1706 switch (Attr->getKind()) {
1707 case attr::ExclusiveTrylockFunction: {
1708 ExclusiveTrylockFunctionAttr *A =
1709 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001710 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1711 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001712 break;
1713 }
1714 case attr::SharedTrylockFunction: {
1715 SharedTrylockFunctionAttr *A =
1716 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001717 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001718 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001719 break;
1720 }
1721 default:
1722 break;
1723 }
1724 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001725
1726 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001727 SourceLocation Loc = Exp->getExprLoc();
1728 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001729 addLock(Result, ExclusiveLocksToAdd[i],
1730 LockData(Loc, LK_Exclusive));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001731 }
1732 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001733 addLock(Result, SharedLocksToAdd[i],
1734 LockData(Loc, LK_Shared));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001735 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001736}
1737
1738
Caitlin Sadowski33208342011-09-09 16:11:56 +00001739/// \brief We use this class to visit different types of expressions in
1740/// CFGBlocks, and build up the lockset.
1741/// An expression may cause us to add or remove locks from the lockset, or else
1742/// output error messages related to missing locks.
1743/// FIXME: In future, we may be able to not inherit from a visitor.
1744class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001745 friend class ThreadSafetyAnalyzer;
1746
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001747 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001748 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001749 LocalVariableMap::Context LVarCtx;
1750 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001751
1752 // Helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001753 const ValueDecl *getValueDecl(const Expr *Exp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001754
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001755 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001756 Expr *MutexExp, ProtectedOperationKind POK);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001757 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001758
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001759 void checkAccess(const Expr *Exp, AccessKind AK);
1760 void checkPtAccess(const Expr *Exp, AccessKind AK);
1761
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001762 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001763
Caitlin Sadowski33208342011-09-09 16:11:56 +00001764public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001765 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001766 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001767 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001768 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001769 LVarCtx(Info.EntryContext),
1770 CtxIndex(Info.EntryIndex)
1771 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001772
1773 void VisitUnaryOperator(UnaryOperator *UO);
1774 void VisitBinaryOperator(BinaryOperator *BO);
1775 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001776 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001777 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001778 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001779};
1780
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001781
Caitlin Sadowski33208342011-09-09 16:11:56 +00001782/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001783const ValueDecl *BuildLockset::getValueDecl(const Expr *Exp) {
1784 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Exp))
1785 return getValueDecl(CE->getSubExpr());
1786
Caitlin Sadowski33208342011-09-09 16:11:56 +00001787 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1788 return DR->getDecl();
1789
1790 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1791 return ME->getMemberDecl();
1792
1793 return 0;
1794}
1795
1796/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001797/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001798void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001799 AccessKind AK, Expr *MutexExp,
1800 ProtectedOperationKind POK) {
1801 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001802
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001803 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001804 if (!Mutex.isValid()) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001805 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001806 return;
1807 } else if (Mutex.shouldIgnore()) {
1808 return;
1809 }
1810
1811 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001812 bool NoError = true;
1813 if (!LDat) {
1814 // No exact match found. Look for a partial match.
1815 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1816 if (FEntry) {
1817 // Warn that there's no precise match.
1818 LDat = &FEntry->LDat;
1819 std::string PartMatchStr = FEntry->MutID.toString();
1820 StringRef PartMatchName(PartMatchStr);
1821 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1822 Exp->getExprLoc(), &PartMatchName);
1823 } else {
1824 // Warn that there's no match at all.
1825 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1826 Exp->getExprLoc());
1827 }
1828 NoError = false;
1829 }
1830 // Make sure the mutex we found is the right kind.
1831 if (NoError && LDat && !LDat->isAtLeast(LK))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001832 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001833 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001834}
1835
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001836/// \brief Warn if the LSet contains the given lock.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001837void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr* Exp,
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001838 Expr *MutexExp) {
1839 SExpr Mutex(MutexExp, Exp, D);
1840 if (!Mutex.isValid()) {
1841 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1842 return;
1843 }
1844
1845 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001846 if (LDat) {
1847 std::string DeclName = D->getNameAsString();
1848 StringRef DeclNameSR (DeclName);
1849 Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(),
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001850 Exp->getExprLoc());
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001851 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001852}
1853
1854
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001855/// \brief Checks guarded_by and pt_guarded_by attributes.
1856/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1857/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1858/// Similarly, we check if the access is to an expression that dereferences
1859/// a pointer marked with pt_guarded_by.
1860void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1861 Exp = Exp->IgnoreParenCasts();
1862
1863 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1864 // For dereferences
1865 if (UO->getOpcode() == clang::UO_Deref)
1866 checkPtAccess(UO->getSubExpr(), AK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001867 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001868 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001869
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001870 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1871 if (Analyzer->Handler.issueBetaWarnings()) {
1872 checkPtAccess(AE->getLHS(), AK);
1873 return;
1874 }
1875 }
1876
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001877 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1878 if (ME->isArrow())
1879 checkPtAccess(ME->getBase(), AK);
1880 else
1881 checkAccess(ME->getBase(), AK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001882 }
1883
Caitlin Sadowski33208342011-09-09 16:11:56 +00001884 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001885 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001886 return;
1887
Aaron Ballman9ead1242013-12-19 02:39:40 +00001888 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001889 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1890 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001891
Aaron Ballmanee58e6d2013-12-19 15:35:31 +00001892 for (specific_attr_iterator<GuardedByAttr>
1893 I = D->specific_attr_begin<GuardedByAttr>(),
1894 E = D->specific_attr_end<GuardedByAttr>(); I != E; ++I)
1895 warnIfMutexNotHeld(D, Exp, AK, (*I)->getArg(), POK_VarAccess);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001896}
1897
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001898/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1899void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001900 if (Analyzer->Handler.issueBetaWarnings()) {
1901 while (true) {
1902 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1903 Exp = PE->getSubExpr();
1904 continue;
1905 }
1906 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1907 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1908 // If it's an actual array, and not a pointer, then it's elements
1909 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1910 checkAccess(CE->getSubExpr(), AK);
1911 return;
1912 }
1913 Exp = CE->getSubExpr();
1914 continue;
1915 }
1916 break;
1917 }
1918 }
1919 else
1920 Exp = Exp->IgnoreParenCasts();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001921
1922 const ValueDecl *D = getValueDecl(Exp);
1923 if (!D || !D->hasAttrs())
1924 return;
1925
Aaron Ballman9ead1242013-12-19 02:39:40 +00001926 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001927 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1928 Exp->getExprLoc());
1929
Aaron Ballmanee58e6d2013-12-19 15:35:31 +00001930 for (specific_attr_iterator<PtGuardedByAttr>
1931 I = D->specific_attr_begin<PtGuardedByAttr>(),
1932 E = D->specific_attr_end<PtGuardedByAttr>(); I != E; ++I)
1933 warnIfMutexNotHeld(D, Exp, AK, (*I)->getArg(), POK_VarDereference);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001934}
1935
1936
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001937/// \brief Process a function call, method call, constructor call,
1938/// or destructor call. This involves looking at the attributes on the
1939/// corresponding function/method/constructor/destructor, issuing warnings,
1940/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001941///
1942/// FIXME: For classes annotated with one of the guarded annotations, we need
1943/// to treat const method calls as reads and non-const method calls as writes,
1944/// and check that the appropriate locks are held. Non-const method calls with
1945/// the same signature as const method calls can be also treated as reads.
1946///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001947void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001948 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001949 const AttrVec &ArgAttrs = D->getAttrs();
1950 MutexIDList ExclusiveLocksToAdd;
1951 MutexIDList SharedLocksToAdd;
1952 MutexIDList LocksToRemove;
1953
Caitlin Sadowski33208342011-09-09 16:11:56 +00001954 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001955 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1956 switch (At->getKind()) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001957 // When we encounter an exclusive lock function, we need to add the lock
1958 // to our lockset with kind exclusive.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001959 case attr::ExclusiveLockFunction: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001960 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001961 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D, VD);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001962 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001963 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001964
1965 // When we encounter a shared lock function, we need to add the lock
1966 // to our lockset with kind shared.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001967 case attr::SharedLockFunction: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001968 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001969 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D, VD);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001970 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001971 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001972
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001973 // An assert will add a lock to the lockset, but will not generate
1974 // a warning if it is already there, and will not generate a warning
1975 // if it is not removed.
1976 case attr::AssertExclusiveLock: {
1977 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1978
1979 MutexIDList AssertLocks;
1980 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1981 for (unsigned i=0,n=AssertLocks.size(); i<n; ++i) {
1982 Analyzer->addLock(FSet, AssertLocks[i],
1983 LockData(Loc, LK_Exclusive, false, true));
1984 }
1985 break;
1986 }
1987 case attr::AssertSharedLock: {
1988 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1989
1990 MutexIDList AssertLocks;
1991 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1992 for (unsigned i=0,n=AssertLocks.size(); i<n; ++i) {
1993 Analyzer->addLock(FSet, AssertLocks[i],
1994 LockData(Loc, LK_Shared, false, true));
1995 }
1996 break;
1997 }
1998
Caitlin Sadowski33208342011-09-09 16:11:56 +00001999 // When we encounter an unlock function, we need to remove unlocked
2000 // mutexes from the lockset, and flag a warning if they are not there.
2001 case attr::UnlockFunction: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002002 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00002003 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D, VD);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002004 break;
2005 }
2006
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002007 case attr::RequiresCapability: {
2008 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002009
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002010 for (RequiresCapabilityAttr::args_iterator I = A->args_begin(),
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002011 E = A->args_end(); I != E; ++I)
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002012 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, *I,
2013 POK_FunctionCall);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002014 break;
2015 }
2016
2017 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002018 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00002019
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002020 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
2021 E = A->args_end(); I != E; ++I) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00002022 warnIfMutexHeld(D, Exp, *I);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002023 }
2024 break;
2025 }
2026
Alp Tokerd4733632013-12-05 04:47:09 +00002027 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00002028 default:
2029 break;
2030 }
2031 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002032
2033 // Figure out if we're calling the constructor of scoped lockable class
2034 bool isScopedVar = false;
2035 if (VD) {
2036 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
2037 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00002038 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002039 isScopedVar = true;
2040 }
2041 }
2042
2043 // Add locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002044 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002045 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
2046 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002047 }
2048 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002049 Analyzer->addLock(FSet, SharedLocksToAdd[i],
2050 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002051 }
2052
2053 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2054 // FIXME -- this doesn't work if we acquire multiple locks.
2055 if (isScopedVar) {
2056 SourceLocation MLoc = VD->getLocation();
2057 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002058 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002059
2060 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002061 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
2062 ExclusiveLocksToAdd[i]));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002063 }
2064 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002065 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
2066 SharedLocksToAdd[i]));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002067 }
2068 }
2069
2070 // Remove locks.
2071 // FIXME -- should only fully remove if the attribute refers to 'this'.
2072 bool Dtor = isa<CXXDestructorDecl>(D);
2073 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002074 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002075 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002076}
2077
DeLesley Hutchins9d530332012-01-06 19:16:50 +00002078
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002079/// \brief For unary operations which read and write a variable, we need to
2080/// check whether we hold any required mutexes. Reads are checked in
2081/// VisitCastExpr.
2082void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2083 switch (UO->getOpcode()) {
2084 case clang::UO_PostDec:
2085 case clang::UO_PostInc:
2086 case clang::UO_PreDec:
2087 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002088 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002089 break;
2090 }
2091 default:
2092 break;
2093 }
2094}
2095
2096/// For binary operations which assign to a variable (writes), we need to check
2097/// whether we hold any required mutexes.
2098/// FIXME: Deal with non-primitive types.
2099void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2100 if (!BO->isAssignmentOp())
2101 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002102
2103 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002104 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002105
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002106 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002107}
2108
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002109
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002110/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2111/// need to ensure we hold any required mutexes.
2112/// FIXME: Deal with non-primitive types.
2113void BuildLockset::VisitCastExpr(CastExpr *CE) {
2114 if (CE->getCastKind() != CK_LValueToRValue)
2115 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002116 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002117}
2118
2119
DeLesley Hutchins714296c2011-12-29 00:56:48 +00002120void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002121 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2122 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2123 // ME can be null when calling a method pointer
2124 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002125
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002126 if (ME && MD) {
2127 if (ME->isArrow()) {
2128 if (MD->isConst()) {
2129 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2130 } else { // FIXME -- should be AK_Written
2131 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002132 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002133 } else {
2134 if (MD->isConst())
2135 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2136 else // FIXME -- should be AK_Written
2137 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002138 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002139 }
2140 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2141 switch (OE->getOperator()) {
2142 case OO_Equal: {
2143 const Expr *Target = OE->getArg(0);
2144 const Expr *Source = OE->getArg(1);
2145 checkAccess(Target, AK_Written);
2146 checkAccess(Source, AK_Read);
2147 break;
2148 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002149 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002150 case OO_Arrow:
2151 case OO_Subscript: {
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002152 if (Analyzer->Handler.issueBetaWarnings()) {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002153 const Expr *Obj = OE->getArg(0);
2154 checkAccess(Obj, AK_Read);
2155 checkPtAccess(Obj, AK_Read);
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002156 }
2157 break;
2158 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002159 default: {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002160 const Expr *Obj = OE->getArg(0);
2161 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002162 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002163 }
2164 }
2165 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002166 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2167 if(!D || !D->hasAttrs())
2168 return;
2169 handleCall(Exp, D);
2170}
2171
2172void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002173 const CXXConstructorDecl *D = Exp->getConstructor();
2174 if (D && D->isCopyConstructor()) {
2175 const Expr* Source = Exp->getArg(0);
2176 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002177 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002178 // FIXME -- only handles constructors in DeclStmt below.
2179}
2180
2181void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002182 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002183 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002184
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002185 DeclGroupRef DGrp = S->getDeclGroup();
2186 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2187 Decl *D = *I;
2188 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2189 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002190 // handle constructors that involve temporaries
2191 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2192 E = EWC->getSubExpr();
2193
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002194 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2195 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2196 if (!CtorD || !CtorD->hasAttrs())
2197 return;
2198 handleCall(CE, CtorD, VD);
2199 }
2200 }
2201 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002202}
2203
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002204
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002205
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002206/// \brief Compute the intersection of two locksets and issue warnings for any
2207/// locks in the symmetric difference.
2208///
2209/// This function is used at a merge point in the CFG when comparing the lockset
2210/// of each branch being merged. For example, given the following sequence:
2211/// A; if () then B; else C; D; we need to check that the lockset after B and C
2212/// are the same. In the event of a difference, we use the intersection of these
2213/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002214///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002215/// \param FSet1 The first lockset.
2216/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002217/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002218/// \param LEK1 The error message to report if a mutex is missing from LSet1
2219/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002220void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2221 const FactSet &FSet2,
2222 SourceLocation JoinLoc,
2223 LockErrorKind LEK1,
2224 LockErrorKind LEK2,
2225 bool Modify) {
2226 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002227
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002228 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002229 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2230 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002231 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002232 const LockData &LDat2 = FactMan[*I].LDat;
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002233 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002234
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002235 if (I1 != FSet1.end()) {
2236 const LockData* LDat1 = &FactMan[*I1].LDat;
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002237 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002238 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002239 LDat2.AcquireLoc,
2240 LDat1->AcquireLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002241 if (Modify && LDat1->LKind != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002242 // Take the exclusive lock, which is the one in FSet2.
2243 *I1 = *I;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002244 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002245 }
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002246 else if (LDat1->Asserted && !LDat2.Asserted) {
2247 // The non-asserted lock in FSet2 is the one we want to track.
2248 *I1 = *I;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002249 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002250 } else {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002251 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002252 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002253 // If this is a scoped lock that manages another mutex, and if the
2254 // underlying mutex is still held, then warn about the underlying
2255 // mutex.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002256 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002257 LDat2.AcquireLoc,
2258 JoinLoc, LEK1);
2259 }
2260 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002261 else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted)
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002262 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002263 LDat2.AcquireLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002264 JoinLoc, LEK1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002265 }
2266 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002267
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002268 // Find locks in FSet1 that are not in FSet2, and remove them.
2269 for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002270 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002271 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002272 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002273
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002274 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002275 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002276 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002277 // If this is a scoped lock that manages another mutex, and if the
2278 // underlying mutex is still held, then warn about the underlying
2279 // mutex.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002280 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002281 LDat1.AcquireLoc,
2282 JoinLoc, LEK1);
2283 }
2284 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002285 else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted)
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002286 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002287 LDat1.AcquireLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002288 JoinLoc, LEK2);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002289 if (Modify)
2290 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002291 }
2292 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002293}
2294
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002295
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002296// Return true if block B never continues to its successors.
2297inline bool neverReturns(const CFGBlock* B) {
2298 if (B->hasNoReturnElement())
2299 return true;
2300 if (B->empty())
2301 return false;
2302
2303 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002304 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2305 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002306 return true;
2307 }
2308 return false;
2309}
2310
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002311
Caitlin Sadowski33208342011-09-09 16:11:56 +00002312/// \brief Check a function's CFG for thread-safety violations.
2313///
2314/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2315/// at the end of each block, and issue warnings for thread safety violations.
2316/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002317void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002318 CFG *CFGraph = AC.getCFG();
2319 if (!CFGraph) return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002320 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2321
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002322 // AC.dumpCFG(true);
2323
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002324 if (!D)
2325 return; // Ignore anonymous functions for now.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002326 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002327 return;
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002328 // FIXME: Do something a bit more intelligent inside constructor and
2329 // destructor code. Constructors and destructors must assume unique access
2330 // to 'this', so checks on member variable access is disabled, but we should
2331 // still enable checks on other objects.
2332 if (isa<CXXConstructorDecl>(D))
2333 return; // Don't check inside constructors.
2334 if (isa<CXXDestructorDecl>(D))
2335 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002336
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002337 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002338 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002339
2340 // We need to explore the CFG via a "topological" ordering.
2341 // That way, we will be guaranteed to have information about required
2342 // predecessor locksets when exploring a new block.
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002343 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2344 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002345
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002346 // Mark entry block as reachable
2347 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2348
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002349 // Compute SSA names for local variables
2350 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2351
Richard Smith92286672012-02-03 04:45:26 +00002352 // Fill in source locations for all CFGBlocks.
2353 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2354
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002355 MutexIDList ExclusiveLocksAcquired;
2356 MutexIDList SharedLocksAcquired;
2357 MutexIDList LocksReleased;
2358
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002359 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002360 // to initial lockset. Also turn off checking for lock and unlock functions.
2361 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002362 if (!SortedGraph->empty() && D->hasAttrs()) {
2363 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002364 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002365 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002366
2367 MutexIDList ExclusiveLocksToAdd;
2368 MutexIDList SharedLocksToAdd;
2369
2370 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002371 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002372 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002373 Loc = Attr->getLocation();
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002374 if (RequiresCapabilityAttr *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2375 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2376 0, D);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002377 } else if (UnlockFunctionAttr *A = dyn_cast<UnlockFunctionAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002378 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2379 // We must ignore such methods.
2380 if (A->args_size() == 0)
2381 return;
2382 // FIXME -- deal with exclusive vs. shared unlock functions?
2383 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2384 getMutexIDs(LocksReleased, A, (Expr*) 0, D);
2385 } else if (ExclusiveLockFunctionAttr *A
2386 = dyn_cast<ExclusiveLockFunctionAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002387 if (A->args_size() == 0)
2388 return;
2389 getMutexIDs(ExclusiveLocksAcquired, A, (Expr*) 0, D);
2390 } else if (SharedLockFunctionAttr *A
2391 = dyn_cast<SharedLockFunctionAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002392 if (A->args_size() == 0)
2393 return;
2394 getMutexIDs(SharedLocksAcquired, A, (Expr*) 0, D);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002395 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2396 // Don't try to check trylock functions for now
2397 return;
2398 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2399 // Don't try to check trylock functions for now
2400 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002401 }
2402 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002403
2404 // FIXME -- Loc can be wrong here.
2405 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002406 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2407 LockData(Loc, LK_Exclusive));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002408 }
2409 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002410 addLock(InitialLockset, SharedLocksToAdd[i],
2411 LockData(Loc, LK_Shared));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002412 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002413 }
2414
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002415 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2416 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002417 const CFGBlock *CurrBlock = *I;
2418 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002419 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002420
2421 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002422 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002423
2424 // Iterate through the predecessor blocks and warn if the lockset for all
2425 // predecessors is not the same. We take the entry lockset of the current
2426 // block to be the intersection of all previous locksets.
2427 // FIXME: By keeping the intersection, we may output more errors in future
2428 // for a lock which is not in the intersection, but was in the union. We
2429 // may want to also keep the union in future. As an example, let's say
2430 // the intersection contains Mutex L, and the union contains L and M.
2431 // Later we unlock M. At this point, we would output an error because we
2432 // never locked M; although the real error is probably that we forgot to
2433 // lock M on all code paths. Conversely, let's say that later we lock M.
2434 // In this case, we should compare against the intersection instead of the
2435 // union because the real error is probably that we forgot to unlock M on
2436 // all code paths.
2437 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002438 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002439 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2440 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2441
2442 // if *PI -> CurrBlock is a back edge
2443 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2444 continue;
2445
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002446 int PrevBlockID = (*PI)->getBlockID();
2447 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2448
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002449 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002450 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002451 continue;
2452
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002453 // Okay, we can reach this block from the entry.
2454 CurrBlockInfo->Reachable = true;
2455
Richard Smith815b29d2012-02-03 03:30:07 +00002456 // If the previous block ended in a 'continue' or 'break' statement, then
2457 // a difference in locksets is probably due to a bug in that block, rather
2458 // than in some other predecessor. In that case, keep the other
2459 // predecessor's lockset.
2460 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2461 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2462 SpecialBlocks.push_back(*PI);
2463 continue;
2464 }
2465 }
2466
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002467 FactSet PrevLockset;
2468 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002469
Caitlin Sadowski33208342011-09-09 16:11:56 +00002470 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002471 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002472 LocksetInitialized = true;
2473 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002474 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2475 CurrBlockInfo->EntryLoc,
2476 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002477 }
2478 }
2479
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002480 // Skip rest of block if it's not reachable.
2481 if (!CurrBlockInfo->Reachable)
2482 continue;
2483
Richard Smith815b29d2012-02-03 03:30:07 +00002484 // Process continue and break blocks. Assume that the lockset for the
2485 // resulting block is unaffected by any discrepancies in them.
2486 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2487 SpecialI < SpecialN; ++SpecialI) {
2488 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2489 int PrevBlockID = PrevBlock->getBlockID();
2490 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2491
2492 if (!LocksetInitialized) {
2493 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2494 LocksetInitialized = true;
2495 } else {
2496 // Determine whether this edge is a loop terminator for diagnostic
2497 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2498 // it might also be part of a switch. Also, a subsequent destructor
2499 // might add to the lockset, in which case the real issue might be a
2500 // double lock on the other path.
2501 const Stmt *Terminator = PrevBlock->getTerminator();
2502 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2503
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002504 FactSet PrevLockset;
2505 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2506 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002507
Richard Smith815b29d2012-02-03 03:30:07 +00002508 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002509 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2510 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002511 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002512 : LEK_LockedSomePredecessors,
2513 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002514 }
2515 }
2516
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002517 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2518
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002519 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002520 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2521 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002522 switch (BI->getKind()) {
2523 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002524 CFGStmt CS = BI->castAs<CFGStmt>();
2525 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002526 break;
2527 }
2528 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2529 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002530 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2531 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2532 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002533 if (!DD->hasAttrs())
2534 break;
2535
2536 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002537 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002538 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002539 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002540 LocksetBuilder.handleCall(&DRE, DD);
2541 break;
2542 }
2543 default:
2544 break;
2545 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002546 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002547 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002548
2549 // For every back edge from CurrBlock (the end of the loop) to another block
2550 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2551 // the one held at the beginning of FirstLoopBlock. We can look up the
2552 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2553 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2554 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2555
2556 // if CurrBlock -> *SI is *not* a back edge
2557 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2558 continue;
2559
2560 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002561 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2562 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2563 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2564 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002565 LEK_LockedSomeLoopIterations,
2566 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002567 }
2568 }
2569
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002570 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2571 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002572
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002573 // Skip the final check if the exit block is unreachable.
2574 if (!Final->Reachable)
2575 return;
2576
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002577 // By default, we expect all locks held on entry to be held on exit.
2578 FactSet ExpectedExitSet = Initial->EntrySet;
2579
2580 // Adjust the expected exit set by adding or removing locks, as declared
2581 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2582 // issue the appropriate warning.
2583 // FIXME: the location here is not quite right.
2584 for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) {
2585 ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i],
2586 LockData(D->getLocation(), LK_Exclusive));
2587 }
2588 for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) {
2589 ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i],
2590 LockData(D->getLocation(), LK_Shared));
2591 }
2592 for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) {
2593 ExpectedExitSet.removeLock(FactMan, LocksReleased[i]);
2594 }
2595
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002596 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002597 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002598 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002599 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002600 LEK_NotLockedAtEndOfFunction,
2601 false);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002602}
2603
2604} // end anonymous namespace
2605
2606
2607namespace clang {
2608namespace thread_safety {
2609
2610/// \brief Check a function's CFG for thread-safety violations.
2611///
2612/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2613/// at the end of each block, and issue warnings for thread safety violations.
2614/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002615void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002616 ThreadSafetyHandler &Handler) {
2617 ThreadSafetyAnalyzer Analyzer(Handler);
2618 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002619}
2620
2621/// \brief Helper function that returns a LockKind required for the given level
2622/// of access.
2623LockKind getLockKindFromAccessKind(AccessKind AK) {
2624 switch (AK) {
2625 case AK_Read :
2626 return LK_Shared;
2627 case AK_Written :
2628 return LK_Exclusive;
2629 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002630 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002631}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002632
Caitlin Sadowski33208342011-09-09 16:11:56 +00002633}} // end namespace clang::thread_safety