blob: 77785d3e29f36e48c90b976cc73b5ca42766b3a2 [file] [log] [blame]
Caitlin Sadowski402aa062011-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//
Caitlin Sadowski19903462011-09-14 20:05:09 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
14// information.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek439ed162011-10-22 02:14:27 +000019#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000020#include "clang/Analysis/AnalysisContext.h"
21#include "clang/Analysis/CFG.h"
22#include "clang/Analysis/CFGStmtMap.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000023#include "clang/AST/DeclCXX.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtVisitor.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceLocation.h"
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +000029#include "clang/Basic/OperatorKinds.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/ImmutableMap.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000036#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000037#include <algorithm>
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000038#include <utility>
Caitlin Sadowski402aa062011-09-09 16:11:56 +000039#include <vector>
40
41using namespace clang;
42using namespace thread_safety;
43
Caitlin Sadowski19903462011-09-14 20:05:09 +000044// Key method definition
45ThreadSafetyHandler::~ThreadSafetyHandler() {}
46
Caitlin Sadowski402aa062011-09-09 16:11:56 +000047namespace {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +000048
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000049/// SExpr implements a simple expression language that is used to store,
50/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
51/// does not capture surface syntax, and it does not distinguish between
52/// C++ concepts, like pointers and references, that have no real semantic
53/// differences. This simplicity allows SExprs to be meaningfully compared,
54/// e.g.
55/// (x) = x
56/// (*this).foo = this->foo
57/// *&a = a
Caitlin Sadowski402aa062011-09-09 16:11:56 +000058///
59/// Thread-safety analysis works by comparing lock expressions. Within the
60/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
61/// a particular mutex object at run-time. Subsequent occurrences of the same
62/// expression (where "same" means syntactic equality) will refer to the same
63/// run-time object if three conditions hold:
64/// (1) Local variables in the expression, such as "x" have not changed.
65/// (2) Values on the heap that affect the expression have not changed.
66/// (3) The expression involves only pure function calls.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +000067///
Caitlin Sadowski402aa062011-09-09 16:11:56 +000068/// The current implementation assumes, but does not verify, that multiple uses
69/// of the same lock expression satisfies these criteria.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000070class SExpr {
71private:
72 enum ExprOp {
Ted Kremenekad0fe032012-08-22 23:50:41 +000073 EOP_Nop, ///< No-op
74 EOP_Wildcard, ///< Matches anything.
75 EOP_This, ///< This keyword.
76 EOP_NVar, ///< Named variable.
77 EOP_LVar, ///< Local variable.
78 EOP_Dot, ///< Field access
79 EOP_Call, ///< Function call
80 EOP_MCall, ///< Method call
81 EOP_Index, ///< Array index
82 EOP_Unary, ///< Unary operation
83 EOP_Binary, ///< Binary operation
84 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000085 };
86
87
88 class SExprNode {
89 private:
Ted Kremenekad0fe032012-08-22 23:50:41 +000090 unsigned char Op; ///< Opcode of the root node
91 unsigned char Flags; ///< Additional opcode-specific data
92 unsigned short Sz; ///< Number of child nodes
93 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000094
95 public:
96 SExprNode(ExprOp O, unsigned F, const void* D)
97 : Op(static_cast<unsigned char>(O)),
98 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
99 { }
100
101 unsigned size() const { return Sz; }
102 void setSize(unsigned S) { Sz = S; }
103
104 ExprOp kind() const { return static_cast<ExprOp>(Op); }
105
106 const NamedDecl* getNamedDecl() const {
107 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
108 return reinterpret_cast<const NamedDecl*>(Data);
109 }
110
111 const NamedDecl* getFunctionDecl() const {
112 assert(Op == EOP_Call || Op == EOP_MCall);
113 return reinterpret_cast<const NamedDecl*>(Data);
114 }
115
116 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
117 void setArrow(bool A) { Flags = A ? 1 : 0; }
118
119 unsigned arity() const {
120 switch (Op) {
121 case EOP_Nop: return 0;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000122 case EOP_Wildcard: return 0;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000123 case EOP_NVar: return 0;
124 case EOP_LVar: return 0;
125 case EOP_This: return 0;
126 case EOP_Dot: return 1;
127 case EOP_Call: return Flags+1; // First arg is function.
128 case EOP_MCall: return Flags+1; // First arg is implicit obj.
129 case EOP_Index: return 2;
130 case EOP_Unary: return 1;
131 case EOP_Binary: return 2;
132 case EOP_Unknown: return Flags;
133 }
134 return 0;
135 }
136
137 bool operator==(const SExprNode& Other) const {
138 // Ignore flags and size -- they don't matter.
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000139 return (Op == Other.Op &&
140 Data == Other.Data);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000141 }
142
143 bool operator!=(const SExprNode& Other) const {
144 return !(*this == Other);
145 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000146
147 bool matches(const SExprNode& Other) const {
148 return (*this == Other) ||
149 (Op == EOP_Wildcard) ||
150 (Other.Op == EOP_Wildcard);
151 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000152 };
153
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000154
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000155 /// \brief Encapsulates the lexical context of a function call. The lexical
156 /// context includes the arguments to the call, including the implicit object
157 /// argument. When an attribute containing a mutex expression is attached to
158 /// a method, the expression may refer to formal parameters of the method.
159 /// Actual arguments must be substituted for formal parameters to derive
160 /// the appropriate mutex expression in the lexical context where the function
161 /// is called. PrevCtx holds the context in which the arguments themselves
162 /// should be evaluated; multiple calling contexts can be chained together
163 /// by the lock_returned attribute.
164 struct CallingContext {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000165 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
166 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
167 bool SelfArrow; // is Self referred to with -> or .?
168 unsigned NumArgs; // Number of funArgs
169 Expr** FunArgs; // Function arguments
170 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000171
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000172 CallingContext(const NamedDecl *D = 0, Expr *S = 0,
173 unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
174 : AttrDecl(D), SelfArg(S), SelfArrow(false),
175 NumArgs(N), FunArgs(A), PrevCtx(P)
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000176 { }
177 };
178
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000179 typedef SmallVector<SExprNode, 4> NodeVector;
180
181private:
182 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
183 // the list to be traversed as a tree.
184 NodeVector NodeVec;
185
186private:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000187 unsigned makeNop() {
188 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
189 return NodeVec.size()-1;
190 }
191
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000192 unsigned makeWildcard() {
193 NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
194 return NodeVec.size()-1;
195 }
196
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000197 unsigned makeNamedVar(const NamedDecl *D) {
198 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
199 return NodeVec.size()-1;
200 }
201
202 unsigned makeLocalVar(const NamedDecl *D) {
203 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
204 return NodeVec.size()-1;
205 }
206
207 unsigned makeThis() {
208 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
209 return NodeVec.size()-1;
210 }
211
212 unsigned makeDot(const NamedDecl *D, bool Arrow) {
213 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
214 return NodeVec.size()-1;
215 }
216
217 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
218 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
219 return NodeVec.size()-1;
220 }
221
222 unsigned makeMCall(unsigned NumArgs, const NamedDecl *D) {
223 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, D));
224 return NodeVec.size()-1;
225 }
226
227 unsigned makeIndex() {
228 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
229 return NodeVec.size()-1;
230 }
231
232 unsigned makeUnary() {
233 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
234 return NodeVec.size()-1;
235 }
236
237 unsigned makeBinary() {
238 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
239 return NodeVec.size()-1;
240 }
241
242 unsigned makeUnknown(unsigned Arity) {
243 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
244 return NodeVec.size()-1;
245 }
246
247 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000248 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000249 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000250 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000251 ///
252 /// NDeref returns the number of Derefence and AddressOf operations
253 /// preceeding the Expr; this is used to decide whether to pretty-print
254 /// SExprs with . or ->.
255 unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
256 if (!Exp)
257 return 0;
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000258
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000259 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
260 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000261 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
262 if (PV) {
263 FunctionDecl *FD =
264 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
265 unsigned i = PV->getFunctionScopeIndex();
266
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000267 if (CallCtx && CallCtx->FunArgs &&
268 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000269 // Substitute call arguments for references to function parameters
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000270 assert(i < CallCtx->NumArgs);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000271 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000272 }
273 // Map the param back to the param of the original function declaration.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000274 makeNamedVar(FD->getParamDecl(i));
275 return 1;
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000276 }
277 // Not a function parameter -- just store the reference.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000278 makeNamedVar(ND);
279 return 1;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000280 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000281 // Substitute parent for 'this'
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000282 if (CallCtx && CallCtx->SelfArg) {
283 if (!CallCtx->SelfArrow && NDeref)
284 // 'this' is a pointer, but self is not, so need to take address.
285 --(*NDeref);
286 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
287 }
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000288 else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000289 makeThis();
290 return 1;
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000291 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000292 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
293 NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000294 int ImplicitDeref = ME->isArrow() ? 1 : 0;
295 unsigned Root = makeDot(ND, false);
296 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
297 NodeVec[Root].setArrow(ImplicitDeref > 0);
298 NodeVec[Root].setSize(Sz + 1);
299 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000300 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000301 // When calling a function with a lock_returned attribute, replace
302 // the function call with the expression in lock_returned.
303 if (LockReturnedAttr* At =
304 CMCE->getMethodDecl()->getAttr<LockReturnedAttr>()) {
305 CallingContext LRCallCtx(CMCE->getMethodDecl());
306 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000307 LRCallCtx.SelfArrow =
308 dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000309 LRCallCtx.NumArgs = CMCE->getNumArgs();
310 LRCallCtx.FunArgs = CMCE->getArgs();
311 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000312 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000313 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000314 // Hack to treat smart pointers and iterators as pointers;
315 // ignore any method named get().
316 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
317 CMCE->getNumArgs() == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000318 if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
319 ++(*NDeref);
320 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000321 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000322 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000323 unsigned Root =
324 makeMCall(NumCallArgs, CMCE->getMethodDecl()->getCanonicalDecl());
325 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000326 Expr** CallArgs = CMCE->getArgs();
327 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000328 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000329 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000330 NodeVec[Root].setSize(Sz + 1);
331 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000332 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000333 if (LockReturnedAttr* At =
334 CE->getDirectCallee()->getAttr<LockReturnedAttr>()) {
335 CallingContext LRCallCtx(CE->getDirectCallee());
336 LRCallCtx.NumArgs = CE->getNumArgs();
337 LRCallCtx.FunArgs = CE->getArgs();
338 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000339 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000340 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000341 // Treat smart pointers and iterators as pointers;
342 // ignore the * and -> operators.
343 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
344 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000345 if (k == OO_Star) {
346 if (NDeref) ++(*NDeref);
347 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
348 }
349 else if (k == OO_Arrow) {
350 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000351 }
352 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000353 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000354 unsigned Root = makeCall(NumCallArgs, 0);
355 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000356 Expr** CallArgs = CE->getArgs();
357 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000358 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000359 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000360 NodeVec[Root].setSize(Sz+1);
361 return Sz+1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000362 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000363 unsigned Root = makeBinary();
364 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
365 Sz += buildSExpr(BOE->getRHS(), CallCtx);
366 NodeVec[Root].setSize(Sz);
367 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000368 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000369 // Ignore & and * operators -- they're no-ops.
370 // However, we try to figure out whether the expression is a pointer,
371 // so we can use . and -> appropriately in error messages.
372 if (UOE->getOpcode() == UO_Deref) {
373 if (NDeref) ++(*NDeref);
374 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
375 }
376 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000377 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
378 if (DRE->getDecl()->isCXXInstanceMember()) {
379 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
380 // We interpret this syntax specially, as a wildcard.
381 unsigned Root = makeDot(DRE->getDecl(), false);
382 makeWildcard();
383 NodeVec[Root].setSize(2);
384 return 2;
385 }
386 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000387 if (NDeref) --(*NDeref);
388 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
389 }
390 unsigned Root = makeUnary();
391 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
392 NodeVec[Root].setSize(Sz);
393 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000394 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000395 unsigned Root = makeIndex();
396 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
397 Sz += buildSExpr(ASE->getIdx(), CallCtx);
398 NodeVec[Root].setSize(Sz);
399 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000400 } else if (AbstractConditionalOperator *CE =
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000401 dyn_cast<AbstractConditionalOperator>(Exp)) {
402 unsigned Root = makeUnknown(3);
403 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
404 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
405 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
406 NodeVec[Root].setSize(Sz);
407 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000408 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000409 unsigned Root = makeUnknown(3);
410 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
411 Sz += buildSExpr(CE->getLHS(), CallCtx);
412 Sz += buildSExpr(CE->getRHS(), CallCtx);
413 NodeVec[Root].setSize(Sz);
414 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000415 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000416 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000417 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000418 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000419 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000420 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000421 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000422 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000423 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000424 isa<CXXNullPtrLiteralExpr>(Exp) ||
425 isa<GNUNullExpr>(Exp) ||
426 isa<CXXBoolLiteralExpr>(Exp) ||
427 isa<FloatingLiteral>(Exp) ||
428 isa<ImaginaryLiteral>(Exp) ||
429 isa<IntegerLiteral>(Exp) ||
430 isa<StringLiteral>(Exp) ||
431 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000432 makeNop();
433 return 1; // FIXME: Ignore literals for now
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000434 } else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000435 makeNop();
436 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000437 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000438 }
439
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000440 /// \brief Construct a SExpr from an expression.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000441 /// \param MutexExp The original mutex expression within an attribute
442 /// \param DeclExp An expression involving the Decl on which the attribute
443 /// occurs.
444 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000445 void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000446 CallingContext CallCtx(D);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000447
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000448 // Ignore string literals
449 if (MutexExp && isa<StringLiteral>(MutexExp)) {
450 makeNop();
451 return;
452 }
453
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000454 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000455 if (DeclExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000456 buildSExpr(MutexExp, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000457 return;
458 }
459
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000460 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000461 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000462 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000463 CallCtx.SelfArg = ME->getBase();
464 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000465 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000466 CallCtx.SelfArg = CE->getImplicitObjectArgument();
467 CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
468 CallCtx.NumArgs = CE->getNumArgs();
469 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000470 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000471 CallCtx.NumArgs = CE->getNumArgs();
472 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000473 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000474 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
475 CallCtx.NumArgs = CE->getNumArgs();
476 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000477 } else if (D && isa<CXXDestructorDecl>(D)) {
478 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000479 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000480 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000481
482 // If the attribute has no arguments, then assume the argument is "this".
483 if (MutexExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000484 buildSExpr(CallCtx.SelfArg, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000485 return;
486 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000487
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000488 // For most attributes.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000489 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000490 }
491
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000492 /// \brief Get index of next sibling of node i.
493 unsigned getNextSibling(unsigned i) const {
494 return i + NodeVec[i].size();
495 }
496
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000497public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000498 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000499
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000500 /// \param MutexExp The original mutex expression within an attribute
501 /// \param DeclExp An expression involving the Decl on which the attribute
502 /// occurs.
503 /// \param D The declaration to which the lock/unlock attribute is attached.
504 /// Caller must check isValid() after construction.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000505 SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
506 buildSExprFromExpr(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000507 }
508
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000509 /// Return true if this is a valid decl sequence.
510 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000511 bool isValid() const {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000512 return !NodeVec.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000513 }
514
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000515 bool shouldIgnore() const {
516 // Nop is a mutex that we have decided to deliberately ignore.
517 assert(NodeVec.size() > 0 && "Invalid Mutex");
518 return NodeVec[0].kind() == EOP_Nop;
519 }
520
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000521 /// Issue a warning about an invalid lock expression
522 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
523 Expr *DeclExp, const NamedDecl* D) {
524 SourceLocation Loc;
525 if (DeclExp)
526 Loc = DeclExp->getExprLoc();
527
528 // FIXME: add a note about the attribute location in MutexExp or D
529 if (Loc.isValid())
530 Handler.handleInvalidLockExp(Loc);
531 }
532
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000533 bool operator==(const SExpr &other) const {
534 return NodeVec == other.NodeVec;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000535 }
536
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000537 bool operator!=(const SExpr &other) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000538 return !(*this == other);
539 }
540
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000541 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
542 if (NodeVec[i].matches(Other.NodeVec[j])) {
543 unsigned n = NodeVec[i].arity();
544 bool Result = true;
545 unsigned ci = i+1; // first child of i
546 unsigned cj = j+1; // first child of j
547 for (unsigned k = 0; k < n;
548 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
549 Result = Result && matches(Other, ci, cj);
550 }
551 return Result;
552 }
553 return false;
554 }
555
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000556 /// \brief Pretty print a lock expression for use in error messages.
557 std::string toString(unsigned i = 0) const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000558 assert(isValid());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000559 if (i >= NodeVec.size())
560 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000561
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000562 const SExprNode* N = &NodeVec[i];
563 switch (N->kind()) {
564 case EOP_Nop:
565 return "_";
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000566 case EOP_Wildcard:
567 return "(?)";
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000568 case EOP_This:
569 return "this";
570 case EOP_NVar:
571 case EOP_LVar: {
572 return N->getNamedDecl()->getNameAsString();
573 }
574 case EOP_Dot: {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000575 if (NodeVec[i+1].kind() == EOP_Wildcard) {
576 std::string S = "&";
577 S += N->getNamedDecl()->getQualifiedNameAsString();
578 return S;
579 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000580 std::string FieldName = N->getNamedDecl()->getNameAsString();
581 if (NodeVec[i+1].kind() == EOP_This)
582 return FieldName;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000583
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000584 std::string S = toString(i+1);
585 if (N->isArrow())
586 return S + "->" + FieldName;
587 else
588 return S + "." + FieldName;
589 }
590 case EOP_Call: {
591 std::string S = toString(i+1) + "(";
592 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000593 unsigned ci = getNextSibling(i+1);
594 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000595 S += toString(ci);
596 if (k+1 < NumArgs) S += ",";
597 }
598 S += ")";
599 return S;
600 }
601 case EOP_MCall: {
602 std::string S = "";
603 if (NodeVec[i+1].kind() != EOP_This)
604 S = toString(i+1) + ".";
605 if (const NamedDecl *D = N->getFunctionDecl())
606 S += D->getNameAsString() + "(";
607 else
608 S += "#(";
609 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000610 unsigned ci = getNextSibling(i+1);
611 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000612 S += toString(ci);
613 if (k+1 < NumArgs) S += ",";
614 }
615 S += ")";
616 return S;
617 }
618 case EOP_Index: {
619 std::string S1 = toString(i+1);
620 std::string S2 = toString(i+1 + NodeVec[i+1].size());
621 return S1 + "[" + S2 + "]";
622 }
623 case EOP_Unary: {
624 std::string S = toString(i+1);
625 return "#" + S;
626 }
627 case EOP_Binary: {
628 std::string S1 = toString(i+1);
629 std::string S2 = toString(i+1 + NodeVec[i+1].size());
630 return "(" + S1 + "#" + S2 + ")";
631 }
632 case EOP_Unknown: {
633 unsigned NumChildren = N->arity();
634 if (NumChildren == 0)
635 return "(...)";
636 std::string S = "(";
637 unsigned ci = i+1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000638 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000639 S += toString(ci);
640 if (j+1 < NumChildren) S += "#";
641 }
642 S += ")";
643 return S;
644 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000645 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000646 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000647 }
648};
649
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000650
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000651
652/// \brief A short list of SExprs
653class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000654public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000655 /// \brief Return true if the list contains the specified SExpr
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000656 /// Performs a linear search, because these lists are almost always very small.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000657 bool contains(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000658 for (iterator I=begin(),E=end(); I != E; ++I)
659 if ((*I) == M) return true;
660 return false;
661 }
662
663 /// \brief Push M onto list, bud discard duplicates
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000664 void push_back_nodup(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000665 if (!contains(M)) push_back(M);
666 }
667};
668
669
670
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000671/// \brief This is a helper class that stores info about the most recent
672/// accquire of a Lock.
673///
674/// The main body of the analysis maps MutexIDs to LockDatas.
675struct LockData {
676 SourceLocation AcquireLoc;
677
678 /// \brief LKind stores whether a lock is held shared or exclusively.
679 /// Note that this analysis does not currently support either re-entrant
680 /// locking or lock "upgrading" and "downgrading" between exclusive and
681 /// shared.
682 ///
683 /// FIXME: add support for re-entrant locking and lock up/downgrading
684 LockKind LKind;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000685 bool Managed; // for ScopedLockable objects
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000686 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000687
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000688 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
689 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
690 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000691 {}
692
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000693 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000694 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
695 UnderlyingMutex(Mu)
696 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000697
698 bool operator==(const LockData &other) const {
699 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
700 }
701
702 bool operator!=(const LockData &other) const {
703 return !(*this == other);
704 }
705
706 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000707 ID.AddInteger(AcquireLoc.getRawEncoding());
708 ID.AddInteger(LKind);
709 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000710};
711
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000712
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000713/// \brief A FactEntry stores a single fact that is known at a particular point
714/// in the program execution. Currently, this is information regarding a lock
715/// that is held at that point.
716struct FactEntry {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000717 SExpr MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000718 LockData LDat;
719
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000720 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000721 : MutID(M), LDat(L)
722 { }
723};
724
725
726typedef unsigned short FactID;
727
728/// \brief FactManager manages the memory for all facts that are created during
729/// the analysis of a single routine.
730class FactManager {
731private:
732 std::vector<FactEntry> Facts;
733
734public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000735 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000736 Facts.push_back(FactEntry(M,L));
737 return static_cast<unsigned short>(Facts.size() - 1);
738 }
739
740 const FactEntry& operator[](FactID F) const { return Facts[F]; }
741 FactEntry& operator[](FactID F) { return Facts[F]; }
742};
743
744
745/// \brief A FactSet is the set of facts that are known to be true at a
746/// particular program point. FactSets must be small, because they are
747/// frequently copied, and are thus implemented as a set of indices into a
748/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
749/// locks, so we can get away with doing a linear search for lookup. Note
750/// that a hashtable or map is inappropriate in this case, because lookups
751/// may involve partial pattern matches, rather than exact matches.
752class FactSet {
753private:
754 typedef SmallVector<FactID, 4> FactVec;
755
756 FactVec FactIDs;
757
758public:
759 typedef FactVec::iterator iterator;
760 typedef FactVec::const_iterator const_iterator;
761
762 iterator begin() { return FactIDs.begin(); }
763 const_iterator begin() const { return FactIDs.begin(); }
764
765 iterator end() { return FactIDs.end(); }
766 const_iterator end() const { return FactIDs.end(); }
767
768 bool isEmpty() const { return FactIDs.size() == 0; }
769
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000770 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000771 FactID F = FM.newLock(M, L);
772 FactIDs.push_back(F);
773 return F;
774 }
775
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000776 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000777 unsigned n = FactIDs.size();
778 if (n == 0)
779 return false;
780
781 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000782 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000783 FactIDs[i] = FactIDs[n-1];
784 FactIDs.pop_back();
785 return true;
786 }
787 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000788 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000789 FactIDs.pop_back();
790 return true;
791 }
792 return false;
793 }
794
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000795 LockData* findLock(FactManager& FM, const SExpr& M) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000796 for (const_iterator I=begin(), E=end(); I != E; ++I) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000797 if (FM[*I].MutID.matches(M)) return &FM[*I].LDat;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000798 }
799 return 0;
800 }
801};
802
803
804
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000805/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000806/// been locked.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000807typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000808typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000809
810class LocalVariableMap;
811
Richard Smith2e515622012-02-03 04:45:26 +0000812/// A side (entry or exit) of a CFG node.
813enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000814
815/// CFGBlockInfo is a struct which contains all the information that is
816/// maintained for each block in the CFG. See LocalVariableMap for more
817/// information about the contexts.
818struct CFGBlockInfo {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000819 FactSet EntrySet; // Lockset held at entry to block
820 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000821 LocalVarContext EntryContext; // Context held at entry to block
822 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000823 SourceLocation EntryLoc; // Location of first statement in block
824 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000825 unsigned EntryIndex; // Used to replay contexts later
826
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000827 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith2e515622012-02-03 04:45:26 +0000828 return Side == CBS_Entry ? EntrySet : ExitSet;
829 }
830 SourceLocation getLocation(CFGBlockSide Side) const {
831 return Side == CBS_Entry ? EntryLoc : ExitLoc;
832 }
833
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000834private:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000835 CFGBlockInfo(LocalVarContext EmptyCtx)
836 : EntryContext(EmptyCtx), ExitContext(EmptyCtx)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000837 { }
838
839public:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000840 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000841};
842
843
844
845// A LocalVariableMap maintains a map from local variables to their currently
846// valid definitions. It provides SSA-like functionality when traversing the
847// CFG. Like SSA, each definition or assignment to a variable is assigned a
848// unique name (an integer), which acts as the SSA name for that definition.
849// The total set of names is shared among all CFG basic blocks.
850// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
851// with their SSA-names. Instead, we compute a Context for each point in the
852// code, which maps local variables to the appropriate SSA-name. This map
853// changes with each assignment.
854//
855// The map is computed in a single pass over the CFG. Subsequent analyses can
856// then query the map to find the appropriate Context for a statement, and use
857// that Context to look up the definitions of variables.
858class LocalVariableMap {
859public:
860 typedef LocalVarContext Context;
861
862 /// A VarDefinition consists of an expression, representing the value of the
863 /// variable, along with the context in which that expression should be
864 /// interpreted. A reference VarDefinition does not itself contain this
865 /// information, but instead contains a pointer to a previous VarDefinition.
866 struct VarDefinition {
867 public:
868 friend class LocalVariableMap;
869
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000870 const NamedDecl *Dec; // The original declaration for this variable.
871 const Expr *Exp; // The expression for this variable, OR
872 unsigned Ref; // Reference to another VarDefinition
873 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000874
875 bool isReference() { return !Exp; }
876
877 private:
878 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000879 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000880 : Dec(D), Exp(E), Ref(0), Ctx(C)
881 { }
882
883 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000884 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000885 : Dec(D), Exp(0), Ref(R), Ctx(C)
886 { }
887 };
888
889private:
890 Context::Factory ContextFactory;
891 std::vector<VarDefinition> VarDefinitions;
892 std::vector<unsigned> CtxIndices;
893 std::vector<std::pair<Stmt*, Context> > SavedContexts;
894
895public:
896 LocalVariableMap() {
897 // index 0 is a placeholder for undefined variables (aka phi-nodes).
898 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
899 }
900
901 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000902 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000903 const unsigned *i = Ctx.lookup(D);
904 if (!i)
905 return 0;
906 assert(*i < VarDefinitions.size());
907 return &VarDefinitions[*i];
908 }
909
910 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000911 /// NULL if the expression is not statically known. If successful, also
912 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000913 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000914 const unsigned *P = Ctx.lookup(D);
915 if (!P)
916 return 0;
917
918 unsigned i = *P;
919 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000920 if (VarDefinitions[i].Exp) {
921 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000922 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000923 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000924 i = VarDefinitions[i].Ref;
925 }
926 return 0;
927 }
928
929 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
930
931 /// Return the next context after processing S. This function is used by
932 /// clients of the class to get the appropriate context when traversing the
933 /// CFG. It must be called for every assignment or DeclStmt.
934 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
935 if (SavedContexts[CtxIndex+1].first == S) {
936 CtxIndex++;
937 Context Result = SavedContexts[CtxIndex].second;
938 return Result;
939 }
940 return C;
941 }
942
943 void dumpVarDefinitionName(unsigned i) {
944 if (i == 0) {
945 llvm::errs() << "Undefined";
946 return;
947 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000948 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000949 if (!Dec) {
950 llvm::errs() << "<<NULL>>";
951 return;
952 }
953 Dec->printName(llvm::errs());
954 llvm::errs() << "." << i << " " << ((void*) Dec);
955 }
956
957 /// Dumps an ASCII representation of the variable map to llvm::errs()
958 void dump() {
959 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000960 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000961 unsigned Ref = VarDefinitions[i].Ref;
962
963 dumpVarDefinitionName(i);
964 llvm::errs() << " = ";
965 if (Exp) Exp->dump();
966 else {
967 dumpVarDefinitionName(Ref);
968 llvm::errs() << "\n";
969 }
970 }
971 }
972
973 /// Dumps an ASCII representation of a Context to llvm::errs()
974 void dumpContext(Context C) {
975 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000976 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000977 D->printName(llvm::errs());
978 const unsigned *i = C.lookup(D);
979 llvm::errs() << " -> ";
980 dumpVarDefinitionName(*i);
981 llvm::errs() << "\n";
982 }
983 }
984
985 /// Builds the variable map.
986 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
987 std::vector<CFGBlockInfo> &BlockInfo);
988
989protected:
990 // Get the current context index
991 unsigned getContextIndex() { return SavedContexts.size()-1; }
992
993 // Save the current context for later replay
994 void saveContext(Stmt *S, Context C) {
995 SavedContexts.push_back(std::make_pair(S,C));
996 }
997
998 // Adds a new definition to the given context, and returns a new context.
999 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001000 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001001 assert(!Ctx.contains(D));
1002 unsigned newID = VarDefinitions.size();
1003 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1004 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1005 return NewCtx;
1006 }
1007
1008 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001009 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001010 unsigned newID = VarDefinitions.size();
1011 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1012 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1013 return NewCtx;
1014 }
1015
1016 // Updates a definition only if that definition is already in the map.
1017 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001018 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001019 if (Ctx.contains(D)) {
1020 unsigned newID = VarDefinitions.size();
1021 Context NewCtx = ContextFactory.remove(Ctx, D);
1022 NewCtx = ContextFactory.add(NewCtx, D, newID);
1023 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1024 return NewCtx;
1025 }
1026 return Ctx;
1027 }
1028
1029 // Removes a definition from the context, but keeps the variable name
1030 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001031 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001032 Context NewCtx = Ctx;
1033 if (NewCtx.contains(D)) {
1034 NewCtx = ContextFactory.remove(NewCtx, D);
1035 NewCtx = ContextFactory.add(NewCtx, D, 0);
1036 }
1037 return NewCtx;
1038 }
1039
1040 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001041 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001042 Context NewCtx = Ctx;
1043 if (NewCtx.contains(D)) {
1044 NewCtx = ContextFactory.remove(NewCtx, D);
1045 }
1046 return NewCtx;
1047 }
1048
1049 Context intersectContexts(Context C1, Context C2);
1050 Context createReferenceContext(Context C);
1051 void intersectBackEdge(Context C1, Context C2);
1052
1053 friend class VarMapBuilder;
1054};
1055
1056
1057// This has to be defined after LocalVariableMap.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001058CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1059 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001060}
1061
1062
1063/// Visitor which builds a LocalVariableMap
1064class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1065public:
1066 LocalVariableMap* VMap;
1067 LocalVariableMap::Context Ctx;
1068
1069 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1070 : VMap(VM), Ctx(C) {}
1071
1072 void VisitDeclStmt(DeclStmt *S);
1073 void VisitBinaryOperator(BinaryOperator *BO);
1074};
1075
1076
1077// Add new local variables to the variable map
1078void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1079 bool modifiedCtx = false;
1080 DeclGroupRef DGrp = S->getDeclGroup();
1081 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1082 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1083 Expr *E = VD->getInit();
1084
1085 // Add local variables with trivial type to the variable map
1086 QualType T = VD->getType();
1087 if (T.isTrivialType(VD->getASTContext())) {
1088 Ctx = VMap->addDefinition(VD, E, Ctx);
1089 modifiedCtx = true;
1090 }
1091 }
1092 }
1093 if (modifiedCtx)
1094 VMap->saveContext(S, Ctx);
1095}
1096
1097// Update local variable definitions in variable map
1098void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1099 if (!BO->isAssignmentOp())
1100 return;
1101
1102 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1103
1104 // Update the variable map and current context.
1105 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1106 ValueDecl *VDec = DRE->getDecl();
1107 if (Ctx.lookup(VDec)) {
1108 if (BO->getOpcode() == BO_Assign)
1109 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1110 else
1111 // FIXME -- handle compound assignment operators
1112 Ctx = VMap->clearDefinition(VDec, Ctx);
1113 VMap->saveContext(BO, Ctx);
1114 }
1115 }
1116}
1117
1118
1119// Computes the intersection of two contexts. The intersection is the
1120// set of variables which have the same definition in both contexts;
1121// variables with different definitions are discarded.
1122LocalVariableMap::Context
1123LocalVariableMap::intersectContexts(Context C1, Context C2) {
1124 Context Result = C1;
1125 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001126 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001127 unsigned i1 = I.getData();
1128 const unsigned *i2 = C2.lookup(Dec);
1129 if (!i2) // variable doesn't exist on second path
1130 Result = removeDefinition(Dec, Result);
1131 else if (*i2 != i1) // variable exists, but has different definition
1132 Result = clearDefinition(Dec, Result);
1133 }
1134 return Result;
1135}
1136
1137// For every variable in C, create a new variable that refers to the
1138// definition in C. Return a new context that contains these new variables.
1139// (We use this for a naive implementation of SSA on loop back-edges.)
1140LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1141 Context Result = getEmptyContext();
1142 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001143 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001144 unsigned i = I.getData();
1145 Result = addReference(Dec, i, Result);
1146 }
1147 return Result;
1148}
1149
1150// This routine also takes the intersection of C1 and C2, but it does so by
1151// altering the VarDefinitions. C1 must be the result of an earlier call to
1152// createReferenceContext.
1153void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1154 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001155 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001156 unsigned i1 = I.getData();
1157 VarDefinition *VDef = &VarDefinitions[i1];
1158 assert(VDef->isReference());
1159
1160 const unsigned *i2 = C2.lookup(Dec);
1161 if (!i2 || (*i2 != i1))
1162 VDef->Ref = 0; // Mark this variable as undefined
1163 }
1164}
1165
1166
1167// Traverse the CFG in topological order, so all predecessors of a block
1168// (excluding back-edges) are visited before the block itself. At
1169// each point in the code, we calculate a Context, which holds the set of
1170// variable definitions which are visible at that point in execution.
1171// Visible variables are mapped to their definitions using an array that
1172// contains all definitions.
1173//
1174// At join points in the CFG, the set is computed as the intersection of
1175// the incoming sets along each edge, E.g.
1176//
1177// { Context | VarDefinitions }
1178// int x = 0; { x -> x1 | x1 = 0 }
1179// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1180// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1181// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1182// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1183//
1184// This is essentially a simpler and more naive version of the standard SSA
1185// algorithm. Those definitions that remain in the intersection are from blocks
1186// that strictly dominate the current block. We do not bother to insert proper
1187// phi nodes, because they are not used in our analysis; instead, wherever
1188// a phi node would be required, we simply remove that definition from the
1189// context (E.g. x above).
1190//
1191// The initial traversal does not capture back-edges, so those need to be
1192// handled on a separate pass. Whenever the first pass encounters an
1193// incoming back edge, it duplicates the context, creating new definitions
1194// that refer back to the originals. (These correspond to places where SSA
1195// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001196// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001197// node was actually required.) E.g.
1198//
1199// { Context | VarDefinitions }
1200// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1201// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1202// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1203// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1204//
1205void LocalVariableMap::traverseCFG(CFG *CFGraph,
1206 PostOrderCFGView *SortedGraph,
1207 std::vector<CFGBlockInfo> &BlockInfo) {
1208 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1209
1210 CtxIndices.resize(CFGraph->getNumBlockIDs());
1211
1212 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1213 E = SortedGraph->end(); I!= E; ++I) {
1214 const CFGBlock *CurrBlock = *I;
1215 int CurrBlockID = CurrBlock->getBlockID();
1216 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1217
1218 VisitedBlocks.insert(CurrBlock);
1219
1220 // Calculate the entry context for the current block
1221 bool HasBackEdges = false;
1222 bool CtxInit = true;
1223 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1224 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1225 // if *PI -> CurrBlock is a back edge, so skip it
1226 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1227 HasBackEdges = true;
1228 continue;
1229 }
1230
1231 int PrevBlockID = (*PI)->getBlockID();
1232 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1233
1234 if (CtxInit) {
1235 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1236 CtxInit = false;
1237 }
1238 else {
1239 CurrBlockInfo->EntryContext =
1240 intersectContexts(CurrBlockInfo->EntryContext,
1241 PrevBlockInfo->ExitContext);
1242 }
1243 }
1244
1245 // Duplicate the context if we have back-edges, so we can call
1246 // intersectBackEdges later.
1247 if (HasBackEdges)
1248 CurrBlockInfo->EntryContext =
1249 createReferenceContext(CurrBlockInfo->EntryContext);
1250
1251 // Create a starting context index for the current block
1252 saveContext(0, CurrBlockInfo->EntryContext);
1253 CurrBlockInfo->EntryIndex = getContextIndex();
1254
1255 // Visit all the statements in the basic block.
1256 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1257 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1258 BE = CurrBlock->end(); BI != BE; ++BI) {
1259 switch (BI->getKind()) {
1260 case CFGElement::Statement: {
1261 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1262 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1263 break;
1264 }
1265 default:
1266 break;
1267 }
1268 }
1269 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1270
1271 // Mark variables on back edges as "unknown" if they've been changed.
1272 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1273 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1274 // if CurrBlock -> *SI is *not* a back edge
1275 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1276 continue;
1277
1278 CFGBlock *FirstLoopBlock = *SI;
1279 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1280 Context LoopEnd = CurrBlockInfo->ExitContext;
1281 intersectBackEdge(LoopBegin, LoopEnd);
1282 }
1283 }
1284
1285 // Put an extra entry at the end of the indexed context array
1286 unsigned exitID = CFGraph->getExit().getBlockID();
1287 saveContext(0, BlockInfo[exitID].ExitContext);
1288}
1289
Richard Smith2e515622012-02-03 04:45:26 +00001290/// Find the appropriate source locations to use when producing diagnostics for
1291/// each block in the CFG.
1292static void findBlockLocations(CFG *CFGraph,
1293 PostOrderCFGView *SortedGraph,
1294 std::vector<CFGBlockInfo> &BlockInfo) {
1295 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1296 E = SortedGraph->end(); I!= E; ++I) {
1297 const CFGBlock *CurrBlock = *I;
1298 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1299
1300 // Find the source location of the last statement in the block, if the
1301 // block is not empty.
1302 if (const Stmt *S = CurrBlock->getTerminator()) {
1303 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1304 } else {
1305 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1306 BE = CurrBlock->rend(); BI != BE; ++BI) {
1307 // FIXME: Handle other CFGElement kinds.
1308 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1309 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1310 break;
1311 }
1312 }
1313 }
1314
1315 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1316 // This block contains at least one statement. Find the source location
1317 // of the first statement in the block.
1318 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1319 BE = CurrBlock->end(); BI != BE; ++BI) {
1320 // FIXME: Handle other CFGElement kinds.
1321 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1322 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1323 break;
1324 }
1325 }
1326 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1327 CurrBlock != &CFGraph->getExit()) {
1328 // The block is empty, and has a single predecessor. Use its exit
1329 // location.
1330 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1331 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1332 }
1333 }
1334}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001335
1336/// \brief Class which implements the core thread safety analysis routines.
1337class ThreadSafetyAnalyzer {
1338 friend class BuildLockset;
1339
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001340 ThreadSafetyHandler &Handler;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001341 LocalVariableMap LocalVarMap;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001342 FactManager FactMan;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001343 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001344
1345public:
1346 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1347
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001348 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1349 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001350 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001351
1352 template <typename AttrType>
1353 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1354 const NamedDecl *D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001355
1356 template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001357 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1358 const NamedDecl *D,
1359 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1360 Expr *BrE, bool Neg);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001361
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001362 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1363 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001364
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001365 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1366 const CFGBlock* PredBlock,
1367 const CFGBlock *CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001368
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001369 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1370 SourceLocation JoinLoc,
1371 LockErrorKind LEK1, LockErrorKind LEK2,
1372 bool Modify=true);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001373
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001374 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1375 SourceLocation JoinLoc, LockErrorKind LEK1,
1376 bool Modify=true) {
1377 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001378 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001379
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001380 void runAnalysis(AnalysisDeclContext &AC);
1381};
1382
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001383
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001384/// \brief Add a new lock to the lockset, warning if the lock is already there.
1385/// \param Mutex -- the Mutex expression for the lock
1386/// \param LDat -- the LockData for the lock
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001387void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001388 const LockData &LDat) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001389 // FIXME: deal with acquired before/after annotations.
1390 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001391 if (Mutex.shouldIgnore())
1392 return;
1393
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001394 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001395 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001396 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001397 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001398 }
1399}
1400
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001401
1402/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenekad0fe032012-08-22 23:50:41 +00001403/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001404/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001405void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001406 const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001407 SourceLocation UnlockLoc,
1408 bool FullyRemove) {
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001409 if (Mutex.shouldIgnore())
1410 return;
1411
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001412 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001413 if (!LDat) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001414 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001415 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001416 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001417
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001418 if (LDat->UnderlyingMutex.isValid()) {
1419 // This is scoped lockable object, which manages the real mutex.
1420 if (FullyRemove) {
1421 // We're destroying the managing object.
1422 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001423 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1424 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001425 } else {
1426 // We're releasing the underlying mutex, but not destroying the
1427 // managing object. Warn on dual release.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001428 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001429 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001430 UnlockLoc);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001431 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001432 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1433 return;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001434 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001435 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001436 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001437}
1438
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001439
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001440/// \brief Extract the list of mutexIDs from the attribute on an expression,
1441/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001442template <typename AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001443void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1444 Expr *Exp, const NamedDecl *D) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001445 typedef typename AttrType::args_iterator iterator_type;
1446
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001447 if (Attr->args_size() == 0) {
1448 // The mutex held is the "this" object.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001449 SExpr Mu(0, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001450 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001451 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001452 else
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001453 Mtxs.push_back_nodup(Mu);
1454 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001455 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001456
1457 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001458 SExpr Mu(*I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001459 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001460 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001461 else
1462 Mtxs.push_back_nodup(Mu);
1463 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001464}
1465
1466
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001467/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1468/// trylock applies to the given edge, then push them onto Mtxs, discarding
1469/// any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001470template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001471void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1472 Expr *Exp, const NamedDecl *D,
1473 const CFGBlock *PredBlock,
1474 const CFGBlock *CurrBlock,
1475 Expr *BrE, bool Neg) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001476 // Find out which branch has the lock
1477 bool branch = 0;
1478 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1479 branch = BLE->getValue();
1480 }
1481 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1482 branch = ILE->getValue().getBoolValue();
1483 }
1484 int branchnum = branch ? 0 : 1;
1485 if (Neg) branchnum = !branchnum;
1486
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001487 // If we've taken the trylock branch, then add the lock
1488 int i = 0;
1489 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1490 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1491 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001492 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001493 }
1494 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001495}
1496
1497
DeLesley Hutchins13106112012-07-10 21:47:55 +00001498bool getStaticBooleanValue(Expr* E, bool& TCond) {
1499 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1500 TCond = false;
1501 return true;
1502 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1503 TCond = BLE->getValue();
1504 return true;
1505 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1506 TCond = ILE->getValue().getBoolValue();
1507 return true;
1508 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1509 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1510 }
1511 return false;
1512}
1513
1514
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001515// If Cond can be traced back to a function call, return the call expression.
1516// The negate variable should be called with false, and will be set to true
1517// if the function call is negated, e.g. if (!mu.tryLock(...))
1518const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1519 LocalVarContext C,
1520 bool &Negate) {
1521 if (!Cond)
1522 return 0;
1523
1524 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1525 return CallExp;
1526 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001527 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1528 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1529 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001530 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1531 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1532 }
1533 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1534 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1535 return getTrylockCallExpr(E, C, Negate);
1536 }
1537 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1538 if (UOP->getOpcode() == UO_LNot) {
1539 Negate = !Negate;
1540 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1541 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001542 return 0;
1543 }
1544 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1545 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1546 if (BOP->getOpcode() == BO_NE)
1547 Negate = !Negate;
1548
1549 bool TCond = false;
1550 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1551 if (!TCond) Negate = !Negate;
1552 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1553 }
1554 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1555 if (!TCond) Negate = !Negate;
1556 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1557 }
1558 return 0;
1559 }
1560 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001561 }
1562 // FIXME -- handle && and || as well.
DeLesley Hutchins13106112012-07-10 21:47:55 +00001563 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001564}
1565
1566
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001567/// \brief Find the lockset that holds on the edge between PredBlock
1568/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1569/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001570void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1571 const FactSet &ExitSet,
1572 const CFGBlock *PredBlock,
1573 const CFGBlock *CurrBlock) {
1574 Result = ExitSet;
1575
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001576 if (!PredBlock->getTerminatorCondition())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001577 return;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001578
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001579 bool Negate = false;
1580 const Stmt *Cond = PredBlock->getTerminatorCondition();
1581 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1582 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1583
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001584 CallExpr *Exp =
1585 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001586 if (!Exp)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001587 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001588
1589 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1590 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001591 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001592
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001593
1594 MutexIDList ExclusiveLocksToAdd;
1595 MutexIDList SharedLocksToAdd;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001596
1597 // If the condition is a call to a Trylock function, then grab the attributes
1598 AttrVec &ArgAttrs = FunDecl->getAttrs();
1599 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1600 Attr *Attr = ArgAttrs[i];
1601 switch (Attr->getKind()) {
1602 case attr::ExclusiveTrylockFunction: {
1603 ExclusiveTrylockFunctionAttr *A =
1604 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001605 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1606 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001607 break;
1608 }
1609 case attr::SharedTrylockFunction: {
1610 SharedTrylockFunctionAttr *A =
1611 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001612 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1613 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001614 break;
1615 }
1616 default:
1617 break;
1618 }
1619 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001620
1621 // Add and remove locks.
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001622 SourceLocation Loc = Exp->getExprLoc();
1623 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001624 addLock(Result, ExclusiveLocksToAdd[i],
1625 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001626 }
1627 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001628 addLock(Result, SharedLocksToAdd[i],
1629 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001630 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001631}
1632
1633
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001634/// \brief We use this class to visit different types of expressions in
1635/// CFGBlocks, and build up the lockset.
1636/// An expression may cause us to add or remove locks from the lockset, or else
1637/// output error messages related to missing locks.
1638/// FIXME: In future, we may be able to not inherit from a visitor.
1639class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001640 friend class ThreadSafetyAnalyzer;
1641
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001642 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001643 FactSet FSet;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001644 LocalVariableMap::Context LVarCtx;
1645 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001646
1647 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001648 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001649
1650 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1651 Expr *MutexExp, ProtectedOperationKind POK);
1652
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001653 void checkAccess(Expr *Exp, AccessKind AK);
1654 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001655 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001656
1657 /// \brief Returns true if the lockset contains a lock, regardless of whether
1658 /// the lock is held exclusively or shared.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001659 bool locksetContains(const SExpr &Mu) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001660 return FSet.findLock(Analyzer->FactMan, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001661 }
1662
1663 /// \brief Returns true if the lockset contains a lock with the passed in
1664 /// locktype.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001665 bool locksetContains(const SExpr &Mu, LockKind KindRequested) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001666 const LockData *LockHeld = FSet.findLock(Analyzer->FactMan, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001667 return (LockHeld && KindRequested == LockHeld->LKind);
1668 }
1669
1670 /// \brief Returns true if the lockset contains a lock with at least the
1671 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1672 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1673 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001674 bool locksetContainsAtLeast(const SExpr &Lock,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001675 LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001676 switch (KindRequested) {
1677 case LK_Shared:
1678 return locksetContains(Lock);
1679 case LK_Exclusive:
1680 return locksetContains(Lock, KindRequested);
1681 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001682 llvm_unreachable("Unknown LockKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001683 }
1684
1685public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001686 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001687 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001688 Analyzer(Anlzr),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001689 FSet(Info.EntrySet),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001690 LVarCtx(Info.EntryContext),
1691 CtxIndex(Info.EntryIndex)
1692 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001693
1694 void VisitUnaryOperator(UnaryOperator *UO);
1695 void VisitBinaryOperator(BinaryOperator *BO);
1696 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001697 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001698 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001699 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001700};
1701
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001702
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001703/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1704const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1705 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1706 return DR->getDecl();
1707
1708 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1709 return ME->getMemberDecl();
1710
1711 return 0;
1712}
1713
1714/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001715/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001716void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1717 AccessKind AK, Expr *MutexExp,
1718 ProtectedOperationKind POK) {
1719 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001720
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001721 SExpr Mutex(MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001722 if (!Mutex.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001723 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001724 else if (Mutex.shouldIgnore())
1725 return; // A Nop is an invalid mutex that we've decided to ignore.
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001726 else if (!locksetContainsAtLeast(Mutex, LK))
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001727 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001728 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001729}
1730
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001731/// \brief This method identifies variable dereferences and checks pt_guarded_by
1732/// and pt_guarded_var annotations. Note that we only check these annotations
1733/// at the time a pointer is dereferenced.
1734/// FIXME: We need to check for other types of pointer dereferences
1735/// (e.g. [], ->) and deal with them here.
1736/// \param Exp An expression that has been read or written.
1737void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1738 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1739 if (!UO || UO->getOpcode() != clang::UO_Deref)
1740 return;
1741 Exp = UO->getSubExpr()->IgnoreParenCasts();
1742
1743 const ValueDecl *D = getValueDecl(Exp);
1744 if(!D || !D->hasAttrs())
1745 return;
1746
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001747 if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001748 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1749 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001750
1751 const AttrVec &ArgAttrs = D->getAttrs();
1752 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1753 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1754 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1755}
1756
1757/// \brief Checks guarded_by and guarded_var attributes.
1758/// Whenever we identify an access (read or write) of a DeclRefExpr or
1759/// MemberExpr, we need to check whether there are any guarded_by or
1760/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1761void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1762 const ValueDecl *D = getValueDecl(Exp);
1763 if(!D || !D->hasAttrs())
1764 return;
1765
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001766 if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001767 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1768 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001769
1770 const AttrVec &ArgAttrs = D->getAttrs();
1771 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1772 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1773 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1774}
1775
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001776/// \brief Process a function call, method call, constructor call,
1777/// or destructor call. This involves looking at the attributes on the
1778/// corresponding function/method/constructor/destructor, issuing warnings,
1779/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001780///
1781/// FIXME: For classes annotated with one of the guarded annotations, we need
1782/// to treat const method calls as reads and non-const method calls as writes,
1783/// and check that the appropriate locks are held. Non-const method calls with
1784/// the same signature as const method calls can be also treated as reads.
1785///
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001786void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1787 const AttrVec &ArgAttrs = D->getAttrs();
1788 MutexIDList ExclusiveLocksToAdd;
1789 MutexIDList SharedLocksToAdd;
1790 MutexIDList LocksToRemove;
1791
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001792 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001793 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1794 switch (At->getKind()) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001795 // When we encounter an exclusive lock function, we need to add the lock
1796 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001797 case attr::ExclusiveLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001798 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1799 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001800 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001801 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001802
1803 // When we encounter a shared lock function, we need to add the lock
1804 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001805 case attr::SharedLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001806 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1807 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001808 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001809 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001810
1811 // When we encounter an unlock function, we need to remove unlocked
1812 // mutexes from the lockset, and flag a warning if they are not there.
1813 case attr::UnlockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001814 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1815 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001816 break;
1817 }
1818
1819 case attr::ExclusiveLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001820 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001821
1822 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001823 I = A->args_begin(), E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001824 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1825 break;
1826 }
1827
1828 case attr::SharedLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001829 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001830
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001831 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1832 E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001833 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1834 break;
1835 }
1836
1837 case attr::LocksExcluded: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001838 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1839 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1840 E = A->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001841 SExpr Mutex(*I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001842 if (!Mutex.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001843 SExpr::warnInvalidLock(Analyzer->Handler, *I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001844 else if (locksetContains(Mutex))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001845 Analyzer->Handler.handleFunExcludesLock(D->getName(),
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001846 Mutex.toString(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001847 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001848 }
1849 break;
1850 }
1851
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001852 // Ignore other (non thread-safety) attributes
1853 default:
1854 break;
1855 }
1856 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001857
1858 // Figure out if we're calling the constructor of scoped lockable class
1859 bool isScopedVar = false;
1860 if (VD) {
1861 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1862 const CXXRecordDecl* PD = CD->getParent();
1863 if (PD && PD->getAttr<ScopedLockableAttr>())
1864 isScopedVar = true;
1865 }
1866 }
1867
1868 // Add locks.
1869 SourceLocation Loc = Exp->getExprLoc();
1870 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001871 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1872 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001873 }
1874 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001875 Analyzer->addLock(FSet, SharedLocksToAdd[i],
1876 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001877 }
1878
1879 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1880 // FIXME -- this doesn't work if we acquire multiple locks.
1881 if (isScopedVar) {
1882 SourceLocation MLoc = VD->getLocation();
1883 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001884 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001885
1886 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001887 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
1888 ExclusiveLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001889 }
1890 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001891 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
1892 SharedLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001893 }
1894 }
1895
1896 // Remove locks.
1897 // FIXME -- should only fully remove if the attribute refers to 'this'.
1898 bool Dtor = isa<CXXDestructorDecl>(D);
1899 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001900 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001901 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001902}
1903
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001904
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001905/// \brief For unary operations which read and write a variable, we need to
1906/// check whether we hold any required mutexes. Reads are checked in
1907/// VisitCastExpr.
1908void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1909 switch (UO->getOpcode()) {
1910 case clang::UO_PostDec:
1911 case clang::UO_PostInc:
1912 case clang::UO_PreDec:
1913 case clang::UO_PreInc: {
1914 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1915 checkAccess(SubExp, AK_Written);
1916 checkDereference(SubExp, AK_Written);
1917 break;
1918 }
1919 default:
1920 break;
1921 }
1922}
1923
1924/// For binary operations which assign to a variable (writes), we need to check
1925/// whether we hold any required mutexes.
1926/// FIXME: Deal with non-primitive types.
1927void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1928 if (!BO->isAssignmentOp())
1929 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001930
1931 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001932 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001933
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001934 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1935 checkAccess(LHSExp, AK_Written);
1936 checkDereference(LHSExp, AK_Written);
1937}
1938
1939/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1940/// need to ensure we hold any required mutexes.
1941/// FIXME: Deal with non-primitive types.
1942void BuildLockset::VisitCastExpr(CastExpr *CE) {
1943 if (CE->getCastKind() != CK_LValueToRValue)
1944 return;
1945 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
1946 checkAccess(SubExp, AK_Read);
1947 checkDereference(SubExp, AK_Read);
1948}
1949
1950
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001951void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001952 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1953 if(!D || !D->hasAttrs())
1954 return;
1955 handleCall(Exp, D);
1956}
1957
1958void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001959 // FIXME -- only handles constructors in DeclStmt below.
1960}
1961
1962void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001963 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001964 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001965
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001966 DeclGroupRef DGrp = S->getDeclGroup();
1967 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1968 Decl *D = *I;
1969 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1970 Expr *E = VD->getInit();
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +00001971 // handle constructors that involve temporaries
1972 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1973 E = EWC->getSubExpr();
1974
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001975 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1976 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1977 if (!CtorD || !CtorD->hasAttrs())
1978 return;
1979 handleCall(CE, CtorD, VD);
1980 }
1981 }
1982 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001983}
1984
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001985
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001986
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001987/// \brief Compute the intersection of two locksets and issue warnings for any
1988/// locks in the symmetric difference.
1989///
1990/// This function is used at a merge point in the CFG when comparing the lockset
1991/// of each branch being merged. For example, given the following sequence:
1992/// A; if () then B; else C; D; we need to check that the lockset after B and C
1993/// are the same. In the event of a difference, we use the intersection of these
1994/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001995///
Ted Kremenekad0fe032012-08-22 23:50:41 +00001996/// \param FSet1 The first lockset.
1997/// \param FSet2 The second lockset.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001998/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001999/// \param LEK1 The error message to report if a mutex is missing from LSet1
2000/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002001void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2002 const FactSet &FSet2,
2003 SourceLocation JoinLoc,
2004 LockErrorKind LEK1,
2005 LockErrorKind LEK2,
2006 bool Modify) {
2007 FactSet FSet1Orig = FSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002008
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002009 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2010 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002011 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002012 const LockData &LDat2 = FactMan[*I].LDat;
2013
2014 if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002015 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002016 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002017 LDat2.AcquireLoc,
2018 LDat1->AcquireLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002019 if (Modify && LDat1->LKind != LK_Exclusive) {
2020 FSet1.removeLock(FactMan, FSet2Mutex);
2021 FSet1.addLock(FactMan, FSet2Mutex, LDat2);
2022 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002023 }
2024 } else {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002025 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002026 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002027 // If this is a scoped lock that manages another mutex, and if the
2028 // underlying mutex is still held, then warn about the underlying
2029 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002030 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002031 LDat2.AcquireLoc,
2032 JoinLoc, LEK1);
2033 }
2034 }
2035 else if (!LDat2.Managed)
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002036 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002037 LDat2.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002038 JoinLoc, LEK1);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002039 }
2040 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002041
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002042 for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
2043 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002044 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002045 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00002046
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002047 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002048 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002049 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002050 // If this is a scoped lock that manages another mutex, and if the
2051 // underlying mutex is still held, then warn about the underlying
2052 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002053 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002054 LDat1.AcquireLoc,
2055 JoinLoc, LEK1);
2056 }
2057 }
2058 else if (!LDat1.Managed)
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002059 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002060 LDat1.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002061 JoinLoc, LEK2);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002062 if (Modify)
2063 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002064 }
2065 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002066}
2067
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002068
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002069
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002070/// \brief Check a function's CFG for thread-safety violations.
2071///
2072/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2073/// at the end of each block, and issue warnings for thread safety violations.
2074/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002075void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002076 CFG *CFGraph = AC.getCFG();
2077 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002078 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2079
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002080 // AC.dumpCFG(true);
2081
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002082 if (!D)
2083 return; // Ignore anonymous functions for now.
2084 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2085 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002086 // FIXME: Do something a bit more intelligent inside constructor and
2087 // destructor code. Constructors and destructors must assume unique access
2088 // to 'this', so checks on member variable access is disabled, but we should
2089 // still enable checks on other objects.
2090 if (isa<CXXConstructorDecl>(D))
2091 return; // Don't check inside constructors.
2092 if (isa<CXXDestructorDecl>(D))
2093 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002094
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002095 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002096 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002097
2098 // We need to explore the CFG via a "topological" ordering.
2099 // That way, we will be guaranteed to have information about required
2100 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00002101 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2102 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002103
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002104 // Compute SSA names for local variables
2105 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2106
Richard Smith2e515622012-02-03 04:45:26 +00002107 // Fill in source locations for all CFGBlocks.
2108 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2109
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002110 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002111 // to initial lockset. Also turn off checking for lock and unlock functions.
2112 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00002113 if (!SortedGraph->empty() && D->hasAttrs()) {
2114 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002115 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002116 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002117
2118 MutexIDList ExclusiveLocksToAdd;
2119 MutexIDList SharedLocksToAdd;
2120
2121 SourceLocation Loc = D->getLocation();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002122 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002123 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002124 Loc = Attr->getLocation();
2125 if (ExclusiveLocksRequiredAttr *A
2126 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2127 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2128 } else if (SharedLocksRequiredAttr *A
2129 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2130 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002131 } else if (isa<UnlockFunctionAttr>(Attr)) {
2132 // Don't try to check unlock functions for now
2133 return;
2134 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
2135 // Don't try to check lock functions for now
2136 return;
2137 } else if (isa<SharedLockFunctionAttr>(Attr)) {
2138 // Don't try to check lock functions for now
2139 return;
DeLesley Hutchins76f0a6e2012-07-02 21:59:24 +00002140 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2141 // Don't try to check trylock functions for now
2142 return;
2143 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2144 // Don't try to check trylock functions for now
2145 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002146 }
2147 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002148
2149 // FIXME -- Loc can be wrong here.
2150 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002151 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2152 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002153 }
2154 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002155 addLock(InitialLockset, SharedLocksToAdd[i],
2156 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002157 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002158 }
2159
Ted Kremenek439ed162011-10-22 02:14:27 +00002160 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2161 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002162 const CFGBlock *CurrBlock = *I;
2163 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002164 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002165
2166 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002167 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002168
2169 // Iterate through the predecessor blocks and warn if the lockset for all
2170 // predecessors is not the same. We take the entry lockset of the current
2171 // block to be the intersection of all previous locksets.
2172 // FIXME: By keeping the intersection, we may output more errors in future
2173 // for a lock which is not in the intersection, but was in the union. We
2174 // may want to also keep the union in future. As an example, let's say
2175 // the intersection contains Mutex L, and the union contains L and M.
2176 // Later we unlock M. At this point, we would output an error because we
2177 // never locked M; although the real error is probably that we forgot to
2178 // lock M on all code paths. Conversely, let's say that later we lock M.
2179 // In this case, we should compare against the intersection instead of the
2180 // union because the real error is probably that we forgot to unlock M on
2181 // all code paths.
2182 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00002183 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002184 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2185 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2186
2187 // if *PI -> CurrBlock is a back edge
2188 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2189 continue;
2190
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00002191 // Ignore edges from blocks that can't return.
2192 if ((*PI)->hasNoReturnElement())
2193 continue;
2194
Richard Smithaacde712012-02-03 03:30:07 +00002195 // If the previous block ended in a 'continue' or 'break' statement, then
2196 // a difference in locksets is probably due to a bug in that block, rather
2197 // than in some other predecessor. In that case, keep the other
2198 // predecessor's lockset.
2199 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2200 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2201 SpecialBlocks.push_back(*PI);
2202 continue;
2203 }
2204 }
2205
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002206 int PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002207 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002208 FactSet PrevLockset;
2209 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002210
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002211 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002212 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002213 LocksetInitialized = true;
2214 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002215 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2216 CurrBlockInfo->EntryLoc,
2217 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002218 }
2219 }
2220
Richard Smithaacde712012-02-03 03:30:07 +00002221 // Process continue and break blocks. Assume that the lockset for the
2222 // resulting block is unaffected by any discrepancies in them.
2223 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2224 SpecialI < SpecialN; ++SpecialI) {
2225 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2226 int PrevBlockID = PrevBlock->getBlockID();
2227 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2228
2229 if (!LocksetInitialized) {
2230 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2231 LocksetInitialized = true;
2232 } else {
2233 // Determine whether this edge is a loop terminator for diagnostic
2234 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2235 // it might also be part of a switch. Also, a subsequent destructor
2236 // might add to the lockset, in which case the real issue might be a
2237 // double lock on the other path.
2238 const Stmt *Terminator = PrevBlock->getTerminator();
2239 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2240
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002241 FactSet PrevLockset;
2242 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2243 PrevBlock, CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002244
Richard Smithaacde712012-02-03 03:30:07 +00002245 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002246 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2247 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00002248 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002249 : LEK_LockedSomePredecessors,
2250 false);
Richard Smithaacde712012-02-03 03:30:07 +00002251 }
2252 }
2253
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002254 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2255
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002256 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002257 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2258 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002259 switch (BI->getKind()) {
2260 case CFGElement::Statement: {
2261 const CFGStmt *CS = cast<CFGStmt>(&*BI);
2262 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
2263 break;
2264 }
2265 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2266 case CFGElement::AutomaticObjectDtor: {
2267 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
2268 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
2269 AD->getDestructorDecl(AC.getASTContext()));
2270 if (!DD->hasAttrs())
2271 break;
2272
2273 // Create a dummy expression,
2274 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00002275 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002276 AD->getTriggerStmt()->getLocEnd());
2277 LocksetBuilder.handleCall(&DRE, DD);
2278 break;
2279 }
2280 default:
2281 break;
2282 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002283 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002284 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002285
2286 // For every back edge from CurrBlock (the end of the loop) to another block
2287 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2288 // the one held at the beginning of FirstLoopBlock. We can look up the
2289 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2290 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2291 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2292
2293 // if CurrBlock -> *SI is *not* a back edge
2294 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2295 continue;
2296
2297 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002298 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2299 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2300 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2301 PreLoop->EntryLoc,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002302 LEK_LockedSomeLoopIterations,
2303 false);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002304 }
2305 }
2306
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002307 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2308 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00002309
2310 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002311 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
2312 Final->ExitLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002313 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002314 LEK_NotLockedAtEndOfFunction,
2315 false);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002316}
2317
2318} // end anonymous namespace
2319
2320
2321namespace clang {
2322namespace thread_safety {
2323
2324/// \brief Check a function's CFG for thread-safety violations.
2325///
2326/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2327/// at the end of each block, and issue warnings for thread safety violations.
2328/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002329void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002330 ThreadSafetyHandler &Handler) {
2331 ThreadSafetyAnalyzer Analyzer(Handler);
2332 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002333}
2334
2335/// \brief Helper function that returns a LockKind required for the given level
2336/// of access.
2337LockKind getLockKindFromAccessKind(AccessKind AK) {
2338 switch (AK) {
2339 case AK_Read :
2340 return LK_Shared;
2341 case AK_Written :
2342 return LK_Exclusive;
2343 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00002344 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002345}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002346
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002347}} // end namespace clang::thread_safety