blob: d9ab61e75344d3bbe422f1f1f24270775b82ebd6 [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 {
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +000073 EOP_Nop, ///< No-op
74 EOP_Wildcard, ///< Matches anything.
75 EOP_Universal, ///< Universal lock.
76 EOP_This, ///< This keyword.
77 EOP_NVar, ///< Named variable.
78 EOP_LVar, ///< Local variable.
79 EOP_Dot, ///< Field access
80 EOP_Call, ///< Function call
81 EOP_MCall, ///< Method call
82 EOP_Index, ///< Array index
83 EOP_Unary, ///< Unary operation
84 EOP_Binary, ///< Binary operation
85 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000086 };
87
88
89 class SExprNode {
90 private:
Ted Kremenekad0fe032012-08-22 23:50:41 +000091 unsigned char Op; ///< Opcode of the root node
92 unsigned char Flags; ///< Additional opcode-specific data
93 unsigned short Sz; ///< Number of child nodes
94 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +000095
96 public:
97 SExprNode(ExprOp O, unsigned F, const void* D)
98 : Op(static_cast<unsigned char>(O)),
99 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
100 { }
101
102 unsigned size() const { return Sz; }
103 void setSize(unsigned S) { Sz = S; }
104
105 ExprOp kind() const { return static_cast<ExprOp>(Op); }
106
107 const NamedDecl* getNamedDecl() const {
108 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
109 return reinterpret_cast<const NamedDecl*>(Data);
110 }
111
112 const NamedDecl* getFunctionDecl() const {
113 assert(Op == EOP_Call || Op == EOP_MCall);
114 return reinterpret_cast<const NamedDecl*>(Data);
115 }
116
117 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
118 void setArrow(bool A) { Flags = A ? 1 : 0; }
119
120 unsigned arity() const {
121 switch (Op) {
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000122 case EOP_Nop: return 0;
123 case EOP_Wildcard: return 0;
124 case EOP_Universal: return 0;
125 case EOP_NVar: return 0;
126 case EOP_LVar: return 0;
127 case EOP_This: return 0;
128 case EOP_Dot: return 1;
129 case EOP_Call: return Flags+1; // First arg is function.
130 case EOP_MCall: return Flags+1; // First arg is implicit obj.
131 case EOP_Index: return 2;
132 case EOP_Unary: return 1;
133 case EOP_Binary: return 2;
134 case EOP_Unknown: return Flags;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000135 }
136 return 0;
137 }
138
139 bool operator==(const SExprNode& Other) const {
140 // Ignore flags and size -- they don't matter.
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000141 return (Op == Other.Op &&
142 Data == Other.Data);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000143 }
144
145 bool operator!=(const SExprNode& Other) const {
146 return !(*this == Other);
147 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000148
149 bool matches(const SExprNode& Other) const {
150 return (*this == Other) ||
151 (Op == EOP_Wildcard) ||
152 (Other.Op == EOP_Wildcard);
153 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000154 };
155
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000156
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000157 /// \brief Encapsulates the lexical context of a function call. The lexical
158 /// context includes the arguments to the call, including the implicit object
159 /// argument. When an attribute containing a mutex expression is attached to
160 /// a method, the expression may refer to formal parameters of the method.
161 /// Actual arguments must be substituted for formal parameters to derive
162 /// the appropriate mutex expression in the lexical context where the function
163 /// is called. PrevCtx holds the context in which the arguments themselves
164 /// should be evaluated; multiple calling contexts can be chained together
165 /// by the lock_returned attribute.
166 struct CallingContext {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000167 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
168 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
169 bool SelfArrow; // is Self referred to with -> or .?
170 unsigned NumArgs; // Number of funArgs
171 Expr** FunArgs; // Function arguments
172 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000173
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000174 CallingContext(const NamedDecl *D = 0, Expr *S = 0,
175 unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
176 : AttrDecl(D), SelfArg(S), SelfArrow(false),
177 NumArgs(N), FunArgs(A), PrevCtx(P)
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000178 { }
179 };
180
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000181 typedef SmallVector<SExprNode, 4> NodeVector;
182
183private:
184 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
185 // the list to be traversed as a tree.
186 NodeVector NodeVec;
187
188private:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000189 unsigned makeNop() {
190 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
191 return NodeVec.size()-1;
192 }
193
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000194 unsigned makeWildcard() {
195 NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
196 return NodeVec.size()-1;
197 }
198
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000199 unsigned makeUniversal() {
200 NodeVec.push_back(SExprNode(EOP_Universal, 0, 0));
201 return NodeVec.size()-1;
202 }
203
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000204 unsigned makeNamedVar(const NamedDecl *D) {
205 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
206 return NodeVec.size()-1;
207 }
208
209 unsigned makeLocalVar(const NamedDecl *D) {
210 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
211 return NodeVec.size()-1;
212 }
213
214 unsigned makeThis() {
215 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
216 return NodeVec.size()-1;
217 }
218
219 unsigned makeDot(const NamedDecl *D, bool Arrow) {
220 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
221 return NodeVec.size()-1;
222 }
223
224 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
225 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
226 return NodeVec.size()-1;
227 }
228
DeLesley Hutchins186af2d2012-09-20 22:18:02 +0000229 // Grab the very first declaration of virtual method D
230 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
231 while (true) {
232 D = D->getCanonicalDecl();
233 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
234 E = D->end_overridden_methods();
235 if (I == E)
236 return D; // Method does not override anything
237 D = *I; // FIXME: this does not work with multiple inheritance.
238 }
239 return 0;
240 }
241
242 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
243 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, getFirstVirtualDecl(D)));
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000244 return NodeVec.size()-1;
245 }
246
247 unsigned makeIndex() {
248 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
249 return NodeVec.size()-1;
250 }
251
252 unsigned makeUnary() {
253 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
254 return NodeVec.size()-1;
255 }
256
257 unsigned makeBinary() {
258 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
259 return NodeVec.size()-1;
260 }
261
262 unsigned makeUnknown(unsigned Arity) {
263 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
264 return NodeVec.size()-1;
265 }
266
267 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000268 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000269 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000270 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000271 ///
272 /// NDeref returns the number of Derefence and AddressOf operations
273 /// preceeding the Expr; this is used to decide whether to pretty-print
274 /// SExprs with . or ->.
275 unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
276 if (!Exp)
277 return 0;
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000278
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000279 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
280 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000281 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
282 if (PV) {
283 FunctionDecl *FD =
284 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
285 unsigned i = PV->getFunctionScopeIndex();
286
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000287 if (CallCtx && CallCtx->FunArgs &&
288 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000289 // Substitute call arguments for references to function parameters
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000290 assert(i < CallCtx->NumArgs);
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000291 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000292 }
293 // Map the param back to the param of the original function declaration.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000294 makeNamedVar(FD->getParamDecl(i));
295 return 1;
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000296 }
297 // Not a function parameter -- just store the reference.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000298 makeNamedVar(ND);
299 return 1;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000300 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000301 // Substitute parent for 'this'
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000302 if (CallCtx && CallCtx->SelfArg) {
303 if (!CallCtx->SelfArrow && NDeref)
304 // 'this' is a pointer, but self is not, so need to take address.
305 --(*NDeref);
306 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
307 }
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000308 else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000309 makeThis();
310 return 1;
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000311 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000312 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
313 NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000314 int ImplicitDeref = ME->isArrow() ? 1 : 0;
315 unsigned Root = makeDot(ND, false);
316 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
317 NodeVec[Root].setArrow(ImplicitDeref > 0);
318 NodeVec[Root].setSize(Sz + 1);
319 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000320 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000321 // When calling a function with a lock_returned attribute, replace
322 // the function call with the expression in lock_returned.
DeLesley Hutchins54081532012-08-31 22:09:53 +0000323 CXXMethodDecl* MD =
324 cast<CXXMethodDecl>(CMCE->getMethodDecl()->getMostRecentDecl());
325 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000326 CallingContext LRCallCtx(CMCE->getMethodDecl());
327 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000328 LRCallCtx.SelfArrow =
329 dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000330 LRCallCtx.NumArgs = CMCE->getNumArgs();
331 LRCallCtx.FunArgs = CMCE->getArgs();
332 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000333 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000334 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000335 // Hack to treat smart pointers and iterators as pointers;
336 // ignore any method named get().
337 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
338 CMCE->getNumArgs() == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000339 if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
340 ++(*NDeref);
341 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000342 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000343 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchins186af2d2012-09-20 22:18:02 +0000344 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000345 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000346 Expr** CallArgs = CMCE->getArgs();
347 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000348 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000349 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000350 NodeVec[Root].setSize(Sz + 1);
351 return Sz + 1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000352 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
DeLesley Hutchins54081532012-08-31 22:09:53 +0000353 FunctionDecl* FD =
354 cast<FunctionDecl>(CE->getDirectCallee()->getMostRecentDecl());
355 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000356 CallingContext LRCallCtx(CE->getDirectCallee());
357 LRCallCtx.NumArgs = CE->getNumArgs();
358 LRCallCtx.FunArgs = CE->getArgs();
359 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000360 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000361 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000362 // Treat smart pointers and iterators as pointers;
363 // ignore the * and -> operators.
364 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
365 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000366 if (k == OO_Star) {
367 if (NDeref) ++(*NDeref);
368 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
369 }
370 else if (k == OO_Arrow) {
371 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000372 }
373 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000374 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000375 unsigned Root = makeCall(NumCallArgs, 0);
376 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000377 Expr** CallArgs = CE->getArgs();
378 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000379 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000380 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000381 NodeVec[Root].setSize(Sz+1);
382 return Sz+1;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000383 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000384 unsigned Root = makeBinary();
385 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
386 Sz += buildSExpr(BOE->getRHS(), CallCtx);
387 NodeVec[Root].setSize(Sz);
388 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000389 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000390 // Ignore & and * operators -- they're no-ops.
391 // However, we try to figure out whether the expression is a pointer,
392 // so we can use . and -> appropriately in error messages.
393 if (UOE->getOpcode() == UO_Deref) {
394 if (NDeref) ++(*NDeref);
395 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
396 }
397 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000398 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
399 if (DRE->getDecl()->isCXXInstanceMember()) {
400 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
401 // We interpret this syntax specially, as a wildcard.
402 unsigned Root = makeDot(DRE->getDecl(), false);
403 makeWildcard();
404 NodeVec[Root].setSize(2);
405 return 2;
406 }
407 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000408 if (NDeref) --(*NDeref);
409 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
410 }
411 unsigned Root = makeUnary();
412 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
413 NodeVec[Root].setSize(Sz);
414 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000415 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000416 unsigned Root = makeIndex();
417 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
418 Sz += buildSExpr(ASE->getIdx(), CallCtx);
419 NodeVec[Root].setSize(Sz);
420 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000421 } else if (AbstractConditionalOperator *CE =
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000422 dyn_cast<AbstractConditionalOperator>(Exp)) {
423 unsigned Root = makeUnknown(3);
424 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
425 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
426 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
427 NodeVec[Root].setSize(Sz);
428 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000429 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000430 unsigned Root = makeUnknown(3);
431 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
432 Sz += buildSExpr(CE->getLHS(), CallCtx);
433 Sz += buildSExpr(CE->getRHS(), CallCtx);
434 NodeVec[Root].setSize(Sz);
435 return Sz;
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000436 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000437 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000438 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000439 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000440 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000441 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000442 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000443 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000444 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000445 isa<CXXNullPtrLiteralExpr>(Exp) ||
446 isa<GNUNullExpr>(Exp) ||
447 isa<CXXBoolLiteralExpr>(Exp) ||
448 isa<FloatingLiteral>(Exp) ||
449 isa<ImaginaryLiteral>(Exp) ||
450 isa<IntegerLiteral>(Exp) ||
451 isa<StringLiteral>(Exp) ||
452 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000453 makeNop();
454 return 1; // FIXME: Ignore literals for now
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000455 } else {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000456 makeNop();
457 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000458 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000459 }
460
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000461 /// \brief Construct a SExpr from an expression.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000462 /// \param MutexExp The original mutex expression within an attribute
463 /// \param DeclExp An expression involving the Decl on which the attribute
464 /// occurs.
465 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000466 void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000467 CallingContext CallCtx(D);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000468
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000469 if (MutexExp) {
470 if (StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
471 if (SLit->getString() == StringRef("*"))
472 // The "*" expr is a universal lock, which essentially turns off
473 // checks until it is removed from the lockset.
474 makeUniversal();
475 else
476 // Ignore other string literals for now.
477 makeNop();
478 return;
479 }
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000480 }
481
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000482 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000483 if (DeclExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000484 buildSExpr(MutexExp, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000485 return;
486 }
487
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000488 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000489 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000490 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000491 CallCtx.SelfArg = ME->getBase();
492 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000493 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000494 CallCtx.SelfArg = CE->getImplicitObjectArgument();
495 CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
496 CallCtx.NumArgs = CE->getNumArgs();
497 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000498 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000499 CallCtx.NumArgs = CE->getNumArgs();
500 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000501 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000502 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
503 CallCtx.NumArgs = CE->getNumArgs();
504 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000505 } else if (D && isa<CXXDestructorDecl>(D)) {
506 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000507 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000508 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000509
510 // If the attribute has no arguments, then assume the argument is "this".
511 if (MutexExp == 0) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000512 buildSExpr(CallCtx.SelfArg, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000513 return;
514 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000515
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000516 // For most attributes.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000517 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000518 }
519
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000520 /// \brief Get index of next sibling of node i.
521 unsigned getNextSibling(unsigned i) const {
522 return i + NodeVec[i].size();
523 }
524
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000525public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000526 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000527
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000528 /// \param MutexExp The original mutex expression within an attribute
529 /// \param DeclExp An expression involving the Decl on which the attribute
530 /// occurs.
531 /// \param D The declaration to which the lock/unlock attribute is attached.
532 /// Caller must check isValid() after construction.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000533 SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
534 buildSExprFromExpr(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000535 }
536
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000537 /// Return true if this is a valid decl sequence.
538 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000539 bool isValid() const {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000540 return !NodeVec.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000541 }
542
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +0000543 bool shouldIgnore() const {
544 // Nop is a mutex that we have decided to deliberately ignore.
545 assert(NodeVec.size() > 0 && "Invalid Mutex");
546 return NodeVec[0].kind() == EOP_Nop;
547 }
548
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000549 bool isUniversal() const {
550 assert(NodeVec.size() > 0 && "Invalid Mutex");
551 return NodeVec[0].kind() == EOP_Universal;
552 }
553
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000554 /// Issue a warning about an invalid lock expression
555 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
556 Expr *DeclExp, const NamedDecl* D) {
557 SourceLocation Loc;
558 if (DeclExp)
559 Loc = DeclExp->getExprLoc();
560
561 // FIXME: add a note about the attribute location in MutexExp or D
562 if (Loc.isValid())
563 Handler.handleInvalidLockExp(Loc);
564 }
565
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000566 bool operator==(const SExpr &other) const {
567 return NodeVec == other.NodeVec;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000568 }
569
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000570 bool operator!=(const SExpr &other) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000571 return !(*this == other);
572 }
573
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000574 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
575 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchinsf9ee0ba2012-09-11 23:04:49 +0000576 unsigned ni = NodeVec[i].arity();
577 unsigned nj = Other.NodeVec[j].arity();
578 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000579 bool Result = true;
580 unsigned ci = i+1; // first child of i
581 unsigned cj = j+1; // first child of j
582 for (unsigned k = 0; k < n;
583 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
584 Result = Result && matches(Other, ci, cj);
585 }
586 return Result;
587 }
588 return false;
589 }
590
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000591 // A partial match between a.mu and b.mu returns true a and b have the same
592 // type (and thus mu refers to the same mutex declaration), regardless of
593 // whether a and b are different objects or not.
594 bool partiallyMatches(const SExpr &Other) const {
595 if (NodeVec[0].kind() == EOP_Dot)
596 return NodeVec[0].matches(Other.NodeVec[0]);
597 return false;
598 }
599
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000600 /// \brief Pretty print a lock expression for use in error messages.
601 std::string toString(unsigned i = 0) const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000602 assert(isValid());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000603 if (i >= NodeVec.size())
604 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000605
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000606 const SExprNode* N = &NodeVec[i];
607 switch (N->kind()) {
608 case EOP_Nop:
609 return "_";
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000610 case EOP_Wildcard:
611 return "(?)";
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000612 case EOP_Universal:
613 return "*";
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000614 case EOP_This:
615 return "this";
616 case EOP_NVar:
617 case EOP_LVar: {
618 return N->getNamedDecl()->getNameAsString();
619 }
620 case EOP_Dot: {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000621 if (NodeVec[i+1].kind() == EOP_Wildcard) {
622 std::string S = "&";
623 S += N->getNamedDecl()->getQualifiedNameAsString();
624 return S;
625 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000626 std::string FieldName = N->getNamedDecl()->getNameAsString();
627 if (NodeVec[i+1].kind() == EOP_This)
628 return FieldName;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000629
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000630 std::string S = toString(i+1);
631 if (N->isArrow())
632 return S + "->" + FieldName;
633 else
634 return S + "." + FieldName;
635 }
636 case EOP_Call: {
637 std::string S = toString(i+1) + "(";
638 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000639 unsigned ci = getNextSibling(i+1);
640 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000641 S += toString(ci);
642 if (k+1 < NumArgs) S += ",";
643 }
644 S += ")";
645 return S;
646 }
647 case EOP_MCall: {
648 std::string S = "";
649 if (NodeVec[i+1].kind() != EOP_This)
650 S = toString(i+1) + ".";
651 if (const NamedDecl *D = N->getFunctionDecl())
652 S += D->getNameAsString() + "(";
653 else
654 S += "#(";
655 unsigned NumArgs = N->arity()-1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000656 unsigned ci = getNextSibling(i+1);
657 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000658 S += toString(ci);
659 if (k+1 < NumArgs) S += ",";
660 }
661 S += ")";
662 return S;
663 }
664 case EOP_Index: {
665 std::string S1 = toString(i+1);
666 std::string S2 = toString(i+1 + NodeVec[i+1].size());
667 return S1 + "[" + S2 + "]";
668 }
669 case EOP_Unary: {
670 std::string S = toString(i+1);
671 return "#" + S;
672 }
673 case EOP_Binary: {
674 std::string S1 = toString(i+1);
675 std::string S2 = toString(i+1 + NodeVec[i+1].size());
676 return "(" + S1 + "#" + S2 + ")";
677 }
678 case EOP_Unknown: {
679 unsigned NumChildren = N->arity();
680 if (NumChildren == 0)
681 return "(...)";
682 std::string S = "(";
683 unsigned ci = i+1;
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000684 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000685 S += toString(ci);
686 if (j+1 < NumChildren) S += "#";
687 }
688 S += ")";
689 return S;
690 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000691 }
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000692 return "";
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000693 }
694};
695
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000696
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000697
698/// \brief A short list of SExprs
699class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000700public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000701 /// \brief Return true if the list contains the specified SExpr
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000702 /// Performs a linear search, because these lists are almost always very small.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000703 bool contains(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000704 for (iterator I=begin(),E=end(); I != E; ++I)
705 if ((*I) == M) return true;
706 return false;
707 }
708
709 /// \brief Push M onto list, bud discard duplicates
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000710 void push_back_nodup(const SExpr& M) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000711 if (!contains(M)) push_back(M);
712 }
713};
714
715
716
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000717/// \brief This is a helper class that stores info about the most recent
718/// accquire of a Lock.
719///
720/// The main body of the analysis maps MutexIDs to LockDatas.
721struct LockData {
722 SourceLocation AcquireLoc;
723
724 /// \brief LKind stores whether a lock is held shared or exclusively.
725 /// Note that this analysis does not currently support either re-entrant
726 /// locking or lock "upgrading" and "downgrading" between exclusive and
727 /// shared.
728 ///
729 /// FIXME: add support for re-entrant locking and lock up/downgrading
730 LockKind LKind;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000731 bool Managed; // for ScopedLockable objects
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000732 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000733
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000734 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
735 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
736 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000737 {}
738
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000739 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000740 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
741 UnderlyingMutex(Mu)
742 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000743
744 bool operator==(const LockData &other) const {
745 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
746 }
747
748 bool operator!=(const LockData &other) const {
749 return !(*this == other);
750 }
751
752 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000753 ID.AddInteger(AcquireLoc.getRawEncoding());
754 ID.AddInteger(LKind);
755 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000756
757 bool isAtLeast(LockKind LK) {
758 return (LK == LK_Shared) || (LKind == LK_Exclusive);
759 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000760};
761
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000762
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000763/// \brief A FactEntry stores a single fact that is known at a particular point
764/// in the program execution. Currently, this is information regarding a lock
765/// that is held at that point.
766struct FactEntry {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000767 SExpr MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000768 LockData LDat;
769
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000770 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000771 : MutID(M), LDat(L)
772 { }
773};
774
775
776typedef unsigned short FactID;
777
778/// \brief FactManager manages the memory for all facts that are created during
779/// the analysis of a single routine.
780class FactManager {
781private:
782 std::vector<FactEntry> Facts;
783
784public:
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000785 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000786 Facts.push_back(FactEntry(M,L));
787 return static_cast<unsigned short>(Facts.size() - 1);
788 }
789
790 const FactEntry& operator[](FactID F) const { return Facts[F]; }
791 FactEntry& operator[](FactID F) { return Facts[F]; }
792};
793
794
795/// \brief A FactSet is the set of facts that are known to be true at a
796/// particular program point. FactSets must be small, because they are
797/// frequently copied, and are thus implemented as a set of indices into a
798/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
799/// locks, so we can get away with doing a linear search for lookup. Note
800/// that a hashtable or map is inappropriate in this case, because lookups
801/// may involve partial pattern matches, rather than exact matches.
802class FactSet {
803private:
804 typedef SmallVector<FactID, 4> FactVec;
805
806 FactVec FactIDs;
807
808public:
809 typedef FactVec::iterator iterator;
810 typedef FactVec::const_iterator const_iterator;
811
812 iterator begin() { return FactIDs.begin(); }
813 const_iterator begin() const { return FactIDs.begin(); }
814
815 iterator end() { return FactIDs.end(); }
816 const_iterator end() const { return FactIDs.end(); }
817
818 bool isEmpty() const { return FactIDs.size() == 0; }
819
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000820 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000821 FactID F = FM.newLock(M, L);
822 FactIDs.push_back(F);
823 return F;
824 }
825
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000826 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000827 unsigned n = FactIDs.size();
828 if (n == 0)
829 return false;
830
831 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000832 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000833 FactIDs[i] = FactIDs[n-1];
834 FactIDs.pop_back();
835 return true;
836 }
837 }
DeLesley Hutchinsee2f0322012-08-10 20:29:46 +0000838 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000839 FactIDs.pop_back();
840 return true;
841 }
842 return false;
843 }
844
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000845 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier2de47702012-09-07 18:44:15 +0000846 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier589190b2012-09-07 19:49:55 +0000847 const SExpr &Exp = FM[*I].MutID;
Chad Rosier2de47702012-09-07 18:44:15 +0000848 if (Exp.matches(M))
849 return &FM[*I].LDat;
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +0000850 }
851 return 0;
852 }
853
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000854 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier2de47702012-09-07 18:44:15 +0000855 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier589190b2012-09-07 19:49:55 +0000856 const SExpr &Exp = FM[*I].MutID;
Chad Rosier2de47702012-09-07 18:44:15 +0000857 if (Exp.matches(M) || Exp.isUniversal())
858 return &FM[*I].LDat;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000859 }
860 return 0;
861 }
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +0000862
863 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
864 for (const_iterator I=begin(), E=end(); I != E; ++I) {
865 const SExpr& Exp = FM[*I].MutID;
866 if (Exp.partiallyMatches(M)) return &FM[*I];
867 }
868 return 0;
869 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000870};
871
872
873
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000874/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000875/// been locked.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +0000876typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000877typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000878
879class LocalVariableMap;
880
Richard Smith2e515622012-02-03 04:45:26 +0000881/// A side (entry or exit) of a CFG node.
882enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000883
884/// CFGBlockInfo is a struct which contains all the information that is
885/// maintained for each block in the CFG. See LocalVariableMap for more
886/// information about the contexts.
887struct CFGBlockInfo {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000888 FactSet EntrySet; // Lockset held at entry to block
889 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000890 LocalVarContext EntryContext; // Context held at entry to block
891 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000892 SourceLocation EntryLoc; // Location of first statement in block
893 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000894 unsigned EntryIndex; // Used to replay contexts later
895
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000896 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith2e515622012-02-03 04:45:26 +0000897 return Side == CBS_Entry ? EntrySet : ExitSet;
898 }
899 SourceLocation getLocation(CFGBlockSide Side) const {
900 return Side == CBS_Entry ? EntryLoc : ExitLoc;
901 }
902
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000903private:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000904 CFGBlockInfo(LocalVarContext EmptyCtx)
905 : EntryContext(EmptyCtx), ExitContext(EmptyCtx)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000906 { }
907
908public:
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +0000909 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000910};
911
912
913
914// A LocalVariableMap maintains a map from local variables to their currently
915// valid definitions. It provides SSA-like functionality when traversing the
916// CFG. Like SSA, each definition or assignment to a variable is assigned a
917// unique name (an integer), which acts as the SSA name for that definition.
918// The total set of names is shared among all CFG basic blocks.
919// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
920// with their SSA-names. Instead, we compute a Context for each point in the
921// code, which maps local variables to the appropriate SSA-name. This map
922// changes with each assignment.
923//
924// The map is computed in a single pass over the CFG. Subsequent analyses can
925// then query the map to find the appropriate Context for a statement, and use
926// that Context to look up the definitions of variables.
927class LocalVariableMap {
928public:
929 typedef LocalVarContext Context;
930
931 /// A VarDefinition consists of an expression, representing the value of the
932 /// variable, along with the context in which that expression should be
933 /// interpreted. A reference VarDefinition does not itself contain this
934 /// information, but instead contains a pointer to a previous VarDefinition.
935 struct VarDefinition {
936 public:
937 friend class LocalVariableMap;
938
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000939 const NamedDecl *Dec; // The original declaration for this variable.
940 const Expr *Exp; // The expression for this variable, OR
941 unsigned Ref; // Reference to another VarDefinition
942 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000943
944 bool isReference() { return !Exp; }
945
946 private:
947 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000948 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000949 : Dec(D), Exp(E), Ref(0), Ctx(C)
950 { }
951
952 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000953 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000954 : Dec(D), Exp(0), Ref(R), Ctx(C)
955 { }
956 };
957
958private:
959 Context::Factory ContextFactory;
960 std::vector<VarDefinition> VarDefinitions;
961 std::vector<unsigned> CtxIndices;
962 std::vector<std::pair<Stmt*, Context> > SavedContexts;
963
964public:
965 LocalVariableMap() {
966 // index 0 is a placeholder for undefined variables (aka phi-nodes).
967 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
968 }
969
970 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000971 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000972 const unsigned *i = Ctx.lookup(D);
973 if (!i)
974 return 0;
975 assert(*i < VarDefinitions.size());
976 return &VarDefinitions[*i];
977 }
978
979 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000980 /// NULL if the expression is not statically known. If successful, also
981 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000982 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000983 const unsigned *P = Ctx.lookup(D);
984 if (!P)
985 return 0;
986
987 unsigned i = *P;
988 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000989 if (VarDefinitions[i].Exp) {
990 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000991 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000992 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000993 i = VarDefinitions[i].Ref;
994 }
995 return 0;
996 }
997
998 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
999
1000 /// Return the next context after processing S. This function is used by
1001 /// clients of the class to get the appropriate context when traversing the
1002 /// CFG. It must be called for every assignment or DeclStmt.
1003 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1004 if (SavedContexts[CtxIndex+1].first == S) {
1005 CtxIndex++;
1006 Context Result = SavedContexts[CtxIndex].second;
1007 return Result;
1008 }
1009 return C;
1010 }
1011
1012 void dumpVarDefinitionName(unsigned i) {
1013 if (i == 0) {
1014 llvm::errs() << "Undefined";
1015 return;
1016 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001017 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001018 if (!Dec) {
1019 llvm::errs() << "<<NULL>>";
1020 return;
1021 }
1022 Dec->printName(llvm::errs());
Roman Divacky31ba6132012-09-06 15:59:27 +00001023 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001024 }
1025
1026 /// Dumps an ASCII representation of the variable map to llvm::errs()
1027 void dump() {
1028 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001029 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001030 unsigned Ref = VarDefinitions[i].Ref;
1031
1032 dumpVarDefinitionName(i);
1033 llvm::errs() << " = ";
1034 if (Exp) Exp->dump();
1035 else {
1036 dumpVarDefinitionName(Ref);
1037 llvm::errs() << "\n";
1038 }
1039 }
1040 }
1041
1042 /// Dumps an ASCII representation of a Context to llvm::errs()
1043 void dumpContext(Context C) {
1044 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001045 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001046 D->printName(llvm::errs());
1047 const unsigned *i = C.lookup(D);
1048 llvm::errs() << " -> ";
1049 dumpVarDefinitionName(*i);
1050 llvm::errs() << "\n";
1051 }
1052 }
1053
1054 /// Builds the variable map.
1055 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1056 std::vector<CFGBlockInfo> &BlockInfo);
1057
1058protected:
1059 // Get the current context index
1060 unsigned getContextIndex() { return SavedContexts.size()-1; }
1061
1062 // Save the current context for later replay
1063 void saveContext(Stmt *S, Context C) {
1064 SavedContexts.push_back(std::make_pair(S,C));
1065 }
1066
1067 // Adds a new definition to the given context, and returns a new context.
1068 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001069 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001070 assert(!Ctx.contains(D));
1071 unsigned newID = VarDefinitions.size();
1072 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1073 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1074 return NewCtx;
1075 }
1076
1077 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001078 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001079 unsigned newID = VarDefinitions.size();
1080 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1081 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1082 return NewCtx;
1083 }
1084
1085 // Updates a definition only if that definition is already in the map.
1086 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001087 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001088 if (Ctx.contains(D)) {
1089 unsigned newID = VarDefinitions.size();
1090 Context NewCtx = ContextFactory.remove(Ctx, D);
1091 NewCtx = ContextFactory.add(NewCtx, D, newID);
1092 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1093 return NewCtx;
1094 }
1095 return Ctx;
1096 }
1097
1098 // Removes a definition from the context, but keeps the variable name
1099 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001100 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001101 Context NewCtx = Ctx;
1102 if (NewCtx.contains(D)) {
1103 NewCtx = ContextFactory.remove(NewCtx, D);
1104 NewCtx = ContextFactory.add(NewCtx, D, 0);
1105 }
1106 return NewCtx;
1107 }
1108
1109 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001110 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001111 Context NewCtx = Ctx;
1112 if (NewCtx.contains(D)) {
1113 NewCtx = ContextFactory.remove(NewCtx, D);
1114 }
1115 return NewCtx;
1116 }
1117
1118 Context intersectContexts(Context C1, Context C2);
1119 Context createReferenceContext(Context C);
1120 void intersectBackEdge(Context C1, Context C2);
1121
1122 friend class VarMapBuilder;
1123};
1124
1125
1126// This has to be defined after LocalVariableMap.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001127CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1128 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001129}
1130
1131
1132/// Visitor which builds a LocalVariableMap
1133class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1134public:
1135 LocalVariableMap* VMap;
1136 LocalVariableMap::Context Ctx;
1137
1138 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1139 : VMap(VM), Ctx(C) {}
1140
1141 void VisitDeclStmt(DeclStmt *S);
1142 void VisitBinaryOperator(BinaryOperator *BO);
1143};
1144
1145
1146// Add new local variables to the variable map
1147void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1148 bool modifiedCtx = false;
1149 DeclGroupRef DGrp = S->getDeclGroup();
1150 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1151 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1152 Expr *E = VD->getInit();
1153
1154 // Add local variables with trivial type to the variable map
1155 QualType T = VD->getType();
1156 if (T.isTrivialType(VD->getASTContext())) {
1157 Ctx = VMap->addDefinition(VD, E, Ctx);
1158 modifiedCtx = true;
1159 }
1160 }
1161 }
1162 if (modifiedCtx)
1163 VMap->saveContext(S, Ctx);
1164}
1165
1166// Update local variable definitions in variable map
1167void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1168 if (!BO->isAssignmentOp())
1169 return;
1170
1171 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1172
1173 // Update the variable map and current context.
1174 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1175 ValueDecl *VDec = DRE->getDecl();
1176 if (Ctx.lookup(VDec)) {
1177 if (BO->getOpcode() == BO_Assign)
1178 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1179 else
1180 // FIXME -- handle compound assignment operators
1181 Ctx = VMap->clearDefinition(VDec, Ctx);
1182 VMap->saveContext(BO, Ctx);
1183 }
1184 }
1185}
1186
1187
1188// Computes the intersection of two contexts. The intersection is the
1189// set of variables which have the same definition in both contexts;
1190// variables with different definitions are discarded.
1191LocalVariableMap::Context
1192LocalVariableMap::intersectContexts(Context C1, Context C2) {
1193 Context Result = C1;
1194 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001195 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001196 unsigned i1 = I.getData();
1197 const unsigned *i2 = C2.lookup(Dec);
1198 if (!i2) // variable doesn't exist on second path
1199 Result = removeDefinition(Dec, Result);
1200 else if (*i2 != i1) // variable exists, but has different definition
1201 Result = clearDefinition(Dec, Result);
1202 }
1203 return Result;
1204}
1205
1206// For every variable in C, create a new variable that refers to the
1207// definition in C. Return a new context that contains these new variables.
1208// (We use this for a naive implementation of SSA on loop back-edges.)
1209LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1210 Context Result = getEmptyContext();
1211 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001212 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001213 unsigned i = I.getData();
1214 Result = addReference(Dec, i, Result);
1215 }
1216 return Result;
1217}
1218
1219// This routine also takes the intersection of C1 and C2, but it does so by
1220// altering the VarDefinitions. C1 must be the result of an earlier call to
1221// createReferenceContext.
1222void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1223 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001224 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001225 unsigned i1 = I.getData();
1226 VarDefinition *VDef = &VarDefinitions[i1];
1227 assert(VDef->isReference());
1228
1229 const unsigned *i2 = C2.lookup(Dec);
1230 if (!i2 || (*i2 != i1))
1231 VDef->Ref = 0; // Mark this variable as undefined
1232 }
1233}
1234
1235
1236// Traverse the CFG in topological order, so all predecessors of a block
1237// (excluding back-edges) are visited before the block itself. At
1238// each point in the code, we calculate a Context, which holds the set of
1239// variable definitions which are visible at that point in execution.
1240// Visible variables are mapped to their definitions using an array that
1241// contains all definitions.
1242//
1243// At join points in the CFG, the set is computed as the intersection of
1244// the incoming sets along each edge, E.g.
1245//
1246// { Context | VarDefinitions }
1247// int x = 0; { x -> x1 | x1 = 0 }
1248// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1249// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1250// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1251// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1252//
1253// This is essentially a simpler and more naive version of the standard SSA
1254// algorithm. Those definitions that remain in the intersection are from blocks
1255// that strictly dominate the current block. We do not bother to insert proper
1256// phi nodes, because they are not used in our analysis; instead, wherever
1257// a phi node would be required, we simply remove that definition from the
1258// context (E.g. x above).
1259//
1260// The initial traversal does not capture back-edges, so those need to be
1261// handled on a separate pass. Whenever the first pass encounters an
1262// incoming back edge, it duplicates the context, creating new definitions
1263// that refer back to the originals. (These correspond to places where SSA
1264// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00001265// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001266// node was actually required.) E.g.
1267//
1268// { Context | VarDefinitions }
1269// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1270// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1271// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1272// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1273//
1274void LocalVariableMap::traverseCFG(CFG *CFGraph,
1275 PostOrderCFGView *SortedGraph,
1276 std::vector<CFGBlockInfo> &BlockInfo) {
1277 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1278
1279 CtxIndices.resize(CFGraph->getNumBlockIDs());
1280
1281 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1282 E = SortedGraph->end(); I!= E; ++I) {
1283 const CFGBlock *CurrBlock = *I;
1284 int CurrBlockID = CurrBlock->getBlockID();
1285 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1286
1287 VisitedBlocks.insert(CurrBlock);
1288
1289 // Calculate the entry context for the current block
1290 bool HasBackEdges = false;
1291 bool CtxInit = true;
1292 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1293 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1294 // if *PI -> CurrBlock is a back edge, so skip it
1295 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1296 HasBackEdges = true;
1297 continue;
1298 }
1299
1300 int PrevBlockID = (*PI)->getBlockID();
1301 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1302
1303 if (CtxInit) {
1304 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1305 CtxInit = false;
1306 }
1307 else {
1308 CurrBlockInfo->EntryContext =
1309 intersectContexts(CurrBlockInfo->EntryContext,
1310 PrevBlockInfo->ExitContext);
1311 }
1312 }
1313
1314 // Duplicate the context if we have back-edges, so we can call
1315 // intersectBackEdges later.
1316 if (HasBackEdges)
1317 CurrBlockInfo->EntryContext =
1318 createReferenceContext(CurrBlockInfo->EntryContext);
1319
1320 // Create a starting context index for the current block
1321 saveContext(0, CurrBlockInfo->EntryContext);
1322 CurrBlockInfo->EntryIndex = getContextIndex();
1323
1324 // Visit all the statements in the basic block.
1325 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1326 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1327 BE = CurrBlock->end(); BI != BE; ++BI) {
1328 switch (BI->getKind()) {
1329 case CFGElement::Statement: {
1330 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1331 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1332 break;
1333 }
1334 default:
1335 break;
1336 }
1337 }
1338 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1339
1340 // Mark variables on back edges as "unknown" if they've been changed.
1341 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1342 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1343 // if CurrBlock -> *SI is *not* a back edge
1344 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1345 continue;
1346
1347 CFGBlock *FirstLoopBlock = *SI;
1348 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1349 Context LoopEnd = CurrBlockInfo->ExitContext;
1350 intersectBackEdge(LoopBegin, LoopEnd);
1351 }
1352 }
1353
1354 // Put an extra entry at the end of the indexed context array
1355 unsigned exitID = CFGraph->getExit().getBlockID();
1356 saveContext(0, BlockInfo[exitID].ExitContext);
1357}
1358
Richard Smith2e515622012-02-03 04:45:26 +00001359/// Find the appropriate source locations to use when producing diagnostics for
1360/// each block in the CFG.
1361static void findBlockLocations(CFG *CFGraph,
1362 PostOrderCFGView *SortedGraph,
1363 std::vector<CFGBlockInfo> &BlockInfo) {
1364 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1365 E = SortedGraph->end(); I!= E; ++I) {
1366 const CFGBlock *CurrBlock = *I;
1367 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1368
1369 // Find the source location of the last statement in the block, if the
1370 // block is not empty.
1371 if (const Stmt *S = CurrBlock->getTerminator()) {
1372 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1373 } else {
1374 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1375 BE = CurrBlock->rend(); BI != BE; ++BI) {
1376 // FIXME: Handle other CFGElement kinds.
1377 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1378 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1379 break;
1380 }
1381 }
1382 }
1383
1384 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1385 // This block contains at least one statement. Find the source location
1386 // of the first statement in the block.
1387 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1388 BE = CurrBlock->end(); BI != BE; ++BI) {
1389 // FIXME: Handle other CFGElement kinds.
1390 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1391 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1392 break;
1393 }
1394 }
1395 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1396 CurrBlock != &CFGraph->getExit()) {
1397 // The block is empty, and has a single predecessor. Use its exit
1398 // location.
1399 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1400 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1401 }
1402 }
1403}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001404
1405/// \brief Class which implements the core thread safety analysis routines.
1406class ThreadSafetyAnalyzer {
1407 friend class BuildLockset;
1408
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001409 ThreadSafetyHandler &Handler;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001410 LocalVariableMap LocalVarMap;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001411 FactManager FactMan;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001412 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001413
1414public:
1415 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1416
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001417 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1418 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001419 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001420
1421 template <typename AttrType>
1422 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1423 const NamedDecl *D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001424
1425 template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001426 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1427 const NamedDecl *D,
1428 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1429 Expr *BrE, bool Neg);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001430
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001431 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1432 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001433
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001434 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1435 const CFGBlock* PredBlock,
1436 const CFGBlock *CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001437
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001438 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1439 SourceLocation JoinLoc,
1440 LockErrorKind LEK1, LockErrorKind LEK2,
1441 bool Modify=true);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001442
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001443 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1444 SourceLocation JoinLoc, LockErrorKind LEK1,
1445 bool Modify=true) {
1446 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001447 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001448
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001449 void runAnalysis(AnalysisDeclContext &AC);
1450};
1451
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001452
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001453/// \brief Add a new lock to the lockset, warning if the lock is already there.
1454/// \param Mutex -- the Mutex expression for the lock
1455/// \param LDat -- the LockData for the lock
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001456void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001457 const LockData &LDat) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001458 // FIXME: deal with acquired before/after annotations.
1459 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001460 if (Mutex.shouldIgnore())
1461 return;
1462
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001463 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001464 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001465 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001466 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001467 }
1468}
1469
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001470
1471/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenekad0fe032012-08-22 23:50:41 +00001472/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001473/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001474void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001475 const SExpr &Mutex,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001476 SourceLocation UnlockLoc,
1477 bool FullyRemove) {
DeLesley Hutchins4e4c1572012-08-31 21:57:32 +00001478 if (Mutex.shouldIgnore())
1479 return;
1480
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001481 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001482 if (!LDat) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001483 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001484 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001485 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001486
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001487 if (LDat->UnderlyingMutex.isValid()) {
1488 // This is scoped lockable object, which manages the real mutex.
1489 if (FullyRemove) {
1490 // We're destroying the managing object.
1491 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001492 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1493 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001494 } else {
1495 // We're releasing the underlying mutex, but not destroying the
1496 // managing object. Warn on dual release.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001497 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001498 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001499 UnlockLoc);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001500 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001501 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1502 return;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001503 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001504 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001505 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001506}
1507
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001508
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001509/// \brief Extract the list of mutexIDs from the attribute on an expression,
1510/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001511template <typename AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001512void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1513 Expr *Exp, const NamedDecl *D) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001514 typedef typename AttrType::args_iterator iterator_type;
1515
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001516 if (Attr->args_size() == 0) {
1517 // The mutex held is the "this" object.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001518 SExpr Mu(0, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001519 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001520 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001521 else
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001522 Mtxs.push_back_nodup(Mu);
1523 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001524 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001525
1526 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001527 SExpr Mu(*I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001528 if (!Mu.isValid())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001529 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001530 else
1531 Mtxs.push_back_nodup(Mu);
1532 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001533}
1534
1535
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001536/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1537/// trylock applies to the given edge, then push them onto Mtxs, discarding
1538/// any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001539template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001540void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1541 Expr *Exp, const NamedDecl *D,
1542 const CFGBlock *PredBlock,
1543 const CFGBlock *CurrBlock,
1544 Expr *BrE, bool Neg) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001545 // Find out which branch has the lock
1546 bool branch = 0;
1547 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1548 branch = BLE->getValue();
1549 }
1550 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1551 branch = ILE->getValue().getBoolValue();
1552 }
1553 int branchnum = branch ? 0 : 1;
1554 if (Neg) branchnum = !branchnum;
1555
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001556 // If we've taken the trylock branch, then add the lock
1557 int i = 0;
1558 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1559 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1560 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001561 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001562 }
1563 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001564}
1565
1566
DeLesley Hutchins13106112012-07-10 21:47:55 +00001567bool getStaticBooleanValue(Expr* E, bool& TCond) {
1568 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1569 TCond = false;
1570 return true;
1571 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1572 TCond = BLE->getValue();
1573 return true;
1574 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1575 TCond = ILE->getValue().getBoolValue();
1576 return true;
1577 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1578 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1579 }
1580 return false;
1581}
1582
1583
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001584// If Cond can be traced back to a function call, return the call expression.
1585// The negate variable should be called with false, and will be set to true
1586// if the function call is negated, e.g. if (!mu.tryLock(...))
1587const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1588 LocalVarContext C,
1589 bool &Negate) {
1590 if (!Cond)
1591 return 0;
1592
1593 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1594 return CallExp;
1595 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001596 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1597 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1598 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001599 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1600 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1601 }
DeLesley Hutchinsfd0f11c2012-09-05 20:01:16 +00001602 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1603 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1604 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001605 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1606 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1607 return getTrylockCallExpr(E, C, Negate);
1608 }
1609 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1610 if (UOP->getOpcode() == UO_LNot) {
1611 Negate = !Negate;
1612 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1613 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001614 return 0;
1615 }
1616 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1617 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1618 if (BOP->getOpcode() == BO_NE)
1619 Negate = !Negate;
1620
1621 bool TCond = false;
1622 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1623 if (!TCond) Negate = !Negate;
1624 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1625 }
1626 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1627 if (!TCond) Negate = !Negate;
1628 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1629 }
1630 return 0;
1631 }
1632 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001633 }
1634 // FIXME -- handle && and || as well.
DeLesley Hutchins13106112012-07-10 21:47:55 +00001635 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001636}
1637
1638
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001639/// \brief Find the lockset that holds on the edge between PredBlock
1640/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1641/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001642void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1643 const FactSet &ExitSet,
1644 const CFGBlock *PredBlock,
1645 const CFGBlock *CurrBlock) {
1646 Result = ExitSet;
1647
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001648 if (!PredBlock->getTerminatorCondition())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001649 return;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001650
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001651 bool Negate = false;
1652 const Stmt *Cond = PredBlock->getTerminatorCondition();
1653 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1654 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1655
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001656 CallExpr *Exp =
1657 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001658 if (!Exp)
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001659 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001660
1661 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1662 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001663 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001664
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001665
1666 MutexIDList ExclusiveLocksToAdd;
1667 MutexIDList SharedLocksToAdd;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001668
1669 // If the condition is a call to a Trylock function, then grab the attributes
1670 AttrVec &ArgAttrs = FunDecl->getAttrs();
1671 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1672 Attr *Attr = ArgAttrs[i];
1673 switch (Attr->getKind()) {
1674 case attr::ExclusiveTrylockFunction: {
1675 ExclusiveTrylockFunctionAttr *A =
1676 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001677 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1678 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001679 break;
1680 }
1681 case attr::SharedTrylockFunction: {
1682 SharedTrylockFunctionAttr *A =
1683 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchins60ff1982012-09-20 23:14:43 +00001684 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001685 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001686 break;
1687 }
1688 default:
1689 break;
1690 }
1691 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001692
1693 // Add and remove locks.
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001694 SourceLocation Loc = Exp->getExprLoc();
1695 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001696 addLock(Result, ExclusiveLocksToAdd[i],
1697 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001698 }
1699 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001700 addLock(Result, SharedLocksToAdd[i],
1701 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001702 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001703}
1704
1705
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001706/// \brief We use this class to visit different types of expressions in
1707/// CFGBlocks, and build up the lockset.
1708/// An expression may cause us to add or remove locks from the lockset, or else
1709/// output error messages related to missing locks.
1710/// FIXME: In future, we may be able to not inherit from a visitor.
1711class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001712 friend class ThreadSafetyAnalyzer;
1713
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001714 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001715 FactSet FSet;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001716 LocalVariableMap::Context LVarCtx;
1717 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001718
1719 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001720 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001721
1722 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1723 Expr *MutexExp, ProtectedOperationKind POK);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001724 void warnIfMutexHeld(const NamedDecl *D, Expr *Exp, Expr *MutexExp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001725
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001726 void checkAccess(Expr *Exp, AccessKind AK);
1727 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001728 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001729
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001730public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001731 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001732 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001733 Analyzer(Anlzr),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001734 FSet(Info.EntrySet),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001735 LVarCtx(Info.EntryContext),
1736 CtxIndex(Info.EntryIndex)
1737 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001738
1739 void VisitUnaryOperator(UnaryOperator *UO);
1740 void VisitBinaryOperator(BinaryOperator *BO);
1741 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001742 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001743 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001744 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001745};
1746
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001747
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001748/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1749const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1750 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1751 return DR->getDecl();
1752
1753 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1754 return ME->getMemberDecl();
1755
1756 return 0;
1757}
1758
1759/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001760/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001761void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1762 AccessKind AK, Expr *MutexExp,
1763 ProtectedOperationKind POK) {
1764 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001765
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001766 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001767 if (!Mutex.isValid()) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001768 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001769 return;
1770 } else if (Mutex.shouldIgnore()) {
1771 return;
1772 }
1773
1774 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins3f0ec522012-09-10 19:58:23 +00001775 bool NoError = true;
1776 if (!LDat) {
1777 // No exact match found. Look for a partial match.
1778 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1779 if (FEntry) {
1780 // Warn that there's no precise match.
1781 LDat = &FEntry->LDat;
1782 std::string PartMatchStr = FEntry->MutID.toString();
1783 StringRef PartMatchName(PartMatchStr);
1784 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1785 Exp->getExprLoc(), &PartMatchName);
1786 } else {
1787 // Warn that there's no match at all.
1788 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1789 Exp->getExprLoc());
1790 }
1791 NoError = false;
1792 }
1793 // Make sure the mutex we found is the right kind.
1794 if (NoError && LDat && !LDat->isAtLeast(LK))
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001795 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001796 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001797}
1798
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001799/// \brief Warn if the LSet contains the given lock.
1800void BuildLockset::warnIfMutexHeld(const NamedDecl *D, Expr* Exp,
1801 Expr *MutexExp) {
1802 SExpr Mutex(MutexExp, Exp, D);
1803 if (!Mutex.isValid()) {
1804 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1805 return;
1806 }
1807
1808 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001809 if (LDat) {
1810 std::string DeclName = D->getNameAsString();
1811 StringRef DeclNameSR (DeclName);
1812 Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(),
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001813 Exp->getExprLoc());
DeLesley Hutchins5b280f22012-09-19 19:18:29 +00001814 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001815}
1816
1817
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001818/// \brief This method identifies variable dereferences and checks pt_guarded_by
1819/// and pt_guarded_var annotations. Note that we only check these annotations
1820/// at the time a pointer is dereferenced.
1821/// FIXME: We need to check for other types of pointer dereferences
1822/// (e.g. [], ->) and deal with them here.
1823/// \param Exp An expression that has been read or written.
1824void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1825 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1826 if (!UO || UO->getOpcode() != clang::UO_Deref)
1827 return;
1828 Exp = UO->getSubExpr()->IgnoreParenCasts();
1829
1830 const ValueDecl *D = getValueDecl(Exp);
1831 if(!D || !D->hasAttrs())
1832 return;
1833
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001834 if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001835 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1836 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001837
1838 const AttrVec &ArgAttrs = D->getAttrs();
1839 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1840 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1841 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1842}
1843
1844/// \brief Checks guarded_by and guarded_var attributes.
1845/// Whenever we identify an access (read or write) of a DeclRefExpr or
1846/// MemberExpr, we need to check whether there are any guarded_by or
1847/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1848void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1849 const ValueDecl *D = getValueDecl(Exp);
1850 if(!D || !D->hasAttrs())
1851 return;
1852
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001853 if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001854 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1855 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001856
1857 const AttrVec &ArgAttrs = D->getAttrs();
1858 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1859 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1860 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1861}
1862
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001863/// \brief Process a function call, method call, constructor call,
1864/// or destructor call. This involves looking at the attributes on the
1865/// corresponding function/method/constructor/destructor, issuing warnings,
1866/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001867///
1868/// FIXME: For classes annotated with one of the guarded annotations, we need
1869/// to treat const method calls as reads and non-const method calls as writes,
1870/// and check that the appropriate locks are held. Non-const method calls with
1871/// the same signature as const method calls can be also treated as reads.
1872///
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001873void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1874 const AttrVec &ArgAttrs = D->getAttrs();
1875 MutexIDList ExclusiveLocksToAdd;
1876 MutexIDList SharedLocksToAdd;
1877 MutexIDList LocksToRemove;
1878
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001879 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001880 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1881 switch (At->getKind()) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001882 // When we encounter an exclusive lock function, we need to add the lock
1883 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001884 case attr::ExclusiveLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001885 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1886 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001887 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001888 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001889
1890 // When we encounter a shared lock function, we need to add the lock
1891 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001892 case attr::SharedLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001893 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1894 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001895 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001896 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001897
1898 // When we encounter an unlock function, we need to remove unlocked
1899 // mutexes from the lockset, and flag a warning if they are not there.
1900 case attr::UnlockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001901 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1902 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001903 break;
1904 }
1905
1906 case attr::ExclusiveLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001907 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001908
1909 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001910 I = A->args_begin(), E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001911 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1912 break;
1913 }
1914
1915 case attr::SharedLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001916 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001917
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001918 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1919 E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001920 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1921 break;
1922 }
1923
1924 case attr::LocksExcluded: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001925 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001926
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001927 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1928 E = A->args_end(); I != E; ++I) {
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00001929 warnIfMutexHeld(D, Exp, *I);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001930 }
1931 break;
1932 }
1933
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001934 // Ignore other (non thread-safety) attributes
1935 default:
1936 break;
1937 }
1938 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001939
1940 // Figure out if we're calling the constructor of scoped lockable class
1941 bool isScopedVar = false;
1942 if (VD) {
1943 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1944 const CXXRecordDecl* PD = CD->getParent();
1945 if (PD && PD->getAttr<ScopedLockableAttr>())
1946 isScopedVar = true;
1947 }
1948 }
1949
1950 // Add locks.
1951 SourceLocation Loc = Exp->getExprLoc();
1952 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001953 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1954 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001955 }
1956 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001957 Analyzer->addLock(FSet, SharedLocksToAdd[i],
1958 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001959 }
1960
1961 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1962 // FIXME -- this doesn't work if we acquire multiple locks.
1963 if (isScopedVar) {
1964 SourceLocation MLoc = VD->getLocation();
1965 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00001966 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001967
1968 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001969 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
1970 ExclusiveLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001971 }
1972 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001973 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
1974 SharedLocksToAdd[i]));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001975 }
1976 }
1977
1978 // Remove locks.
1979 // FIXME -- should only fully remove if the attribute refers to 'this'.
1980 bool Dtor = isa<CXXDestructorDecl>(D);
1981 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00001982 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001983 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001984}
1985
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001986
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001987/// \brief For unary operations which read and write a variable, we need to
1988/// check whether we hold any required mutexes. Reads are checked in
1989/// VisitCastExpr.
1990void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1991 switch (UO->getOpcode()) {
1992 case clang::UO_PostDec:
1993 case clang::UO_PostInc:
1994 case clang::UO_PreDec:
1995 case clang::UO_PreInc: {
1996 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1997 checkAccess(SubExp, AK_Written);
1998 checkDereference(SubExp, AK_Written);
1999 break;
2000 }
2001 default:
2002 break;
2003 }
2004}
2005
2006/// For binary operations which assign to a variable (writes), we need to check
2007/// whether we hold any required mutexes.
2008/// FIXME: Deal with non-primitive types.
2009void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2010 if (!BO->isAssignmentOp())
2011 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002012
2013 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002014 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002015
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00002016 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
2017 checkAccess(LHSExp, AK_Written);
2018 checkDereference(LHSExp, AK_Written);
2019}
2020
2021/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2022/// need to ensure we hold any required mutexes.
2023/// FIXME: Deal with non-primitive types.
2024void BuildLockset::VisitCastExpr(CastExpr *CE) {
2025 if (CE->getCastKind() != CK_LValueToRValue)
2026 return;
2027 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
2028 checkAccess(SubExp, AK_Read);
2029 checkDereference(SubExp, AK_Read);
2030}
2031
2032
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00002033void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00002034 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2035 if(!D || !D->hasAttrs())
2036 return;
2037 handleCall(Exp, D);
2038}
2039
2040void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00002041 // FIXME -- only handles constructors in DeclStmt below.
2042}
2043
2044void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002045 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002046 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002047
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00002048 DeclGroupRef DGrp = S->getDeclGroup();
2049 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2050 Decl *D = *I;
2051 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2052 Expr *E = VD->getInit();
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +00002053 // handle constructors that involve temporaries
2054 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2055 E = EWC->getSubExpr();
2056
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00002057 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2058 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2059 if (!CtorD || !CtorD->hasAttrs())
2060 return;
2061 handleCall(CE, CtorD, VD);
2062 }
2063 }
2064 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00002065}
2066
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002067
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002068
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00002069/// \brief Compute the intersection of two locksets and issue warnings for any
2070/// locks in the symmetric difference.
2071///
2072/// This function is used at a merge point in the CFG when comparing the lockset
2073/// of each branch being merged. For example, given the following sequence:
2074/// A; if () then B; else C; D; we need to check that the lockset after B and C
2075/// are the same. In the event of a difference, we use the intersection of these
2076/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002077///
Ted Kremenekad0fe032012-08-22 23:50:41 +00002078/// \param FSet1 The first lockset.
2079/// \param FSet2 The second lockset.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002080/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002081/// \param LEK1 The error message to report if a mutex is missing from LSet1
2082/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002083void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2084 const FactSet &FSet2,
2085 SourceLocation JoinLoc,
2086 LockErrorKind LEK1,
2087 LockErrorKind LEK2,
2088 bool Modify) {
2089 FactSet FSet1Orig = FSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002090
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002091 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2092 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002093 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002094 const LockData &LDat2 = FactMan[*I].LDat;
2095
2096 if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002097 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002098 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002099 LDat2.AcquireLoc,
2100 LDat1->AcquireLoc);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002101 if (Modify && LDat1->LKind != LK_Exclusive) {
2102 FSet1.removeLock(FactMan, FSet2Mutex);
2103 FSet1.addLock(FactMan, FSet2Mutex, LDat2);
2104 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002105 }
2106 } else {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002107 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002108 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002109 // If this is a scoped lock that manages another mutex, and if the
2110 // underlying mutex is still held, then warn about the underlying
2111 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002112 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002113 LDat2.AcquireLoc,
2114 JoinLoc, LEK1);
2115 }
2116 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00002117 else if (!LDat2.Managed && !FSet2Mutex.isUniversal())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002118 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002119 LDat2.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002120 JoinLoc, LEK1);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002121 }
2122 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002123
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002124 for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
2125 I != E; ++I) {
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002126 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002127 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00002128
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002129 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002130 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002131 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002132 // If this is a scoped lock that manages another mutex, and if the
2133 // underlying mutex is still held, then warn about the underlying
2134 // mutex.
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002135 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002136 LDat1.AcquireLoc,
2137 JoinLoc, LEK1);
2138 }
2139 }
DeLesley Hutchins0b4db3e2012-09-07 17:34:53 +00002140 else if (!LDat1.Managed && !FSet1Mutex.isUniversal())
DeLesley Hutchinsa74b7152012-08-10 20:19:55 +00002141 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00002142 LDat1.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002143 JoinLoc, LEK2);
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002144 if (Modify)
2145 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002146 }
2147 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002148}
2149
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002150
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002151
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002152/// \brief Check a function's CFG for thread-safety violations.
2153///
2154/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2155/// at the end of each block, and issue warnings for thread safety violations.
2156/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002157void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002158 CFG *CFGraph = AC.getCFG();
2159 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002160 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2161
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002162 // AC.dumpCFG(true);
2163
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00002164 if (!D)
2165 return; // Ignore anonymous functions for now.
2166 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2167 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002168 // FIXME: Do something a bit more intelligent inside constructor and
2169 // destructor code. Constructors and destructors must assume unique access
2170 // to 'this', so checks on member variable access is disabled, but we should
2171 // still enable checks on other objects.
2172 if (isa<CXXConstructorDecl>(D))
2173 return; // Don't check inside constructors.
2174 if (isa<CXXDestructorDecl>(D))
2175 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002176
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002177 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002178 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002179
2180 // We need to explore the CFG via a "topological" ordering.
2181 // That way, we will be guaranteed to have information about required
2182 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00002183 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2184 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002185
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002186 // Compute SSA names for local variables
2187 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2188
Richard Smith2e515622012-02-03 04:45:26 +00002189 // Fill in source locations for all CFGBlocks.
2190 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2191
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002192 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002193 // to initial lockset. Also turn off checking for lock and unlock functions.
2194 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00002195 if (!SortedGraph->empty() && D->hasAttrs()) {
2196 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002197 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002198 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002199
2200 MutexIDList ExclusiveLocksToAdd;
2201 MutexIDList SharedLocksToAdd;
2202
2203 SourceLocation Loc = D->getLocation();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002204 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002205 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002206 Loc = Attr->getLocation();
2207 if (ExclusiveLocksRequiredAttr *A
2208 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2209 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2210 } else if (SharedLocksRequiredAttr *A
2211 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2212 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00002213 } else if (isa<UnlockFunctionAttr>(Attr)) {
2214 // Don't try to check unlock functions for now
2215 return;
2216 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
2217 // Don't try to check lock functions for now
2218 return;
2219 } else if (isa<SharedLockFunctionAttr>(Attr)) {
2220 // Don't try to check lock functions for now
2221 return;
DeLesley Hutchins76f0a6e2012-07-02 21:59:24 +00002222 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2223 // Don't try to check trylock functions for now
2224 return;
2225 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2226 // Don't try to check trylock functions for now
2227 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002228 }
2229 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002230
2231 // FIXME -- Loc can be wrong here.
2232 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002233 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2234 LockData(Loc, LK_Exclusive));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002235 }
2236 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002237 addLock(InitialLockset, SharedLocksToAdd[i],
2238 LockData(Loc, LK_Shared));
DeLesley Hutchins5381c052012-07-05 21:16:29 +00002239 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +00002240 }
2241
Ted Kremenek439ed162011-10-22 02:14:27 +00002242 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2243 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002244 const CFGBlock *CurrBlock = *I;
2245 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002246 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002247
2248 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002249 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002250
2251 // Iterate through the predecessor blocks and warn if the lockset for all
2252 // predecessors is not the same. We take the entry lockset of the current
2253 // block to be the intersection of all previous locksets.
2254 // FIXME: By keeping the intersection, we may output more errors in future
2255 // for a lock which is not in the intersection, but was in the union. We
2256 // may want to also keep the union in future. As an example, let's say
2257 // the intersection contains Mutex L, and the union contains L and M.
2258 // Later we unlock M. At this point, we would output an error because we
2259 // never locked M; although the real error is probably that we forgot to
2260 // lock M on all code paths. Conversely, let's say that later we lock M.
2261 // In this case, we should compare against the intersection instead of the
2262 // union because the real error is probably that we forgot to unlock M on
2263 // all code paths.
2264 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00002265 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002266 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2267 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2268
2269 // if *PI -> CurrBlock is a back edge
2270 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2271 continue;
2272
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00002273 // Ignore edges from blocks that can't return.
2274 if ((*PI)->hasNoReturnElement())
2275 continue;
2276
Richard Smithaacde712012-02-03 03:30:07 +00002277 // If the previous block ended in a 'continue' or 'break' statement, then
2278 // a difference in locksets is probably due to a bug in that block, rather
2279 // than in some other predecessor. In that case, keep the other
2280 // predecessor's lockset.
2281 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2282 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2283 SpecialBlocks.push_back(*PI);
2284 continue;
2285 }
2286 }
2287
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002288 int PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002289 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002290 FactSet PrevLockset;
2291 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002292
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002293 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002294 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002295 LocksetInitialized = true;
2296 } else {
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002297 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2298 CurrBlockInfo->EntryLoc,
2299 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002300 }
2301 }
2302
Richard Smithaacde712012-02-03 03:30:07 +00002303 // Process continue and break blocks. Assume that the lockset for the
2304 // resulting block is unaffected by any discrepancies in them.
2305 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2306 SpecialI < SpecialN; ++SpecialI) {
2307 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2308 int PrevBlockID = PrevBlock->getBlockID();
2309 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2310
2311 if (!LocksetInitialized) {
2312 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2313 LocksetInitialized = true;
2314 } else {
2315 // Determine whether this edge is a loop terminator for diagnostic
2316 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2317 // it might also be part of a switch. Also, a subsequent destructor
2318 // might add to the lockset, in which case the real issue might be a
2319 // double lock on the other path.
2320 const Stmt *Terminator = PrevBlock->getTerminator();
2321 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2322
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002323 FactSet PrevLockset;
2324 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2325 PrevBlock, CurrBlock);
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002326
Richard Smithaacde712012-02-03 03:30:07 +00002327 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002328 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2329 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00002330 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002331 : LEK_LockedSomePredecessors,
2332 false);
Richard Smithaacde712012-02-03 03:30:07 +00002333 }
2334 }
2335
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00002336 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2337
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00002338 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002339 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2340 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002341 switch (BI->getKind()) {
2342 case CFGElement::Statement: {
2343 const CFGStmt *CS = cast<CFGStmt>(&*BI);
2344 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
2345 break;
2346 }
2347 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2348 case CFGElement::AutomaticObjectDtor: {
2349 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
2350 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
2351 AD->getDestructorDecl(AC.getASTContext()));
2352 if (!DD->hasAttrs())
2353 break;
2354
2355 // Create a dummy expression,
2356 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00002357 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00002358 AD->getTriggerStmt()->getLocEnd());
2359 LocksetBuilder.handleCall(&DRE, DD);
2360 break;
2361 }
2362 default:
2363 break;
2364 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002365 }
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002366 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002367
2368 // For every back edge from CurrBlock (the end of the loop) to another block
2369 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2370 // the one held at the beginning of FirstLoopBlock. We can look up the
2371 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2372 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2373 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2374
2375 // if CurrBlock -> *SI is *not* a back edge
2376 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2377 continue;
2378
2379 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002380 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2381 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2382 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2383 PreLoop->EntryLoc,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002384 LEK_LockedSomeLoopIterations,
2385 false);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002386 }
2387 }
2388
DeLesley Hutchins2a237e02012-09-19 19:49:40 +00002389
2390 // Check to make sure that the exit block is reachable
2391 bool ExitUnreachable = true;
2392 for (CFGBlock::const_pred_iterator PI = CFGraph->getExit().pred_begin(),
2393 PE = CFGraph->getExit().pred_end(); PI != PE; ++PI) {
2394 if (!(*PI)->hasNoReturnElement()) {
2395 ExitUnreachable = false;
2396 break;
2397 }
2398 }
2399 // Skip the final check if the exit block is unreachable.
2400 if (ExitUnreachable)
2401 return;
2402
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002403 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2404 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00002405
2406 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00002407 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
2408 Final->ExitLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00002409 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsa1fa4712012-08-10 18:39:05 +00002410 LEK_NotLockedAtEndOfFunction,
2411 false);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002412}
2413
2414} // end anonymous namespace
2415
2416
2417namespace clang {
2418namespace thread_safety {
2419
2420/// \brief Check a function's CFG for thread-safety violations.
2421///
2422/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2423/// at the end of each block, and issue warnings for thread safety violations.
2424/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00002425void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002426 ThreadSafetyHandler &Handler) {
2427 ThreadSafetyAnalyzer Analyzer(Handler);
2428 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002429}
2430
2431/// \brief Helper function that returns a LockKind required for the given level
2432/// of access.
2433LockKind getLockKindFromAccessKind(AccessKind AK) {
2434 switch (AK) {
2435 case AK_Read :
2436 return LK_Shared;
2437 case AK_Written :
2438 return LK_Exclusive;
2439 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00002440 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002441}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00002442
Caitlin Sadowski402aa062011-09-09 16:11:56 +00002443}} // end namespace clang::thread_safety