blob: d359f4f93d43d54364cb26c7a273d3ba0339e3f7 [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 {
73 EOP_Nop, //< No-op
74 EOP_This, //< This keyword.
75 EOP_NVar, //< Named variable.
76 EOP_LVar, //< Local variable.
77 EOP_Dot, //< Field access
78 EOP_Call, //< Function call
79 EOP_MCall, //< Method call
80 EOP_Index, //< Array index
81 EOP_Unary, //< Unary operation
82 EOP_Binary, //< Binary operation
83 EOP_Unknown //< Catchall for everything else
84 };
85
86
87 class SExprNode {
88 private:
89 unsigned char Op; //< Opcode of the root node
90 unsigned char Flags; //< Additional opcode-specific data
91 unsigned short Sz; //< Number of child nodes
92 const void* Data; //< Additional opcode-specific data
93
94 public:
95 SExprNode(ExprOp O, unsigned F, const void* D)
96 : Op(static_cast<unsigned char>(O)),
97 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
98 { }
99
100 unsigned size() const { return Sz; }
101 void setSize(unsigned S) { Sz = S; }
102
103 ExprOp kind() const { return static_cast<ExprOp>(Op); }
104
105 const NamedDecl* getNamedDecl() const {
106 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
107 return reinterpret_cast<const NamedDecl*>(Data);
108 }
109
110 const NamedDecl* getFunctionDecl() const {
111 assert(Op == EOP_Call || Op == EOP_MCall);
112 return reinterpret_cast<const NamedDecl*>(Data);
113 }
114
115 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
116 void setArrow(bool A) { Flags = A ? 1 : 0; }
117
118 unsigned arity() const {
119 switch (Op) {
120 case EOP_Nop: return 0;
121 case EOP_NVar: return 0;
122 case EOP_LVar: return 0;
123 case EOP_This: return 0;
124 case EOP_Dot: return 1;
125 case EOP_Call: return Flags+1; // First arg is function.
126 case EOP_MCall: return Flags+1; // First arg is implicit obj.
127 case EOP_Index: return 2;
128 case EOP_Unary: return 1;
129 case EOP_Binary: return 2;
130 case EOP_Unknown: return Flags;
131 }
132 return 0;
133 }
134
135 bool operator==(const SExprNode& Other) const {
136 // Ignore flags and size -- they don't matter.
137 return Op == Other.Op &&
138 Data == Other.Data;
139 }
140
141 bool operator!=(const SExprNode& Other) const {
142 return !(*this == Other);
143 }
144 };
145
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000146
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000147 /// \brief Encapsulates the lexical context of a function call. The lexical
148 /// context includes the arguments to the call, including the implicit object
149 /// argument. When an attribute containing a mutex expression is attached to
150 /// a method, the expression may refer to formal parameters of the method.
151 /// Actual arguments must be substituted for formal parameters to derive
152 /// the appropriate mutex expression in the lexical context where the function
153 /// is called. PrevCtx holds the context in which the arguments themselves
154 /// should be evaluated; multiple calling contexts can be chained together
155 /// by the lock_returned attribute.
156 struct CallingContext {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000157 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
158 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
159 bool SelfArrow; // is Self referred to with -> or .?
160 unsigned NumArgs; // Number of funArgs
161 Expr** FunArgs; // Function arguments
162 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000163
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000164 CallingContext(const NamedDecl *D = 0, Expr *S = 0,
165 unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
166 : AttrDecl(D), SelfArg(S), SelfArrow(false),
167 NumArgs(N), FunArgs(A), PrevCtx(P)
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000168 { }
169 };
170
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000171 typedef SmallVector<SExprNode, 4> NodeVector;
172
173private:
174 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
175 // the list to be traversed as a tree.
176 NodeVector NodeVec;
177
178private:
179 unsigned getNextIndex(unsigned i) const {
180 return i + NodeVec[i].size();
181 }
182
183 unsigned makeNop() {
184 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
185 return NodeVec.size()-1;
186 }
187
188 unsigned makeNamedVar(const NamedDecl *D) {
189 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
190 return NodeVec.size()-1;
191 }
192
193 unsigned makeLocalVar(const NamedDecl *D) {
194 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
195 return NodeVec.size()-1;
196 }
197
198 unsigned makeThis() {
199 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
200 return NodeVec.size()-1;
201 }
202
203 unsigned makeDot(const NamedDecl *D, bool Arrow) {
204 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
205 return NodeVec.size()-1;
206 }
207
208 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
209 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
210 return NodeVec.size()-1;
211 }
212
213 unsigned makeMCall(unsigned NumArgs, const NamedDecl *D) {
214 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, D));
215 return NodeVec.size()-1;
216 }
217
218 unsigned makeIndex() {
219 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
220 return NodeVec.size()-1;
221 }
222
223 unsigned makeUnary() {
224 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
225 return NodeVec.size()-1;
226 }
227
228 unsigned makeBinary() {
229 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
230 return NodeVec.size()-1;
231 }
232
233 unsigned makeUnknown(unsigned Arity) {
234 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
235 return NodeVec.size()-1;
236 }
237
238 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000239 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000240 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000241 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000242 ///
243 /// NDeref returns the number of Derefence and AddressOf operations
244 /// preceeding the Expr; this is used to decide whether to pretty-print
245 /// SExprs with . or ->.
246 unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
247 if (!Exp)
248 return 0;
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000249
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000250 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
251 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000252 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
253 if (PV) {
254 FunctionDecl *FD =
255 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
256 unsigned i = PV->getFunctionScopeIndex();
257
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000258 if (CallCtx && CallCtx->FunArgs &&
259 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000260 // Substitute call arguments for references to function parameters
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000261 assert(i < CallCtx->NumArgs);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000262 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000263 }
264 // Map the param back to the param of the original function declaration.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000265 makeNamedVar(FD->getParamDecl(i));
266 return 1;
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000267 }
268 // Not a function parameter -- just store the reference.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000269 makeNamedVar(ND);
270 return 1;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000271 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000272 // Substitute parent for 'this'
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000273 if (CallCtx && CallCtx->SelfArg) {
274 if (!CallCtx->SelfArrow && NDeref)
275 // 'this' is a pointer, but self is not, so need to take address.
276 --(*NDeref);
277 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
278 }
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000279 else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000280 makeThis();
281 return 1;
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000282 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000283 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
284 NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000285 int ImplicitDeref = ME->isArrow() ? 1 : 0;
286 unsigned Root = makeDot(ND, false);
287 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
288 NodeVec[Root].setArrow(ImplicitDeref > 0);
289 NodeVec[Root].setSize(Sz + 1);
290 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000291 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000292 // When calling a function with a lock_returned attribute, replace
293 // the function call with the expression in lock_returned.
294 if (LockReturnedAttr* At =
295 CMCE->getMethodDecl()->getAttr<LockReturnedAttr>()) {
296 CallingContext LRCallCtx(CMCE->getMethodDecl());
297 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000298 LRCallCtx.SelfArrow =
299 dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000300 LRCallCtx.NumArgs = CMCE->getNumArgs();
301 LRCallCtx.FunArgs = CMCE->getArgs();
302 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000303 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000304 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000305 // Hack to treat smart pointers and iterators as pointers;
306 // ignore any method named get().
307 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
308 CMCE->getNumArgs() == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000309 if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
310 ++(*NDeref);
311 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000312 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000313 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000314 unsigned Root =
315 makeMCall(NumCallArgs, CMCE->getMethodDecl()->getCanonicalDecl());
316 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000317 Expr** CallArgs = CMCE->getArgs();
318 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000319 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000320 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000321 NodeVec[Root].setSize(Sz + 1);
322 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000323 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000324 if (LockReturnedAttr* At =
325 CE->getDirectCallee()->getAttr<LockReturnedAttr>()) {
326 CallingContext LRCallCtx(CE->getDirectCallee());
327 LRCallCtx.NumArgs = CE->getNumArgs();
328 LRCallCtx.FunArgs = CE->getArgs();
329 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000330 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000331 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000332 // Treat smart pointers and iterators as pointers;
333 // ignore the * and -> operators.
334 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
335 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000336 if (k == OO_Star) {
337 if (NDeref) ++(*NDeref);
338 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
339 }
340 else if (k == OO_Arrow) {
341 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000342 }
343 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000344 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000345 unsigned Root = makeCall(NumCallArgs, 0);
346 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000347 Expr** CallArgs = CE->getArgs();
348 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000349 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000350 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000351 NodeVec[Root].setSize(Sz+1);
352 return Sz+1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000353 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000354 unsigned Root = makeBinary();
355 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
356 Sz += buildSExpr(BOE->getRHS(), CallCtx);
357 NodeVec[Root].setSize(Sz);
358 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000359 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000360 // Ignore & and * operators -- they're no-ops.
361 // However, we try to figure out whether the expression is a pointer,
362 // so we can use . and -> appropriately in error messages.
363 if (UOE->getOpcode() == UO_Deref) {
364 if (NDeref) ++(*NDeref);
365 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
366 }
367 if (UOE->getOpcode() == UO_AddrOf) {
368 if (NDeref) --(*NDeref);
369 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
370 }
371 unsigned Root = makeUnary();
372 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
373 NodeVec[Root].setSize(Sz);
374 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000375 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000376 unsigned Root = makeIndex();
377 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
378 Sz += buildSExpr(ASE->getIdx(), CallCtx);
379 NodeVec[Root].setSize(Sz);
380 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000381 } else if (AbstractConditionalOperator *CE =
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000382 dyn_cast<AbstractConditionalOperator>(Exp)) {
383 unsigned Root = makeUnknown(3);
384 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
385 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
386 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
387 NodeVec[Root].setSize(Sz);
388 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000389 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000390 unsigned Root = makeUnknown(3);
391 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
392 Sz += buildSExpr(CE->getLHS(), CallCtx);
393 Sz += buildSExpr(CE->getRHS(), CallCtx);
394 NodeVec[Root].setSize(Sz);
395 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000396 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000397 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000398 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000399 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000400 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000401 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000402 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000403 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000404 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000405 isa<CXXNullPtrLiteralExpr>(Exp) ||
406 isa<GNUNullExpr>(Exp) ||
407 isa<CXXBoolLiteralExpr>(Exp) ||
408 isa<FloatingLiteral>(Exp) ||
409 isa<ImaginaryLiteral>(Exp) ||
410 isa<IntegerLiteral>(Exp) ||
411 isa<StringLiteral>(Exp) ||
412 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000413 makeNop();
414 return 1; // FIXME: Ignore literals for now
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000415 } else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000416 makeNop();
417 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000418 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000419 }
420
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000421 /// \brief Construct a SExpr from an expression.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000422 /// \param MutexExp The original mutex expression within an attribute
423 /// \param DeclExp An expression involving the Decl on which the attribute
424 /// occurs.
425 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000426 void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000427 CallingContext CallCtx(D);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000428
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000429 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000430 if (DeclExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000431 buildSExpr(MutexExp, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000432 return;
433 }
434
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000435 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000436 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000437 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000438 CallCtx.SelfArg = ME->getBase();
439 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000440 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000441 CallCtx.SelfArg = CE->getImplicitObjectArgument();
442 CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
443 CallCtx.NumArgs = CE->getNumArgs();
444 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000445 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000446 CallCtx.NumArgs = CE->getNumArgs();
447 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000448 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000449 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
450 CallCtx.NumArgs = CE->getNumArgs();
451 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000452 } else if (D && isa<CXXDestructorDecl>(D)) {
453 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000454 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000455 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000456
457 // If the attribute has no arguments, then assume the argument is "this".
458 if (MutexExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000459 buildSExpr(CallCtx.SelfArg, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000460 return;
461 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000462
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000463 // For most attributes.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000464 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000465 }
466
467public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000468 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000469
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000470 /// \param MutexExp The original mutex expression within an attribute
471 /// \param DeclExp An expression involving the Decl on which the attribute
472 /// occurs.
473 /// \param D The declaration to which the lock/unlock attribute is attached.
474 /// Caller must check isValid() after construction.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000475 SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
476 buildSExprFromExpr(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000477 }
478
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000479 /// Return true if this is a valid decl sequence.
480 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000481 bool isValid() const {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000482 return !NodeVec.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000483 }
484
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000485 /// Issue a warning about an invalid lock expression
486 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
487 Expr *DeclExp, const NamedDecl* D) {
488 SourceLocation Loc;
489 if (DeclExp)
490 Loc = DeclExp->getExprLoc();
491
492 // FIXME: add a note about the attribute location in MutexExp or D
493 if (Loc.isValid())
494 Handler.handleInvalidLockExp(Loc);
495 }
496
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000497 bool operator==(const SExpr &other) const {
498 return NodeVec == other.NodeVec;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000499 }
500
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000501 bool operator!=(const SExpr &other) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000502 return !(*this == other);
503 }
504
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000505 /// \brief Pretty print a lock expression for use in error messages.
506 std::string toString(unsigned i = 0) const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000507 assert(isValid());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000508 if (i >= NodeVec.size())
509 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000510
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000511 const SExprNode* N = &NodeVec[i];
512 switch (N->kind()) {
513 case EOP_Nop:
514 return "_";
515 case EOP_This:
516 return "this";
517 case EOP_NVar:
518 case EOP_LVar: {
519 return N->getNamedDecl()->getNameAsString();
520 }
521 case EOP_Dot: {
522 std::string FieldName = N->getNamedDecl()->getNameAsString();
523 if (NodeVec[i+1].kind() == EOP_This)
524 return FieldName;
525 std::string S = toString(i+1);
526 if (N->isArrow())
527 return S + "->" + FieldName;
528 else
529 return S + "." + FieldName;
530 }
531 case EOP_Call: {
532 std::string S = toString(i+1) + "(";
533 unsigned NumArgs = N->arity()-1;
534 unsigned ci = getNextIndex(i+1);
535 for (unsigned k=0; k<NumArgs; ++k, ci = getNextIndex(ci)) {
536 S += toString(ci);
537 if (k+1 < NumArgs) S += ",";
538 }
539 S += ")";
540 return S;
541 }
542 case EOP_MCall: {
543 std::string S = "";
544 if (NodeVec[i+1].kind() != EOP_This)
545 S = toString(i+1) + ".";
546 if (const NamedDecl *D = N->getFunctionDecl())
547 S += D->getNameAsString() + "(";
548 else
549 S += "#(";
550 unsigned NumArgs = N->arity()-1;
551 unsigned ci = getNextIndex(i+1);
552 for (unsigned k=0; k<NumArgs; ++k, ci = getNextIndex(ci)) {
553 S += toString(ci);
554 if (k+1 < NumArgs) S += ",";
555 }
556 S += ")";
557 return S;
558 }
559 case EOP_Index: {
560 std::string S1 = toString(i+1);
561 std::string S2 = toString(i+1 + NodeVec[i+1].size());
562 return S1 + "[" + S2 + "]";
563 }
564 case EOP_Unary: {
565 std::string S = toString(i+1);
566 return "#" + S;
567 }
568 case EOP_Binary: {
569 std::string S1 = toString(i+1);
570 std::string S2 = toString(i+1 + NodeVec[i+1].size());
571 return "(" + S1 + "#" + S2 + ")";
572 }
573 case EOP_Unknown: {
574 unsigned NumChildren = N->arity();
575 if (NumChildren == 0)
576 return "(...)";
577 std::string S = "(";
578 unsigned ci = i+1;
579 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextIndex(ci)) {
580 S += toString(ci);
581 if (j+1 < NumChildren) S += "#";
582 }
583 S += ")";
584 return S;
585 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000586 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000587 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000588 }
589};
590
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000591
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000592
593/// \brief A short list of SExprs
594class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000595public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000596 /// \brief Return true if the list contains the specified SExpr
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000597 /// Performs a linear search, because these lists are almost always very small.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000598 bool contains(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000599 for (iterator I=begin(),E=end(); I != E; ++I)
600 if ((*I) == M) return true;
601 return false;
602 }
603
604 /// \brief Push M onto list, bud discard duplicates
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000605 void push_back_nodup(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000606 if (!contains(M)) push_back(M);
607 }
608};
609
610
611
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000612/// \brief This is a helper class that stores info about the most recent
613/// accquire of a Lock.
614///
615/// The main body of the analysis maps MutexIDs to LockDatas.
616struct LockData {
617 SourceLocation AcquireLoc;
618
619 /// \brief LKind stores whether a lock is held shared or exclusively.
620 /// Note that this analysis does not currently support either re-entrant
621 /// locking or lock "upgrading" and "downgrading" between exclusive and
622 /// shared.
623 ///
624 /// FIXME: add support for re-entrant locking and lock up/downgrading
625 LockKind LKind;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000626 bool Managed; // for ScopedLockable objects
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000627 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000628
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000629 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
630 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
631 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000632 {}
633
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000634 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000635 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
636 UnderlyingMutex(Mu)
637 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000638
639 bool operator==(const LockData &other) const {
640 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
641 }
642
643 bool operator!=(const LockData &other) const {
644 return !(*this == other);
645 }
646
647 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000648 ID.AddInteger(AcquireLoc.getRawEncoding());
649 ID.AddInteger(LKind);
650 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000651};
652
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000653
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000654/// \brief A FactEntry stores a single fact that is known at a particular point
655/// in the program execution. Currently, this is information regarding a lock
656/// that is held at that point.
657struct FactEntry {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000658 SExpr MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000659 LockData LDat;
660
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000661 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000662 : MutID(M), LDat(L)
663 { }
664};
665
666
667typedef unsigned short FactID;
668
669/// \brief FactManager manages the memory for all facts that are created during
670/// the analysis of a single routine.
671class FactManager {
672private:
673 std::vector<FactEntry> Facts;
674
675public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000676 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000677 Facts.push_back(FactEntry(M,L));
678 return static_cast<unsigned short>(Facts.size() - 1);
679 }
680
681 const FactEntry& operator[](FactID F) const { return Facts[F]; }
682 FactEntry& operator[](FactID F) { return Facts[F]; }
683};
684
685
686/// \brief A FactSet is the set of facts that are known to be true at a
687/// particular program point. FactSets must be small, because they are
688/// frequently copied, and are thus implemented as a set of indices into a
689/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
690/// locks, so we can get away with doing a linear search for lookup. Note
691/// that a hashtable or map is inappropriate in this case, because lookups
692/// may involve partial pattern matches, rather than exact matches.
693class FactSet {
694private:
695 typedef SmallVector<FactID, 4> FactVec;
696
697 FactVec FactIDs;
698
699public:
700 typedef FactVec::iterator iterator;
701 typedef FactVec::const_iterator const_iterator;
702
703 iterator begin() { return FactIDs.begin(); }
704 const_iterator begin() const { return FactIDs.begin(); }
705
706 iterator end() { return FactIDs.end(); }
707 const_iterator end() const { return FactIDs.end(); }
708
709 bool isEmpty() const { return FactIDs.size() == 0; }
710
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000711 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000712 FactID F = FM.newLock(M, L);
713 FactIDs.push_back(F);
714 return F;
715 }
716
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000717 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000718 unsigned n = FactIDs.size();
719 if (n == 0)
720 return false;
721
722 for (unsigned i = 0; i < n-1; ++i) {
723 if (FM[FactIDs[i]].MutID == M) {
724 FactIDs[i] = FactIDs[n-1];
725 FactIDs.pop_back();
726 return true;
727 }
728 }
729 if (FM[FactIDs[n-1]].MutID == M) {
730 FactIDs.pop_back();
731 return true;
732 }
733 return false;
734 }
735
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000736 LockData* findLock(FactManager& FM, const SExpr& M) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000737 for (const_iterator I=begin(), E=end(); I != E; ++I) {
738 if (FM[*I].MutID == M) return &FM[*I].LDat;
739 }
740 return 0;
741 }
742};
743
744
745
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000746/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000747/// been locked.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000748typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000749typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000750
751class LocalVariableMap;
752
Richard Smith2e515622012-02-03 04:45:26 +0000753/// A side (entry or exit) of a CFG node.
754enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000755
756/// CFGBlockInfo is a struct which contains all the information that is
757/// maintained for each block in the CFG. See LocalVariableMap for more
758/// information about the contexts.
759struct CFGBlockInfo {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000760 FactSet EntrySet; // Lockset held at entry to block
761 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000762 LocalVarContext EntryContext; // Context held at entry to block
763 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000764 SourceLocation EntryLoc; // Location of first statement in block
765 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000766 unsigned EntryIndex; // Used to replay contexts later
767
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000768 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith2e515622012-02-03 04:45:26 +0000769 return Side == CBS_Entry ? EntrySet : ExitSet;
770 }
771 SourceLocation getLocation(CFGBlockSide Side) const {
772 return Side == CBS_Entry ? EntryLoc : ExitLoc;
773 }
774
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000775private:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000776 CFGBlockInfo(LocalVarContext EmptyCtx)
777 : EntryContext(EmptyCtx), ExitContext(EmptyCtx)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000778 { }
779
780public:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000781 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000782};
783
784
785
786// A LocalVariableMap maintains a map from local variables to their currently
787// valid definitions. It provides SSA-like functionality when traversing the
788// CFG. Like SSA, each definition or assignment to a variable is assigned a
789// unique name (an integer), which acts as the SSA name for that definition.
790// The total set of names is shared among all CFG basic blocks.
791// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
792// with their SSA-names. Instead, we compute a Context for each point in the
793// code, which maps local variables to the appropriate SSA-name. This map
794// changes with each assignment.
795//
796// The map is computed in a single pass over the CFG. Subsequent analyses can
797// then query the map to find the appropriate Context for a statement, and use
798// that Context to look up the definitions of variables.
799class LocalVariableMap {
800public:
801 typedef LocalVarContext Context;
802
803 /// A VarDefinition consists of an expression, representing the value of the
804 /// variable, along with the context in which that expression should be
805 /// interpreted. A reference VarDefinition does not itself contain this
806 /// information, but instead contains a pointer to a previous VarDefinition.
807 struct VarDefinition {
808 public:
809 friend class LocalVariableMap;
810
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000811 const NamedDecl *Dec; // The original declaration for this variable.
812 const Expr *Exp; // The expression for this variable, OR
813 unsigned Ref; // Reference to another VarDefinition
814 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000815
816 bool isReference() { return !Exp; }
817
818 private:
819 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000820 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000821 : Dec(D), Exp(E), Ref(0), Ctx(C)
822 { }
823
824 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000825 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000826 : Dec(D), Exp(0), Ref(R), Ctx(C)
827 { }
828 };
829
830private:
831 Context::Factory ContextFactory;
832 std::vector<VarDefinition> VarDefinitions;
833 std::vector<unsigned> CtxIndices;
834 std::vector<std::pair<Stmt*, Context> > SavedContexts;
835
836public:
837 LocalVariableMap() {
838 // index 0 is a placeholder for undefined variables (aka phi-nodes).
839 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
840 }
841
842 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000843 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000844 const unsigned *i = Ctx.lookup(D);
845 if (!i)
846 return 0;
847 assert(*i < VarDefinitions.size());
848 return &VarDefinitions[*i];
849 }
850
851 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000852 /// NULL if the expression is not statically known. If successful, also
853 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000854 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000855 const unsigned *P = Ctx.lookup(D);
856 if (!P)
857 return 0;
858
859 unsigned i = *P;
860 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000861 if (VarDefinitions[i].Exp) {
862 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000863 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000864 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000865 i = VarDefinitions[i].Ref;
866 }
867 return 0;
868 }
869
870 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
871
872 /// Return the next context after processing S. This function is used by
873 /// clients of the class to get the appropriate context when traversing the
874 /// CFG. It must be called for every assignment or DeclStmt.
875 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
876 if (SavedContexts[CtxIndex+1].first == S) {
877 CtxIndex++;
878 Context Result = SavedContexts[CtxIndex].second;
879 return Result;
880 }
881 return C;
882 }
883
884 void dumpVarDefinitionName(unsigned i) {
885 if (i == 0) {
886 llvm::errs() << "Undefined";
887 return;
888 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000889 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000890 if (!Dec) {
891 llvm::errs() << "<<NULL>>";
892 return;
893 }
894 Dec->printName(llvm::errs());
895 llvm::errs() << "." << i << " " << ((void*) Dec);
896 }
897
898 /// Dumps an ASCII representation of the variable map to llvm::errs()
899 void dump() {
900 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000901 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000902 unsigned Ref = VarDefinitions[i].Ref;
903
904 dumpVarDefinitionName(i);
905 llvm::errs() << " = ";
906 if (Exp) Exp->dump();
907 else {
908 dumpVarDefinitionName(Ref);
909 llvm::errs() << "\n";
910 }
911 }
912 }
913
914 /// Dumps an ASCII representation of a Context to llvm::errs()
915 void dumpContext(Context C) {
916 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000917 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000918 D->printName(llvm::errs());
919 const unsigned *i = C.lookup(D);
920 llvm::errs() << " -> ";
921 dumpVarDefinitionName(*i);
922 llvm::errs() << "\n";
923 }
924 }
925
926 /// Builds the variable map.
927 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
928 std::vector<CFGBlockInfo> &BlockInfo);
929
930protected:
931 // Get the current context index
932 unsigned getContextIndex() { return SavedContexts.size()-1; }
933
934 // Save the current context for later replay
935 void saveContext(Stmt *S, Context C) {
936 SavedContexts.push_back(std::make_pair(S,C));
937 }
938
939 // Adds a new definition to the given context, and returns a new context.
940 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000941 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000942 assert(!Ctx.contains(D));
943 unsigned newID = VarDefinitions.size();
944 Context NewCtx = ContextFactory.add(Ctx, D, newID);
945 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
946 return NewCtx;
947 }
948
949 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000950 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000951 unsigned newID = VarDefinitions.size();
952 Context NewCtx = ContextFactory.add(Ctx, D, newID);
953 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
954 return NewCtx;
955 }
956
957 // Updates a definition only if that definition is already in the map.
958 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000959 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000960 if (Ctx.contains(D)) {
961 unsigned newID = VarDefinitions.size();
962 Context NewCtx = ContextFactory.remove(Ctx, D);
963 NewCtx = ContextFactory.add(NewCtx, D, newID);
964 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
965 return NewCtx;
966 }
967 return Ctx;
968 }
969
970 // Removes a definition from the context, but keeps the variable name
971 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000972 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000973 Context NewCtx = Ctx;
974 if (NewCtx.contains(D)) {
975 NewCtx = ContextFactory.remove(NewCtx, D);
976 NewCtx = ContextFactory.add(NewCtx, D, 0);
977 }
978 return NewCtx;
979 }
980
981 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000982 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000983 Context NewCtx = Ctx;
984 if (NewCtx.contains(D)) {
985 NewCtx = ContextFactory.remove(NewCtx, D);
986 }
987 return NewCtx;
988 }
989
990 Context intersectContexts(Context C1, Context C2);
991 Context createReferenceContext(Context C);
992 void intersectBackEdge(Context C1, Context C2);
993
994 friend class VarMapBuilder;
995};
996
997
998// This has to be defined after LocalVariableMap.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000999CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1000 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001001}
1002
1003
1004/// Visitor which builds a LocalVariableMap
1005class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1006public:
1007 LocalVariableMap* VMap;
1008 LocalVariableMap::Context Ctx;
1009
1010 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1011 : VMap(VM), Ctx(C) {}
1012
1013 void VisitDeclStmt(DeclStmt *S);
1014 void VisitBinaryOperator(BinaryOperator *BO);
1015};
1016
1017
1018// Add new local variables to the variable map
1019void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1020 bool modifiedCtx = false;
1021 DeclGroupRef DGrp = S->getDeclGroup();
1022 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1023 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1024 Expr *E = VD->getInit();
1025
1026 // Add local variables with trivial type to the variable map
1027 QualType T = VD->getType();
1028 if (T.isTrivialType(VD->getASTContext())) {
1029 Ctx = VMap->addDefinition(VD, E, Ctx);
1030 modifiedCtx = true;
1031 }
1032 }
1033 }
1034 if (modifiedCtx)
1035 VMap->saveContext(S, Ctx);
1036}
1037
1038// Update local variable definitions in variable map
1039void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1040 if (!BO->isAssignmentOp())
1041 return;
1042
1043 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1044
1045 // Update the variable map and current context.
1046 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1047 ValueDecl *VDec = DRE->getDecl();
1048 if (Ctx.lookup(VDec)) {
1049 if (BO->getOpcode() == BO_Assign)
1050 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1051 else
1052 // FIXME -- handle compound assignment operators
1053 Ctx = VMap->clearDefinition(VDec, Ctx);
1054 VMap->saveContext(BO, Ctx);
1055 }
1056 }
1057}
1058
1059
1060// Computes the intersection of two contexts. The intersection is the
1061// set of variables which have the same definition in both contexts;
1062// variables with different definitions are discarded.
1063LocalVariableMap::Context
1064LocalVariableMap::intersectContexts(Context C1, Context C2) {
1065 Context Result = C1;
1066 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001067 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001068 unsigned i1 = I.getData();
1069 const unsigned *i2 = C2.lookup(Dec);
1070 if (!i2) // variable doesn't exist on second path
1071 Result = removeDefinition(Dec, Result);
1072 else if (*i2 != i1) // variable exists, but has different definition
1073 Result = clearDefinition(Dec, Result);
1074 }
1075 return Result;
1076}
1077
1078// For every variable in C, create a new variable that refers to the
1079// definition in C. Return a new context that contains these new variables.
1080// (We use this for a naive implementation of SSA on loop back-edges.)
1081LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1082 Context Result = getEmptyContext();
1083 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001084 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001085 unsigned i = I.getData();
1086 Result = addReference(Dec, i, Result);
1087 }
1088 return Result;
1089}
1090
1091// This routine also takes the intersection of C1 and C2, but it does so by
1092// altering the VarDefinitions. C1 must be the result of an earlier call to
1093// createReferenceContext.
1094void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1095 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001096 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001097 unsigned i1 = I.getData();
1098 VarDefinition *VDef = &VarDefinitions[i1];
1099 assert(VDef->isReference());
1100
1101 const unsigned *i2 = C2.lookup(Dec);
1102 if (!i2 || (*i2 != i1))
1103 VDef->Ref = 0; // Mark this variable as undefined
1104 }
1105}
1106
1107
1108// Traverse the CFG in topological order, so all predecessors of a block
1109// (excluding back-edges) are visited before the block itself. At
1110// each point in the code, we calculate a Context, which holds the set of
1111// variable definitions which are visible at that point in execution.
1112// Visible variables are mapped to their definitions using an array that
1113// contains all definitions.
1114//
1115// At join points in the CFG, the set is computed as the intersection of
1116// the incoming sets along each edge, E.g.
1117//
1118// { Context | VarDefinitions }
1119// int x = 0; { x -> x1 | x1 = 0 }
1120// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1121// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1122// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1123// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1124//
1125// This is essentially a simpler and more naive version of the standard SSA
1126// algorithm. Those definitions that remain in the intersection are from blocks
1127// that strictly dominate the current block. We do not bother to insert proper
1128// phi nodes, because they are not used in our analysis; instead, wherever
1129// a phi node would be required, we simply remove that definition from the
1130// context (E.g. x above).
1131//
1132// The initial traversal does not capture back-edges, so those need to be
1133// handled on a separate pass. Whenever the first pass encounters an
1134// incoming back edge, it duplicates the context, creating new definitions
1135// that refer back to the originals. (These correspond to places where SSA
1136// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001137// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001138// node was actually required.) E.g.
1139//
1140// { Context | VarDefinitions }
1141// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1142// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1143// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1144// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1145//
1146void LocalVariableMap::traverseCFG(CFG *CFGraph,
1147 PostOrderCFGView *SortedGraph,
1148 std::vector<CFGBlockInfo> &BlockInfo) {
1149 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1150
1151 CtxIndices.resize(CFGraph->getNumBlockIDs());
1152
1153 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1154 E = SortedGraph->end(); I!= E; ++I) {
1155 const CFGBlock *CurrBlock = *I;
1156 int CurrBlockID = CurrBlock->getBlockID();
1157 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1158
1159 VisitedBlocks.insert(CurrBlock);
1160
1161 // Calculate the entry context for the current block
1162 bool HasBackEdges = false;
1163 bool CtxInit = true;
1164 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1165 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1166 // if *PI -> CurrBlock is a back edge, so skip it
1167 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1168 HasBackEdges = true;
1169 continue;
1170 }
1171
1172 int PrevBlockID = (*PI)->getBlockID();
1173 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1174
1175 if (CtxInit) {
1176 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1177 CtxInit = false;
1178 }
1179 else {
1180 CurrBlockInfo->EntryContext =
1181 intersectContexts(CurrBlockInfo->EntryContext,
1182 PrevBlockInfo->ExitContext);
1183 }
1184 }
1185
1186 // Duplicate the context if we have back-edges, so we can call
1187 // intersectBackEdges later.
1188 if (HasBackEdges)
1189 CurrBlockInfo->EntryContext =
1190 createReferenceContext(CurrBlockInfo->EntryContext);
1191
1192 // Create a starting context index for the current block
1193 saveContext(0, CurrBlockInfo->EntryContext);
1194 CurrBlockInfo->EntryIndex = getContextIndex();
1195
1196 // Visit all the statements in the basic block.
1197 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1198 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1199 BE = CurrBlock->end(); BI != BE; ++BI) {
1200 switch (BI->getKind()) {
1201 case CFGElement::Statement: {
1202 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1203 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1204 break;
1205 }
1206 default:
1207 break;
1208 }
1209 }
1210 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1211
1212 // Mark variables on back edges as "unknown" if they've been changed.
1213 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1214 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1215 // if CurrBlock -> *SI is *not* a back edge
1216 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1217 continue;
1218
1219 CFGBlock *FirstLoopBlock = *SI;
1220 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1221 Context LoopEnd = CurrBlockInfo->ExitContext;
1222 intersectBackEdge(LoopBegin, LoopEnd);
1223 }
1224 }
1225
1226 // Put an extra entry at the end of the indexed context array
1227 unsigned exitID = CFGraph->getExit().getBlockID();
1228 saveContext(0, BlockInfo[exitID].ExitContext);
1229}
1230
Richard Smith2e515622012-02-03 04:45:26 +00001231/// Find the appropriate source locations to use when producing diagnostics for
1232/// each block in the CFG.
1233static void findBlockLocations(CFG *CFGraph,
1234 PostOrderCFGView *SortedGraph,
1235 std::vector<CFGBlockInfo> &BlockInfo) {
1236 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1237 E = SortedGraph->end(); I!= E; ++I) {
1238 const CFGBlock *CurrBlock = *I;
1239 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1240
1241 // Find the source location of the last statement in the block, if the
1242 // block is not empty.
1243 if (const Stmt *S = CurrBlock->getTerminator()) {
1244 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1245 } else {
1246 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1247 BE = CurrBlock->rend(); BI != BE; ++BI) {
1248 // FIXME: Handle other CFGElement kinds.
1249 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1250 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1251 break;
1252 }
1253 }
1254 }
1255
1256 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1257 // This block contains at least one statement. Find the source location
1258 // of the first statement in the block.
1259 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1260 BE = CurrBlock->end(); BI != BE; ++BI) {
1261 // FIXME: Handle other CFGElement kinds.
1262 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1263 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1264 break;
1265 }
1266 }
1267 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1268 CurrBlock != &CFGraph->getExit()) {
1269 // The block is empty, and has a single predecessor. Use its exit
1270 // location.
1271 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1272 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1273 }
1274 }
1275}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001276
1277/// \brief Class which implements the core thread safety analysis routines.
1278class ThreadSafetyAnalyzer {
1279 friend class BuildLockset;
1280
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001281 ThreadSafetyHandler &Handler;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001282 LocalVariableMap LocalVarMap;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001283 FactManager FactMan;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001284 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001285
1286public:
1287 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1288
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001289 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1290 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001291 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001292
1293 template <typename AttrType>
1294 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1295 const NamedDecl *D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001296
1297 template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001298 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1299 const NamedDecl *D,
1300 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1301 Expr *BrE, bool Neg);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001302
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001303 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1304 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001305
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001306 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1307 const CFGBlock* PredBlock,
1308 const CFGBlock *CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001309
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001310 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1311 SourceLocation JoinLoc,
1312 LockErrorKind LEK1, LockErrorKind LEK2,
1313 bool Modify=true);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001314
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001315 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1316 SourceLocation JoinLoc, LockErrorKind LEK1,
1317 bool Modify=true) {
1318 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001319 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001320
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001321 void runAnalysis(AnalysisDeclContext &AC);
1322};
1323
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001324
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001325/// \brief Add a new lock to the lockset, warning if the lock is already there.
1326/// \param Mutex -- the Mutex expression for the lock
1327/// \param LDat -- the LockData for the lock
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001328void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001329 const LockData &LDat) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001330 // FIXME: deal with acquired before/after annotations.
1331 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001332 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001333 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001334 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001335 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001336 }
1337}
1338
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001339
1340/// \brief Remove a lock from the lockset, warning if the lock is not there.
1341/// \param LockExp The lock expression corresponding to the lock to be removed
1342/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001343void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001344 const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001345 SourceLocation UnlockLoc,
1346 bool FullyRemove) {
1347 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001348 if (!LDat) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001349 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001350 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001351 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001352
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001353 if (LDat->UnderlyingMutex.isValid()) {
1354 // This is scoped lockable object, which manages the real mutex.
1355 if (FullyRemove) {
1356 // We're destroying the managing object.
1357 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001358 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1359 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001360 } else {
1361 // We're releasing the underlying mutex, but not destroying the
1362 // managing object. Warn on dual release.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001363 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001364 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001365 UnlockLoc);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001366 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001367 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1368 return;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001369 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001370 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001371 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001372}
1373
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001374
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001375/// \brief Extract the list of mutexIDs from the attribute on an expression,
1376/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001377template <typename AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001378void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1379 Expr *Exp, const NamedDecl *D) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001380 typedef typename AttrType::args_iterator iterator_type;
1381
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001382 if (Attr->args_size() == 0) {
1383 // The mutex held is the "this" object.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001384 SExpr Mu(0, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001385 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001386 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001387 else
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001388 Mtxs.push_back_nodup(Mu);
1389 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001390 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001391
1392 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001393 SExpr Mu(*I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001394 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001395 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001396 else
1397 Mtxs.push_back_nodup(Mu);
1398 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001399}
1400
1401
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001402/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1403/// trylock applies to the given edge, then push them onto Mtxs, discarding
1404/// any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001405template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001406void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1407 Expr *Exp, const NamedDecl *D,
1408 const CFGBlock *PredBlock,
1409 const CFGBlock *CurrBlock,
1410 Expr *BrE, bool Neg) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001411 // Find out which branch has the lock
1412 bool branch = 0;
1413 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1414 branch = BLE->getValue();
1415 }
1416 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1417 branch = ILE->getValue().getBoolValue();
1418 }
1419 int branchnum = branch ? 0 : 1;
1420 if (Neg) branchnum = !branchnum;
1421
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001422 // If we've taken the trylock branch, then add the lock
1423 int i = 0;
1424 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1425 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1426 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001427 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001428 }
1429 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001430}
1431
1432
DeLesley Hutchins13106112012-07-10 21:47:55 +00001433bool getStaticBooleanValue(Expr* E, bool& TCond) {
1434 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1435 TCond = false;
1436 return true;
1437 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1438 TCond = BLE->getValue();
1439 return true;
1440 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1441 TCond = ILE->getValue().getBoolValue();
1442 return true;
1443 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1444 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1445 }
1446 return false;
1447}
1448
1449
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001450// If Cond can be traced back to a function call, return the call expression.
1451// The negate variable should be called with false, and will be set to true
1452// if the function call is negated, e.g. if (!mu.tryLock(...))
1453const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1454 LocalVarContext C,
1455 bool &Negate) {
1456 if (!Cond)
1457 return 0;
1458
1459 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1460 return CallExp;
1461 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001462 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1463 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1464 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001465 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1466 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1467 }
1468 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1469 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1470 return getTrylockCallExpr(E, C, Negate);
1471 }
1472 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1473 if (UOP->getOpcode() == UO_LNot) {
1474 Negate = !Negate;
1475 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1476 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001477 return 0;
1478 }
1479 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1480 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1481 if (BOP->getOpcode() == BO_NE)
1482 Negate = !Negate;
1483
1484 bool TCond = false;
1485 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1486 if (!TCond) Negate = !Negate;
1487 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1488 }
1489 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1490 if (!TCond) Negate = !Negate;
1491 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1492 }
1493 return 0;
1494 }
1495 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001496 }
1497 // FIXME -- handle && and || as well.
DeLesley Hutchins13106112012-07-10 21:47:55 +00001498 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001499}
1500
1501
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001502/// \brief Find the lockset that holds on the edge between PredBlock
1503/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1504/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001505void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1506 const FactSet &ExitSet,
1507 const CFGBlock *PredBlock,
1508 const CFGBlock *CurrBlock) {
1509 Result = ExitSet;
1510
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001511 if (!PredBlock->getTerminatorCondition())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001512 return;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001513
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001514 bool Negate = false;
1515 const Stmt *Cond = PredBlock->getTerminatorCondition();
1516 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1517 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1518
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001519 CallExpr *Exp =
1520 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001521 if (!Exp)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001522 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001523
1524 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1525 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001526 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001527
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001528
1529 MutexIDList ExclusiveLocksToAdd;
1530 MutexIDList SharedLocksToAdd;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001531
1532 // If the condition is a call to a Trylock function, then grab the attributes
1533 AttrVec &ArgAttrs = FunDecl->getAttrs();
1534 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1535 Attr *Attr = ArgAttrs[i];
1536 switch (Attr->getKind()) {
1537 case attr::ExclusiveTrylockFunction: {
1538 ExclusiveTrylockFunctionAttr *A =
1539 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001540 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1541 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001542 break;
1543 }
1544 case attr::SharedTrylockFunction: {
1545 SharedTrylockFunctionAttr *A =
1546 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001547 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1548 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001549 break;
1550 }
1551 default:
1552 break;
1553 }
1554 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001555
1556 // Add and remove locks.
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001557 SourceLocation Loc = Exp->getExprLoc();
1558 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001559 addLock(Result, ExclusiveLocksToAdd[i],
1560 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001561 }
1562 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001563 addLock(Result, SharedLocksToAdd[i],
1564 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001565 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001566}
1567
1568
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001569/// \brief We use this class to visit different types of expressions in
1570/// CFGBlocks, and build up the lockset.
1571/// An expression may cause us to add or remove locks from the lockset, or else
1572/// output error messages related to missing locks.
1573/// FIXME: In future, we may be able to not inherit from a visitor.
1574class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001575 friend class ThreadSafetyAnalyzer;
1576
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001577 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001578 FactSet FSet;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001579 LocalVariableMap::Context LVarCtx;
1580 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001581
1582 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001583 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001584
1585 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1586 Expr *MutexExp, ProtectedOperationKind POK);
1587
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001588 void checkAccess(Expr *Exp, AccessKind AK);
1589 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001590 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001591
1592 /// \brief Returns true if the lockset contains a lock, regardless of whether
1593 /// the lock is held exclusively or shared.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001594 bool locksetContains(const SExpr &Mu) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001595 return FSet.findLock(Analyzer->FactMan, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001596 }
1597
1598 /// \brief Returns true if the lockset contains a lock with the passed in
1599 /// locktype.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001600 bool locksetContains(const SExpr &Mu, LockKind KindRequested) const {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001601 const LockData *LockHeld = FSet.findLock(Analyzer->FactMan, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001602 return (LockHeld && KindRequested == LockHeld->LKind);
1603 }
1604
1605 /// \brief Returns true if the lockset contains a lock with at least the
1606 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1607 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1608 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001609 bool locksetContainsAtLeast(const SExpr &Lock,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001610 LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001611 switch (KindRequested) {
1612 case LK_Shared:
1613 return locksetContains(Lock);
1614 case LK_Exclusive:
1615 return locksetContains(Lock, KindRequested);
1616 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001617 llvm_unreachable("Unknown LockKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001618 }
1619
1620public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001621 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001622 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001623 Analyzer(Anlzr),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001624 FSet(Info.EntrySet),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001625 LVarCtx(Info.EntryContext),
1626 CtxIndex(Info.EntryIndex)
1627 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001628
1629 void VisitUnaryOperator(UnaryOperator *UO);
1630 void VisitBinaryOperator(BinaryOperator *BO);
1631 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001632 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001633 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001634 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001635};
1636
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001637
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001638/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1639const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1640 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1641 return DR->getDecl();
1642
1643 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1644 return ME->getMemberDecl();
1645
1646 return 0;
1647}
1648
1649/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001650/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001651void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1652 AccessKind AK, Expr *MutexExp,
1653 ProtectedOperationKind POK) {
1654 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001655
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001656 SExpr Mutex(MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001657 if (!Mutex.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001658 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001659 else if (!locksetContainsAtLeast(Mutex, LK))
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001660 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001661 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001662}
1663
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001664/// \brief This method identifies variable dereferences and checks pt_guarded_by
1665/// and pt_guarded_var annotations. Note that we only check these annotations
1666/// at the time a pointer is dereferenced.
1667/// FIXME: We need to check for other types of pointer dereferences
1668/// (e.g. [], ->) and deal with them here.
1669/// \param Exp An expression that has been read or written.
1670void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1671 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1672 if (!UO || UO->getOpcode() != clang::UO_Deref)
1673 return;
1674 Exp = UO->getSubExpr()->IgnoreParenCasts();
1675
1676 const ValueDecl *D = getValueDecl(Exp);
1677 if(!D || !D->hasAttrs())
1678 return;
1679
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001680 if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001681 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1682 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001683
1684 const AttrVec &ArgAttrs = D->getAttrs();
1685 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1686 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1687 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1688}
1689
1690/// \brief Checks guarded_by and guarded_var attributes.
1691/// Whenever we identify an access (read or write) of a DeclRefExpr or
1692/// MemberExpr, we need to check whether there are any guarded_by or
1693/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1694void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1695 const ValueDecl *D = getValueDecl(Exp);
1696 if(!D || !D->hasAttrs())
1697 return;
1698
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001699 if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001700 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1701 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001702
1703 const AttrVec &ArgAttrs = D->getAttrs();
1704 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1705 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1706 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1707}
1708
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001709/// \brief Process a function call, method call, constructor call,
1710/// or destructor call. This involves looking at the attributes on the
1711/// corresponding function/method/constructor/destructor, issuing warnings,
1712/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001713///
1714/// FIXME: For classes annotated with one of the guarded annotations, we need
1715/// to treat const method calls as reads and non-const method calls as writes,
1716/// and check that the appropriate locks are held. Non-const method calls with
1717/// the same signature as const method calls can be also treated as reads.
1718///
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001719void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1720 const AttrVec &ArgAttrs = D->getAttrs();
1721 MutexIDList ExclusiveLocksToAdd;
1722 MutexIDList SharedLocksToAdd;
1723 MutexIDList LocksToRemove;
1724
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001725 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001726 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1727 switch (At->getKind()) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001728 // When we encounter an exclusive lock function, we need to add the lock
1729 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001730 case attr::ExclusiveLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001731 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1732 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001733 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001734 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001735
1736 // When we encounter a shared lock function, we need to add the lock
1737 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001738 case attr::SharedLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001739 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1740 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001741 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001742 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001743
1744 // When we encounter an unlock function, we need to remove unlocked
1745 // mutexes from the lockset, and flag a warning if they are not there.
1746 case attr::UnlockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001747 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1748 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001749 break;
1750 }
1751
1752 case attr::ExclusiveLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001753 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001754
1755 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001756 I = A->args_begin(), E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001757 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1758 break;
1759 }
1760
1761 case attr::SharedLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001762 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001763
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001764 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1765 E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001766 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1767 break;
1768 }
1769
1770 case attr::LocksExcluded: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001771 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1772 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1773 E = A->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001774 SExpr Mutex(*I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001775 if (!Mutex.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001776 SExpr::warnInvalidLock(Analyzer->Handler, *I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001777 else if (locksetContains(Mutex))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001778 Analyzer->Handler.handleFunExcludesLock(D->getName(),
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001779 Mutex.toString(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001780 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001781 }
1782 break;
1783 }
1784
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001785 // Ignore other (non thread-safety) attributes
1786 default:
1787 break;
1788 }
1789 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001790
1791 // Figure out if we're calling the constructor of scoped lockable class
1792 bool isScopedVar = false;
1793 if (VD) {
1794 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1795 const CXXRecordDecl* PD = CD->getParent();
1796 if (PD && PD->getAttr<ScopedLockableAttr>())
1797 isScopedVar = true;
1798 }
1799 }
1800
1801 // Add locks.
1802 SourceLocation Loc = Exp->getExprLoc();
1803 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001804 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1805 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001806 }
1807 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001808 Analyzer->addLock(FSet, SharedLocksToAdd[i],
1809 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001810 }
1811
1812 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1813 // FIXME -- this doesn't work if we acquire multiple locks.
1814 if (isScopedVar) {
1815 SourceLocation MLoc = VD->getLocation();
1816 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001817 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001818
1819 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001820 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
1821 ExclusiveLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001822 }
1823 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001824 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
1825 SharedLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001826 }
1827 }
1828
1829 // Remove locks.
1830 // FIXME -- should only fully remove if the attribute refers to 'this'.
1831 bool Dtor = isa<CXXDestructorDecl>(D);
1832 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001833 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001834 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001835}
1836
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001837
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001838/// \brief For unary operations which read and write a variable, we need to
1839/// check whether we hold any required mutexes. Reads are checked in
1840/// VisitCastExpr.
1841void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1842 switch (UO->getOpcode()) {
1843 case clang::UO_PostDec:
1844 case clang::UO_PostInc:
1845 case clang::UO_PreDec:
1846 case clang::UO_PreInc: {
1847 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1848 checkAccess(SubExp, AK_Written);
1849 checkDereference(SubExp, AK_Written);
1850 break;
1851 }
1852 default:
1853 break;
1854 }
1855}
1856
1857/// For binary operations which assign to a variable (writes), we need to check
1858/// whether we hold any required mutexes.
1859/// FIXME: Deal with non-primitive types.
1860void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1861 if (!BO->isAssignmentOp())
1862 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001863
1864 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001865 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001866
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001867 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1868 checkAccess(LHSExp, AK_Written);
1869 checkDereference(LHSExp, AK_Written);
1870}
1871
1872/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1873/// need to ensure we hold any required mutexes.
1874/// FIXME: Deal with non-primitive types.
1875void BuildLockset::VisitCastExpr(CastExpr *CE) {
1876 if (CE->getCastKind() != CK_LValueToRValue)
1877 return;
1878 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
1879 checkAccess(SubExp, AK_Read);
1880 checkDereference(SubExp, AK_Read);
1881}
1882
1883
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001884void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001885 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1886 if(!D || !D->hasAttrs())
1887 return;
1888 handleCall(Exp, D);
1889}
1890
1891void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001892 // FIXME -- only handles constructors in DeclStmt below.
1893}
1894
1895void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001896 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001897 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001898
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001899 DeclGroupRef DGrp = S->getDeclGroup();
1900 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1901 Decl *D = *I;
1902 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1903 Expr *E = VD->getInit();
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +00001904 // handle constructors that involve temporaries
1905 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1906 E = EWC->getSubExpr();
1907
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001908 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1909 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1910 if (!CtorD || !CtorD->hasAttrs())
1911 return;
1912 handleCall(CE, CtorD, VD);
1913 }
1914 }
1915 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001916}
1917
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001918
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001919
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001920/// \brief Compute the intersection of two locksets and issue warnings for any
1921/// locks in the symmetric difference.
1922///
1923/// This function is used at a merge point in the CFG when comparing the lockset
1924/// of each branch being merged. For example, given the following sequence:
1925/// A; if () then B; else C; D; we need to check that the lockset after B and C
1926/// are the same. In the event of a difference, we use the intersection of these
1927/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001928///
1929/// \param LSet1 The first lockset.
1930/// \param LSet2 The second lockset.
1931/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001932/// \param LEK1 The error message to report if a mutex is missing from LSet1
1933/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001934void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
1935 const FactSet &FSet2,
1936 SourceLocation JoinLoc,
1937 LockErrorKind LEK1,
1938 LockErrorKind LEK2,
1939 bool Modify) {
1940 FactSet FSet1Orig = FSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001941
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001942 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
1943 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001944 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001945 const LockData &LDat2 = FactMan[*I].LDat;
1946
1947 if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001948 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001949 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001950 LDat2.AcquireLoc,
1951 LDat1->AcquireLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001952 if (Modify && LDat1->LKind != LK_Exclusive) {
1953 FSet1.removeLock(FactMan, FSet2Mutex);
1954 FSet1.addLock(FactMan, FSet2Mutex, LDat2);
1955 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001956 }
1957 } else {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001958 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001959 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001960 // If this is a scoped lock that manages another mutex, and if the
1961 // underlying mutex is still held, then warn about the underlying
1962 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001963 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001964 LDat2.AcquireLoc,
1965 JoinLoc, LEK1);
1966 }
1967 }
1968 else if (!LDat2.Managed)
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001969 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001970 LDat2.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001971 JoinLoc, LEK1);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001972 }
1973 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001974
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001975 for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
1976 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001977 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001978 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001979
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001980 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001981 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001982 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001983 // If this is a scoped lock that manages another mutex, and if the
1984 // underlying mutex is still held, then warn about the underlying
1985 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001986 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001987 LDat1.AcquireLoc,
1988 JoinLoc, LEK1);
1989 }
1990 }
1991 else if (!LDat1.Managed)
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001992 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001993 LDat1.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001994 JoinLoc, LEK2);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001995 if (Modify)
1996 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001997 }
1998 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001999}
2000
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002001
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002002
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002003/// \brief Check a function's CFG for thread-safety violations.
2004///
2005/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2006/// at the end of each block, and issue warnings for thread safety violations.
2007/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002008void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002009 CFG *CFGraph = AC.getCFG();
2010 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002011 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2012
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002013 // AC.dumpCFG(true);
2014
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002015 if (!D)
2016 return; // Ignore anonymous functions for now.
2017 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2018 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002019 // FIXME: Do something a bit more intelligent inside constructor and
2020 // destructor code. Constructors and destructors must assume unique access
2021 // to 'this', so checks on member variable access is disabled, but we should
2022 // still enable checks on other objects.
2023 if (isa<CXXConstructorDecl>(D))
2024 return; // Don't check inside constructors.
2025 if (isa<CXXDestructorDecl>(D))
2026 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002027
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002028 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002029 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002030
2031 // We need to explore the CFG via a "topological" ordering.
2032 // That way, we will be guaranteed to have information about required
2033 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00002034 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2035 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002036
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002037 // Compute SSA names for local variables
2038 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2039
Richard Smith2e515622012-02-03 04:45:26 +00002040 // Fill in source locations for all CFGBlocks.
2041 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2042
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002043 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002044 // to initial lockset. Also turn off checking for lock and unlock functions.
2045 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00002046 if (!SortedGraph->empty() && D->hasAttrs()) {
2047 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002048 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002049 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002050
2051 MutexIDList ExclusiveLocksToAdd;
2052 MutexIDList SharedLocksToAdd;
2053
2054 SourceLocation Loc = D->getLocation();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002055 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002056 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002057 Loc = Attr->getLocation();
2058 if (ExclusiveLocksRequiredAttr *A
2059 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2060 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2061 } else if (SharedLocksRequiredAttr *A
2062 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2063 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002064 } else if (isa<UnlockFunctionAttr>(Attr)) {
2065 // Don't try to check unlock functions for now
2066 return;
2067 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
2068 // Don't try to check lock functions for now
2069 return;
2070 } else if (isa<SharedLockFunctionAttr>(Attr)) {
2071 // Don't try to check lock functions for now
2072 return;
DeLesley Hutchins76f0a6e2012-07-02 21:59:24 +00002073 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2074 // Don't try to check trylock functions for now
2075 return;
2076 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2077 // Don't try to check trylock functions for now
2078 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002079 }
2080 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002081
2082 // FIXME -- Loc can be wrong here.
2083 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002084 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2085 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002086 }
2087 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002088 addLock(InitialLockset, SharedLocksToAdd[i],
2089 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002090 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002091 }
2092
Ted Kremenek439ed162011-10-22 02:14:27 +00002093 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2094 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002095 const CFGBlock *CurrBlock = *I;
2096 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002097 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002098
2099 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002100 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002101
2102 // Iterate through the predecessor blocks and warn if the lockset for all
2103 // predecessors is not the same. We take the entry lockset of the current
2104 // block to be the intersection of all previous locksets.
2105 // FIXME: By keeping the intersection, we may output more errors in future
2106 // for a lock which is not in the intersection, but was in the union. We
2107 // may want to also keep the union in future. As an example, let's say
2108 // the intersection contains Mutex L, and the union contains L and M.
2109 // Later we unlock M. At this point, we would output an error because we
2110 // never locked M; although the real error is probably that we forgot to
2111 // lock M on all code paths. Conversely, let's say that later we lock M.
2112 // In this case, we should compare against the intersection instead of the
2113 // union because the real error is probably that we forgot to unlock M on
2114 // all code paths.
2115 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00002116 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002117 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2118 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2119
2120 // if *PI -> CurrBlock is a back edge
2121 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2122 continue;
2123
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00002124 // Ignore edges from blocks that can't return.
2125 if ((*PI)->hasNoReturnElement())
2126 continue;
2127
Richard Smithaacde712012-02-03 03:30:07 +00002128 // If the previous block ended in a 'continue' or 'break' statement, then
2129 // a difference in locksets is probably due to a bug in that block, rather
2130 // than in some other predecessor. In that case, keep the other
2131 // predecessor's lockset.
2132 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2133 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2134 SpecialBlocks.push_back(*PI);
2135 continue;
2136 }
2137 }
2138
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002139 int PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002140 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002141 FactSet PrevLockset;
2142 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002143
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002144 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002145 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002146 LocksetInitialized = true;
2147 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002148 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2149 CurrBlockInfo->EntryLoc,
2150 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002151 }
2152 }
2153
Richard Smithaacde712012-02-03 03:30:07 +00002154 // Process continue and break blocks. Assume that the lockset for the
2155 // resulting block is unaffected by any discrepancies in them.
2156 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2157 SpecialI < SpecialN; ++SpecialI) {
2158 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2159 int PrevBlockID = PrevBlock->getBlockID();
2160 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2161
2162 if (!LocksetInitialized) {
2163 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2164 LocksetInitialized = true;
2165 } else {
2166 // Determine whether this edge is a loop terminator for diagnostic
2167 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2168 // it might also be part of a switch. Also, a subsequent destructor
2169 // might add to the lockset, in which case the real issue might be a
2170 // double lock on the other path.
2171 const Stmt *Terminator = PrevBlock->getTerminator();
2172 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2173
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002174 FactSet PrevLockset;
2175 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2176 PrevBlock, CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002177
Richard Smithaacde712012-02-03 03:30:07 +00002178 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002179 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2180 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00002181 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002182 : LEK_LockedSomePredecessors,
2183 false);
Richard Smithaacde712012-02-03 03:30:07 +00002184 }
2185 }
2186
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002187 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2188
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002189 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002190 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2191 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002192 switch (BI->getKind()) {
2193 case CFGElement::Statement: {
2194 const CFGStmt *CS = cast<CFGStmt>(&*BI);
2195 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
2196 break;
2197 }
2198 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2199 case CFGElement::AutomaticObjectDtor: {
2200 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
2201 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
2202 AD->getDestructorDecl(AC.getASTContext()));
2203 if (!DD->hasAttrs())
2204 break;
2205
2206 // Create a dummy expression,
2207 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00002208 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002209 AD->getTriggerStmt()->getLocEnd());
2210 LocksetBuilder.handleCall(&DRE, DD);
2211 break;
2212 }
2213 default:
2214 break;
2215 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002216 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002217 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002218
2219 // For every back edge from CurrBlock (the end of the loop) to another block
2220 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2221 // the one held at the beginning of FirstLoopBlock. We can look up the
2222 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2223 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2224 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2225
2226 // if CurrBlock -> *SI is *not* a back edge
2227 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2228 continue;
2229
2230 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002231 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2232 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2233 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2234 PreLoop->EntryLoc,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002235 LEK_LockedSomeLoopIterations,
2236 false);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002237 }
2238 }
2239
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002240 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2241 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00002242
2243 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002244 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
2245 Final->ExitLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002246 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002247 LEK_NotLockedAtEndOfFunction,
2248 false);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002249}
2250
2251} // end anonymous namespace
2252
2253
2254namespace clang {
2255namespace thread_safety {
2256
2257/// \brief Check a function's CFG for thread-safety violations.
2258///
2259/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2260/// at the end of each block, and issue warnings for thread safety violations.
2261/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002262void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002263 ThreadSafetyHandler &Handler) {
2264 ThreadSafetyAnalyzer Analyzer(Handler);
2265 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002266}
2267
2268/// \brief Helper function that returns a LockKind required for the given level
2269/// of access.
2270LockKind getLockKindFromAccessKind(AccessKind AK) {
2271 switch (AK) {
2272 case AK_Read :
2273 return LK_Shared;
2274 case AK_Written :
2275 return LK_Exclusive;
2276 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00002277 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002278}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002279
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002280}} // end namespace clang::thread_safety