blob: 51f5e030691966fcc9210cbdc9d9e92b861e7742 [file] [log] [blame]
Caitlin Sadowski33208342011-09-09 16:11:56 +00001//===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
Aaron Ballmanfcd5b7e2013-06-26 19:17:19 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#thread-safety-annotation-checking
14// for more information.
Caitlin Sadowski33208342011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000020#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Analysis/Analyses/PostOrderCFGView.h"
25#include "clang/Analysis/AnalysisContext.h"
26#include "clang/Analysis/CFG.h"
27#include "clang/Analysis/CFGStmtMap.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000028#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000029#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/SourceManager.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000031#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/ImmutableMap.h"
34#include "llvm/ADT/PostOrderIterator.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000037#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000038#include <algorithm>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000039#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000040#include <vector>
41
42using namespace clang;
43using namespace thread_safety;
44
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000045// Key method definition
46ThreadSafetyHandler::~ThreadSafetyHandler() {}
47
Caitlin Sadowski33208342011-09-09 16:11:56 +000048namespace {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +000049
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000050/// SExpr implements a simple expression language that is used to store,
51/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
52/// does not capture surface syntax, and it does not distinguish between
53/// C++ concepts, like pointers and references, that have no real semantic
54/// differences. This simplicity allows SExprs to be meaningfully compared,
55/// e.g.
56/// (x) = x
57/// (*this).foo = this->foo
58/// *&a = a
Caitlin Sadowski33208342011-09-09 16:11:56 +000059///
60/// Thread-safety analysis works by comparing lock expressions. Within the
61/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
62/// a particular mutex object at run-time. Subsequent occurrences of the same
63/// expression (where "same" means syntactic equality) will refer to the same
64/// run-time object if three conditions hold:
65/// (1) Local variables in the expression, such as "x" have not changed.
66/// (2) Values on the heap that affect the expression have not changed.
67/// (3) The expression involves only pure function calls.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +000068///
Caitlin Sadowski33208342011-09-09 16:11:56 +000069/// The current implementation assumes, but does not verify, that multiple uses
70/// of the same lock expression satisfies these criteria.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000071class SExpr {
72private:
73 enum ExprOp {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +000074 EOP_Nop, ///< No-op
75 EOP_Wildcard, ///< Matches anything.
76 EOP_Universal, ///< Universal lock.
77 EOP_This, ///< This keyword.
78 EOP_NVar, ///< Named variable.
79 EOP_LVar, ///< Local variable.
80 EOP_Dot, ///< Field access
81 EOP_Call, ///< Function call
82 EOP_MCall, ///< Method call
83 EOP_Index, ///< Array index
84 EOP_Unary, ///< Unary operation
85 EOP_Binary, ///< Binary operation
86 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000087 };
88
89
90 class SExprNode {
91 private:
Ted Kremenek78094ca2012-08-22 23:50:41 +000092 unsigned char Op; ///< Opcode of the root node
93 unsigned char Flags; ///< Additional opcode-specific data
94 unsigned short Sz; ///< Number of child nodes
95 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000096
97 public:
98 SExprNode(ExprOp O, unsigned F, const void* D)
99 : Op(static_cast<unsigned char>(O)),
100 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
101 { }
102
103 unsigned size() const { return Sz; }
104 void setSize(unsigned S) { Sz = S; }
105
106 ExprOp kind() const { return static_cast<ExprOp>(Op); }
107
108 const NamedDecl* getNamedDecl() const {
109 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
110 return reinterpret_cast<const NamedDecl*>(Data);
111 }
112
113 const NamedDecl* getFunctionDecl() const {
114 assert(Op == EOP_Call || Op == EOP_MCall);
115 return reinterpret_cast<const NamedDecl*>(Data);
116 }
117
118 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
119 void setArrow(bool A) { Flags = A ? 1 : 0; }
120
121 unsigned arity() const {
122 switch (Op) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000123 case EOP_Nop: return 0;
124 case EOP_Wildcard: return 0;
125 case EOP_Universal: return 0;
126 case EOP_NVar: return 0;
127 case EOP_LVar: return 0;
128 case EOP_This: return 0;
129 case EOP_Dot: return 1;
130 case EOP_Call: return Flags+1; // First arg is function.
131 case EOP_MCall: return Flags+1; // First arg is implicit obj.
132 case EOP_Index: return 2;
133 case EOP_Unary: return 1;
134 case EOP_Binary: return 2;
135 case EOP_Unknown: return Flags;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000136 }
137 return 0;
138 }
139
140 bool operator==(const SExprNode& Other) const {
141 // Ignore flags and size -- they don't matter.
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000142 return (Op == Other.Op &&
143 Data == Other.Data);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000144 }
145
146 bool operator!=(const SExprNode& Other) const {
147 return !(*this == Other);
148 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000149
150 bool matches(const SExprNode& Other) const {
151 return (*this == Other) ||
152 (Op == EOP_Wildcard) ||
153 (Other.Op == EOP_Wildcard);
154 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000155 };
156
Caitlin Sadowski33208342011-09-09 16:11:56 +0000157
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000158 /// \brief Encapsulates the lexical context of a function call. The lexical
159 /// context includes the arguments to the call, including the implicit object
160 /// argument. When an attribute containing a mutex expression is attached to
161 /// a method, the expression may refer to formal parameters of the method.
162 /// Actual arguments must be substituted for formal parameters to derive
163 /// the appropriate mutex expression in the lexical context where the function
164 /// is called. PrevCtx holds the context in which the arguments themselves
165 /// should be evaluated; multiple calling contexts can be chained together
166 /// by the lock_returned attribute.
167 struct CallingContext {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000168 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
169 const Expr* SelfArg; // Implicit object argument -- e.g. 'this'
170 bool SelfArrow; // is Self referred to with -> or .?
171 unsigned NumArgs; // Number of funArgs
172 const Expr* const* FunArgs; // Function arguments
173 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000174
Aaron Ballman69bb5922014-03-06 19:37:24 +0000175 CallingContext(const NamedDecl *D)
176 : AttrDecl(D), SelfArg(0), SelfArrow(false), NumArgs(0), FunArgs(0),
177 PrevCtx(0) {}
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000178 };
179
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000180 typedef SmallVector<SExprNode, 4> NodeVector;
181
182private:
183 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
184 // the list to be traversed as a tree.
185 NodeVector NodeVec;
186
187private:
Aaron Ballman19842c42014-03-06 19:25:11 +0000188 unsigned make(ExprOp O, unsigned F = 0, const void *D = 0) {
189 NodeVec.push_back(SExprNode(O, F, D));
190 return NodeVec.size() - 1;
191 }
192
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000193 unsigned makeNop() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000194 return make(EOP_Nop);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000195 }
196
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000197 unsigned makeWildcard() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000198 return make(EOP_Wildcard);
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000199 }
200
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000201 unsigned makeUniversal() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000202 return make(EOP_Universal);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000203 }
204
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000205 unsigned makeNamedVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000206 return make(EOP_NVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000207 }
208
209 unsigned makeLocalVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000210 return make(EOP_LVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000211 }
212
213 unsigned makeThis() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000214 return make(EOP_This);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000215 }
216
217 unsigned makeDot(const NamedDecl *D, bool Arrow) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000218 return make(EOP_Dot, Arrow ? 1 : 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000219 }
220
221 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000222 return make(EOP_Call, NumArgs, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000223 }
224
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000225 // Grab the very first declaration of virtual method D
226 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
227 while (true) {
228 D = D->getCanonicalDecl();
229 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
230 E = D->end_overridden_methods();
231 if (I == E)
232 return D; // Method does not override anything
233 D = *I; // FIXME: this does not work with multiple inheritance.
234 }
235 return 0;
236 }
237
238 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000239 return make(EOP_MCall, NumArgs, getFirstVirtualDecl(D));
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000240 }
241
242 unsigned makeIndex() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000243 return make(EOP_Index);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000244 }
245
246 unsigned makeUnary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000247 return make(EOP_Unary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000248 }
249
250 unsigned makeBinary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000251 return make(EOP_Binary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000252 }
253
254 unsigned makeUnknown(unsigned Arity) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000255 return make(EOP_Unknown, Arity);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000256 }
257
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000258 inline bool isCalleeArrow(const Expr *E) {
259 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
260 return ME ? ME->isArrow() : false;
261 }
262
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000263 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000264 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000265 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000266 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000267 ///
268 /// NDeref returns the number of Derefence and AddressOf operations
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000269 /// preceding the Expr; this is used to decide whether to pretty-print
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000270 /// SExprs with . or ->.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000271 unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx,
272 int* NDeref = 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000273 if (!Exp)
274 return 0;
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000275
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000276 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
277 const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
278 const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000279 if (PV) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000280 const FunctionDecl *FD =
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000281 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
282 unsigned i = PV->getFunctionScopeIndex();
283
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000284 if (CallCtx && CallCtx->FunArgs &&
285 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000286 // Substitute call arguments for references to function parameters
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000287 assert(i < CallCtx->NumArgs);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000288 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000289 }
290 // Map the param back to the param of the original function declaration.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000291 makeNamedVar(FD->getParamDecl(i));
292 return 1;
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000293 }
294 // Not a function parameter -- just store the reference.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000295 makeNamedVar(ND);
296 return 1;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000297 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000298 // Substitute parent for 'this'
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000299 if (CallCtx && CallCtx->SelfArg) {
300 if (!CallCtx->SelfArrow && NDeref)
301 // 'this' is a pointer, but self is not, so need to take address.
302 --(*NDeref);
303 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
304 }
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000305 else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000306 makeThis();
307 return 1;
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000308 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000309 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
310 const NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000311 int ImplicitDeref = ME->isArrow() ? 1 : 0;
312 unsigned Root = makeDot(ND, false);
313 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
314 NodeVec[Root].setArrow(ImplicitDeref > 0);
315 NodeVec[Root].setSize(Sz + 1);
316 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000317 } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000318 // When calling a function with a lock_returned attribute, replace
319 // the function call with the expression in lock_returned.
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000320 const CXXMethodDecl *MD = CMCE->getMethodDecl()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000321 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000322 CallingContext LRCallCtx(CMCE->getMethodDecl());
323 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000324 LRCallCtx.SelfArrow = isCalleeArrow(CMCE->getCallee());
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000325 LRCallCtx.NumArgs = CMCE->getNumArgs();
326 LRCallCtx.FunArgs = CMCE->getArgs();
327 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000328 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000329 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000330 // Hack to treat smart pointers and iterators as pointers;
331 // ignore any method named get().
332 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
333 CMCE->getNumArgs() == 0) {
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000334 if (NDeref && isCalleeArrow(CMCE->getCallee()))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000335 ++(*NDeref);
336 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000337 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000338 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000339 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000340 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000341 const Expr* const* CallArgs = CMCE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000342 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000343 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000344 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000345 NodeVec[Root].setSize(Sz + 1);
346 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000347 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000348 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000349 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000350 CallingContext LRCallCtx(CE->getDirectCallee());
351 LRCallCtx.NumArgs = CE->getNumArgs();
352 LRCallCtx.FunArgs = CE->getArgs();
353 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000354 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000355 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000356 // Treat smart pointers and iterators as pointers;
357 // ignore the * and -> operators.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000358 if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000359 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000360 if (k == OO_Star) {
361 if (NDeref) ++(*NDeref);
362 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
363 }
364 else if (k == OO_Arrow) {
365 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000366 }
367 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000368 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000369 unsigned Root = makeCall(NumCallArgs, 0);
370 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000371 const Expr* const* CallArgs = CE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000372 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000373 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000374 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000375 NodeVec[Root].setSize(Sz+1);
376 return Sz+1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000377 } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000378 unsigned Root = makeBinary();
379 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
380 Sz += buildSExpr(BOE->getRHS(), CallCtx);
381 NodeVec[Root].setSize(Sz);
382 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000383 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000384 // Ignore & and * operators -- they're no-ops.
385 // However, we try to figure out whether the expression is a pointer,
386 // so we can use . and -> appropriately in error messages.
387 if (UOE->getOpcode() == UO_Deref) {
388 if (NDeref) ++(*NDeref);
389 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
390 }
391 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000392 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
393 if (DRE->getDecl()->isCXXInstanceMember()) {
394 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
395 // We interpret this syntax specially, as a wildcard.
396 unsigned Root = makeDot(DRE->getDecl(), false);
397 makeWildcard();
398 NodeVec[Root].setSize(2);
399 return 2;
400 }
401 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000402 if (NDeref) --(*NDeref);
403 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
404 }
405 unsigned Root = makeUnary();
406 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
407 NodeVec[Root].setSize(Sz);
408 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000409 } else if (const ArraySubscriptExpr *ASE =
410 dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000411 unsigned Root = makeIndex();
412 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
413 Sz += buildSExpr(ASE->getIdx(), CallCtx);
414 NodeVec[Root].setSize(Sz);
415 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000416 } else if (const AbstractConditionalOperator *CE =
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000417 dyn_cast<AbstractConditionalOperator>(Exp)) {
418 unsigned Root = makeUnknown(3);
419 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
420 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
421 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
422 NodeVec[Root].setSize(Sz);
423 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000424 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000425 unsigned Root = makeUnknown(3);
426 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
427 Sz += buildSExpr(CE->getLHS(), CallCtx);
428 Sz += buildSExpr(CE->getRHS(), CallCtx);
429 NodeVec[Root].setSize(Sz);
430 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000431 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000432 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000433 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000434 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000435 } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000436 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000437 } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000438 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000439 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins0c1da202012-07-03 18:25:56 +0000440 isa<CXXNullPtrLiteralExpr>(Exp) ||
441 isa<GNUNullExpr>(Exp) ||
442 isa<CXXBoolLiteralExpr>(Exp) ||
443 isa<FloatingLiteral>(Exp) ||
444 isa<ImaginaryLiteral>(Exp) ||
445 isa<IntegerLiteral>(Exp) ||
446 isa<StringLiteral>(Exp) ||
447 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000448 makeNop();
449 return 1; // FIXME: Ignore literals for now
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000450 } else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000451 makeNop();
452 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000453 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000454 }
455
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000456 /// \brief Construct a SExpr from an expression.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000457 /// \param MutexExp The original mutex expression within an attribute
458 /// \param DeclExp An expression involving the Decl on which the attribute
459 /// occurs.
460 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000461 void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp,
462 const NamedDecl *D, VarDecl *SelfDecl = 0) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000463 CallingContext CallCtx(D);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000464
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000465 if (MutexExp) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000466 if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000467 if (SLit->getString() == StringRef("*"))
468 // The "*" expr is a universal lock, which essentially turns off
469 // checks until it is removed from the lockset.
470 makeUniversal();
471 else
472 // Ignore other string literals for now.
473 makeNop();
474 return;
475 }
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000476 }
477
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000478 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000479 if (DeclExp == 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000480 buildSExpr(MutexExp, 0);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000481 return;
482 }
483
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000484 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000485 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000486 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000487 CallCtx.SelfArg = ME->getBase();
488 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000489 } else if (const CXXMemberCallExpr *CE =
490 dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000491 CallCtx.SelfArg = CE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000492 CallCtx.SelfArrow = isCalleeArrow(CE->getCallee());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000493 CallCtx.NumArgs = CE->getNumArgs();
494 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000495 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000496 CallCtx.NumArgs = CE->getNumArgs();
497 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000498 } else if (const CXXConstructExpr *CE =
499 dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000500 CallCtx.SelfArg = 0; // Will be set below
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000501 CallCtx.NumArgs = CE->getNumArgs();
502 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +0000503 } else if (D && isa<CXXDestructorDecl>(D)) {
504 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000505 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000506 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000507
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000508 // Hack to handle constructors, where self cannot be recovered from
509 // the expression.
510 if (SelfDecl && !CallCtx.SelfArg) {
511 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
512 SelfDecl->getLocation());
513 CallCtx.SelfArg = &SelfDRE;
514
515 // If the attribute has no arguments, then assume the argument is "this".
516 if (MutexExp == 0)
517 buildSExpr(CallCtx.SelfArg, 0);
518 else // For most attributes.
519 buildSExpr(MutexExp, &CallCtx);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000520 return;
521 }
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000522
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000523 // If the attribute has no arguments, then assume the argument is "this".
524 if (MutexExp == 0)
525 buildSExpr(CallCtx.SelfArg, 0);
526 else // For most attributes.
527 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski33208342011-09-09 16:11:56 +0000528 }
529
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000530 /// \brief Get index of next sibling of node i.
531 unsigned getNextSibling(unsigned i) const {
532 return i + NodeVec[i].size();
533 }
534
Caitlin Sadowski33208342011-09-09 16:11:56 +0000535public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000536 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000537
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000538 /// \param MutexExp The original mutex expression within an attribute
539 /// \param DeclExp An expression involving the Decl on which the attribute
540 /// occurs.
541 /// \param D The declaration to which the lock/unlock attribute is attached.
542 /// Caller must check isValid() after construction.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000543 SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000544 VarDecl *SelfDecl=0) {
545 buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000546 }
547
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000548 /// Return true if this is a valid decl sequence.
549 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000550 bool isValid() const {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000551 return !NodeVec.empty();
Caitlin Sadowski33208342011-09-09 16:11:56 +0000552 }
553
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000554 bool shouldIgnore() const {
555 // Nop is a mutex that we have decided to deliberately ignore.
556 assert(NodeVec.size() > 0 && "Invalid Mutex");
557 return NodeVec[0].kind() == EOP_Nop;
558 }
559
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000560 bool isUniversal() const {
561 assert(NodeVec.size() > 0 && "Invalid Mutex");
562 return NodeVec[0].kind() == EOP_Universal;
563 }
564
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000565 /// Issue a warning about an invalid lock expression
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000566 static void warnInvalidLock(ThreadSafetyHandler &Handler,
567 const Expr *MutexExp,
568 const Expr *DeclExp, const NamedDecl* D) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000569 SourceLocation Loc;
570 if (DeclExp)
571 Loc = DeclExp->getExprLoc();
572
573 // FIXME: add a note about the attribute location in MutexExp or D
574 if (Loc.isValid())
575 Handler.handleInvalidLockExp(Loc);
576 }
577
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000578 bool operator==(const SExpr &other) const {
579 return NodeVec == other.NodeVec;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000580 }
581
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000582 bool operator!=(const SExpr &other) const {
Caitlin Sadowski33208342011-09-09 16:11:56 +0000583 return !(*this == other);
584 }
585
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000586 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
587 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchins138568b2012-09-11 23:04:49 +0000588 unsigned ni = NodeVec[i].arity();
589 unsigned nj = Other.NodeVec[j].arity();
590 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000591 bool Result = true;
592 unsigned ci = i+1; // first child of i
593 unsigned cj = j+1; // first child of j
594 for (unsigned k = 0; k < n;
595 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
596 Result = Result && matches(Other, ci, cj);
597 }
598 return Result;
599 }
600 return false;
601 }
602
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000603 // A partial match between a.mu and b.mu returns true a and b have the same
604 // type (and thus mu refers to the same mutex declaration), regardless of
605 // whether a and b are different objects or not.
606 bool partiallyMatches(const SExpr &Other) const {
607 if (NodeVec[0].kind() == EOP_Dot)
608 return NodeVec[0].matches(Other.NodeVec[0]);
609 return false;
610 }
611
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000612 /// \brief Pretty print a lock expression for use in error messages.
613 std::string toString(unsigned i = 0) const {
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000614 assert(isValid());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000615 if (i >= NodeVec.size())
616 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000617
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000618 const SExprNode* N = &NodeVec[i];
619 switch (N->kind()) {
620 case EOP_Nop:
621 return "_";
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000622 case EOP_Wildcard:
623 return "(?)";
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000624 case EOP_Universal:
625 return "*";
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000626 case EOP_This:
627 return "this";
628 case EOP_NVar:
629 case EOP_LVar: {
630 return N->getNamedDecl()->getNameAsString();
631 }
632 case EOP_Dot: {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000633 if (NodeVec[i+1].kind() == EOP_Wildcard) {
634 std::string S = "&";
635 S += N->getNamedDecl()->getQualifiedNameAsString();
636 return S;
637 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000638 std::string FieldName = N->getNamedDecl()->getNameAsString();
639 if (NodeVec[i+1].kind() == EOP_This)
640 return FieldName;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000641
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000642 std::string S = toString(i+1);
643 if (N->isArrow())
644 return S + "->" + FieldName;
645 else
646 return S + "." + FieldName;
647 }
648 case EOP_Call: {
649 std::string S = toString(i+1) + "(";
650 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000651 unsigned ci = getNextSibling(i+1);
652 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000653 S += toString(ci);
654 if (k+1 < NumArgs) S += ",";
655 }
656 S += ")";
657 return S;
658 }
659 case EOP_MCall: {
660 std::string S = "";
661 if (NodeVec[i+1].kind() != EOP_This)
662 S = toString(i+1) + ".";
663 if (const NamedDecl *D = N->getFunctionDecl())
664 S += D->getNameAsString() + "(";
665 else
666 S += "#(";
667 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000668 unsigned ci = getNextSibling(i+1);
669 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000670 S += toString(ci);
671 if (k+1 < NumArgs) S += ",";
672 }
673 S += ")";
674 return S;
675 }
676 case EOP_Index: {
677 std::string S1 = toString(i+1);
678 std::string S2 = toString(i+1 + NodeVec[i+1].size());
679 return S1 + "[" + S2 + "]";
680 }
681 case EOP_Unary: {
682 std::string S = toString(i+1);
683 return "#" + S;
684 }
685 case EOP_Binary: {
686 std::string S1 = toString(i+1);
687 std::string S2 = toString(i+1 + NodeVec[i+1].size());
688 return "(" + S1 + "#" + S2 + ")";
689 }
690 case EOP_Unknown: {
691 unsigned NumChildren = N->arity();
692 if (NumChildren == 0)
693 return "(...)";
694 std::string S = "(";
695 unsigned ci = i+1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000696 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000697 S += toString(ci);
698 if (j+1 < NumChildren) S += "#";
699 }
700 S += ")";
701 return S;
702 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000703 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000704 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000705 }
706};
707
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000708/// \brief A short list of SExprs
709class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000710public:
Aaron Ballmancea26092014-03-06 19:10:16 +0000711 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000712 void push_back_nodup(const SExpr& M) {
Aaron Ballmancea26092014-03-06 19:10:16 +0000713 if (end() == std::find(begin(), end(), M))
714 push_back(M);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000715 }
716};
717
Caitlin Sadowski33208342011-09-09 16:11:56 +0000718/// \brief This is a helper class that stores info about the most recent
719/// accquire of a Lock.
720///
721/// The main body of the analysis maps MutexIDs to LockDatas.
722struct LockData {
723 SourceLocation AcquireLoc;
724
725 /// \brief LKind stores whether a lock is held shared or exclusively.
726 /// Note that this analysis does not currently support either re-entrant
727 /// locking or lock "upgrading" and "downgrading" between exclusive and
728 /// shared.
729 ///
730 /// FIXME: add support for re-entrant locking and lock up/downgrading
731 LockKind LKind;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000732 bool Asserted; // for asserted locks
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000733 bool Managed; // for ScopedLockable objects
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000734 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski33208342011-09-09 16:11:56 +0000735
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000736 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false,
737 bool Asrt=false)
738 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000739 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000740 {}
741
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000742 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000743 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000744 UnderlyingMutex(Mu)
745 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000746
747 bool operator==(const LockData &other) const {
748 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
749 }
750
751 bool operator!=(const LockData &other) const {
752 return !(*this == other);
753 }
754
755 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000756 ID.AddInteger(AcquireLoc.getRawEncoding());
757 ID.AddInteger(LKind);
758 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000759
760 bool isAtLeast(LockKind LK) {
761 return (LK == LK_Shared) || (LKind == LK_Exclusive);
762 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000763};
764
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000765
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000766/// \brief A FactEntry stores a single fact that is known at a particular point
767/// in the program execution. Currently, this is information regarding a lock
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000768/// that is held at that point.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000769struct FactEntry {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000770 SExpr MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000771 LockData LDat;
772
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000773 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000774 : MutID(M), LDat(L)
775 { }
776};
777
778
779typedef unsigned short FactID;
780
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000781/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000782/// the analysis of a single routine.
783class FactManager {
784private:
785 std::vector<FactEntry> Facts;
786
787public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000788 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000789 Facts.push_back(FactEntry(M,L));
790 return static_cast<unsigned short>(Facts.size() - 1);
791 }
792
793 const FactEntry& operator[](FactID F) const { return Facts[F]; }
794 FactEntry& operator[](FactID F) { return Facts[F]; }
795};
796
797
798/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000799/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000800/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000801/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000802/// locks, so we can get away with doing a linear search for lookup. Note
803/// that a hashtable or map is inappropriate in this case, because lookups
804/// may involve partial pattern matches, rather than exact matches.
805class FactSet {
806private:
807 typedef SmallVector<FactID, 4> FactVec;
808
809 FactVec FactIDs;
810
811public:
812 typedef FactVec::iterator iterator;
813 typedef FactVec::const_iterator const_iterator;
814
815 iterator begin() { return FactIDs.begin(); }
816 const_iterator begin() const { return FactIDs.begin(); }
817
818 iterator end() { return FactIDs.end(); }
819 const_iterator end() const { return FactIDs.end(); }
820
821 bool isEmpty() const { return FactIDs.size() == 0; }
822
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000823 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000824 FactID F = FM.newLock(M, L);
825 FactIDs.push_back(F);
826 return F;
827 }
828
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000829 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000830 unsigned n = FactIDs.size();
831 if (n == 0)
832 return false;
833
834 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000835 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000836 FactIDs[i] = FactIDs[n-1];
837 FactIDs.pop_back();
838 return true;
839 }
840 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000841 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000842 FactIDs.pop_back();
843 return true;
844 }
845 return false;
846 }
847
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000848 // Returns an iterator
849 iterator findLockIter(FactManager &FM, const SExpr &M) {
850 for (iterator I = begin(), E = end(); I != E; ++I) {
851 const SExpr &Exp = FM[*I].MutID;
852 if (Exp.matches(M))
853 return I;
854 }
855 return end();
856 }
857
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000858 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000859 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000860 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000861 if (Exp.matches(M))
862 return &FM[*I].LDat;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000863 }
864 return 0;
865 }
866
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000867 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000868 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000869 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000870 if (Exp.matches(M) || Exp.isUniversal())
871 return &FM[*I].LDat;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000872 }
873 return 0;
874 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000875
876 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
877 for (const_iterator I=begin(), E=end(); I != E; ++I) {
878 const SExpr& Exp = FM[*I].MutID;
879 if (Exp.partiallyMatches(M)) return &FM[*I];
880 }
881 return 0;
882 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000883};
884
885
886
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000887/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski33208342011-09-09 16:11:56 +0000888/// been locked.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000889typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000890typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000891
892class LocalVariableMap;
893
Richard Smith92286672012-02-03 04:45:26 +0000894/// A side (entry or exit) of a CFG node.
895enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000896
897/// CFGBlockInfo is a struct which contains all the information that is
898/// maintained for each block in the CFG. See LocalVariableMap for more
899/// information about the contexts.
900struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000901 FactSet EntrySet; // Lockset held at entry to block
902 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000903 LocalVarContext EntryContext; // Context held at entry to block
904 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000905 SourceLocation EntryLoc; // Location of first statement in block
906 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000907 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000908 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000909
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000910 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000911 return Side == CBS_Entry ? EntrySet : ExitSet;
912 }
913 SourceLocation getLocation(CFGBlockSide Side) const {
914 return Side == CBS_Entry ? EntryLoc : ExitLoc;
915 }
916
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000917private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000918 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000919 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000920 { }
921
922public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000923 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000924};
925
926
927
928// A LocalVariableMap maintains a map from local variables to their currently
929// valid definitions. It provides SSA-like functionality when traversing the
930// CFG. Like SSA, each definition or assignment to a variable is assigned a
931// unique name (an integer), which acts as the SSA name for that definition.
932// The total set of names is shared among all CFG basic blocks.
933// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
934// with their SSA-names. Instead, we compute a Context for each point in the
935// code, which maps local variables to the appropriate SSA-name. This map
936// changes with each assignment.
937//
938// The map is computed in a single pass over the CFG. Subsequent analyses can
939// then query the map to find the appropriate Context for a statement, and use
940// that Context to look up the definitions of variables.
941class LocalVariableMap {
942public:
943 typedef LocalVarContext Context;
944
945 /// A VarDefinition consists of an expression, representing the value of the
946 /// variable, along with the context in which that expression should be
947 /// interpreted. A reference VarDefinition does not itself contain this
948 /// information, but instead contains a pointer to a previous VarDefinition.
949 struct VarDefinition {
950 public:
951 friend class LocalVariableMap;
952
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000953 const NamedDecl *Dec; // The original declaration for this variable.
954 const Expr *Exp; // The expression for this variable, OR
955 unsigned Ref; // Reference to another VarDefinition
956 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000957
958 bool isReference() { return !Exp; }
959
960 private:
961 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000962 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000963 : Dec(D), Exp(E), Ref(0), Ctx(C)
964 { }
965
966 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000967 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000968 : Dec(D), Exp(0), Ref(R), Ctx(C)
969 { }
970 };
971
972private:
973 Context::Factory ContextFactory;
974 std::vector<VarDefinition> VarDefinitions;
975 std::vector<unsigned> CtxIndices;
976 std::vector<std::pair<Stmt*, Context> > SavedContexts;
977
978public:
979 LocalVariableMap() {
980 // index 0 is a placeholder for undefined variables (aka phi-nodes).
981 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
982 }
983
984 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000985 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000986 const unsigned *i = Ctx.lookup(D);
987 if (!i)
988 return 0;
989 assert(*i < VarDefinitions.size());
990 return &VarDefinitions[*i];
991 }
992
993 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000994 /// NULL if the expression is not statically known. If successful, also
995 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000996 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000997 const unsigned *P = Ctx.lookup(D);
998 if (!P)
999 return 0;
1000
1001 unsigned i = *P;
1002 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001003 if (VarDefinitions[i].Exp) {
1004 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001005 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001006 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001007 i = VarDefinitions[i].Ref;
1008 }
1009 return 0;
1010 }
1011
1012 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1013
1014 /// Return the next context after processing S. This function is used by
1015 /// clients of the class to get the appropriate context when traversing the
1016 /// CFG. It must be called for every assignment or DeclStmt.
1017 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1018 if (SavedContexts[CtxIndex+1].first == S) {
1019 CtxIndex++;
1020 Context Result = SavedContexts[CtxIndex].second;
1021 return Result;
1022 }
1023 return C;
1024 }
1025
1026 void dumpVarDefinitionName(unsigned i) {
1027 if (i == 0) {
1028 llvm::errs() << "Undefined";
1029 return;
1030 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001031 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001032 if (!Dec) {
1033 llvm::errs() << "<<NULL>>";
1034 return;
1035 }
1036 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +00001037 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001038 }
1039
1040 /// Dumps an ASCII representation of the variable map to llvm::errs()
1041 void dump() {
1042 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001043 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001044 unsigned Ref = VarDefinitions[i].Ref;
1045
1046 dumpVarDefinitionName(i);
1047 llvm::errs() << " = ";
1048 if (Exp) Exp->dump();
1049 else {
1050 dumpVarDefinitionName(Ref);
1051 llvm::errs() << "\n";
1052 }
1053 }
1054 }
1055
1056 /// Dumps an ASCII representation of a Context to llvm::errs()
1057 void dumpContext(Context C) {
1058 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001059 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001060 D->printName(llvm::errs());
1061 const unsigned *i = C.lookup(D);
1062 llvm::errs() << " -> ";
1063 dumpVarDefinitionName(*i);
1064 llvm::errs() << "\n";
1065 }
1066 }
1067
1068 /// Builds the variable map.
1069 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1070 std::vector<CFGBlockInfo> &BlockInfo);
1071
1072protected:
1073 // Get the current context index
1074 unsigned getContextIndex() { return SavedContexts.size()-1; }
1075
1076 // Save the current context for later replay
1077 void saveContext(Stmt *S, Context C) {
1078 SavedContexts.push_back(std::make_pair(S,C));
1079 }
1080
1081 // Adds a new definition to the given context, and returns a new context.
1082 // This method should be called when declaring a new variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001083 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001084 assert(!Ctx.contains(D));
1085 unsigned newID = VarDefinitions.size();
1086 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1087 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1088 return NewCtx;
1089 }
1090
1091 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001092 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001093 unsigned newID = VarDefinitions.size();
1094 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1095 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1096 return NewCtx;
1097 }
1098
1099 // Updates a definition only if that definition is already in the map.
1100 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001101 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001102 if (Ctx.contains(D)) {
1103 unsigned newID = VarDefinitions.size();
1104 Context NewCtx = ContextFactory.remove(Ctx, D);
1105 NewCtx = ContextFactory.add(NewCtx, D, newID);
1106 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1107 return NewCtx;
1108 }
1109 return Ctx;
1110 }
1111
1112 // Removes a definition from the context, but keeps the variable name
1113 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001114 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001115 Context NewCtx = Ctx;
1116 if (NewCtx.contains(D)) {
1117 NewCtx = ContextFactory.remove(NewCtx, D);
1118 NewCtx = ContextFactory.add(NewCtx, D, 0);
1119 }
1120 return NewCtx;
1121 }
1122
1123 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001124 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001125 Context NewCtx = Ctx;
1126 if (NewCtx.contains(D)) {
1127 NewCtx = ContextFactory.remove(NewCtx, D);
1128 }
1129 return NewCtx;
1130 }
1131
1132 Context intersectContexts(Context C1, Context C2);
1133 Context createReferenceContext(Context C);
1134 void intersectBackEdge(Context C1, Context C2);
1135
1136 friend class VarMapBuilder;
1137};
1138
1139
1140// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001141CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1142 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001143}
1144
1145
1146/// Visitor which builds a LocalVariableMap
1147class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1148public:
1149 LocalVariableMap* VMap;
1150 LocalVariableMap::Context Ctx;
1151
1152 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1153 : VMap(VM), Ctx(C) {}
1154
1155 void VisitDeclStmt(DeclStmt *S);
1156 void VisitBinaryOperator(BinaryOperator *BO);
1157};
1158
1159
1160// Add new local variables to the variable map
1161void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1162 bool modifiedCtx = false;
1163 DeclGroupRef DGrp = S->getDeclGroup();
1164 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1165 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1166 Expr *E = VD->getInit();
1167
1168 // Add local variables with trivial type to the variable map
1169 QualType T = VD->getType();
1170 if (T.isTrivialType(VD->getASTContext())) {
1171 Ctx = VMap->addDefinition(VD, E, Ctx);
1172 modifiedCtx = true;
1173 }
1174 }
1175 }
1176 if (modifiedCtx)
1177 VMap->saveContext(S, Ctx);
1178}
1179
1180// Update local variable definitions in variable map
1181void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1182 if (!BO->isAssignmentOp())
1183 return;
1184
1185 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1186
1187 // Update the variable map and current context.
1188 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1189 ValueDecl *VDec = DRE->getDecl();
1190 if (Ctx.lookup(VDec)) {
1191 if (BO->getOpcode() == BO_Assign)
1192 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1193 else
1194 // FIXME -- handle compound assignment operators
1195 Ctx = VMap->clearDefinition(VDec, Ctx);
1196 VMap->saveContext(BO, Ctx);
1197 }
1198 }
1199}
1200
1201
1202// Computes the intersection of two contexts. The intersection is the
1203// set of variables which have the same definition in both contexts;
1204// variables with different definitions are discarded.
1205LocalVariableMap::Context
1206LocalVariableMap::intersectContexts(Context C1, Context C2) {
1207 Context Result = C1;
1208 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001209 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001210 unsigned i1 = I.getData();
1211 const unsigned *i2 = C2.lookup(Dec);
1212 if (!i2) // variable doesn't exist on second path
1213 Result = removeDefinition(Dec, Result);
1214 else if (*i2 != i1) // variable exists, but has different definition
1215 Result = clearDefinition(Dec, Result);
1216 }
1217 return Result;
1218}
1219
1220// For every variable in C, create a new variable that refers to the
1221// definition in C. Return a new context that contains these new variables.
1222// (We use this for a naive implementation of SSA on loop back-edges.)
1223LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1224 Context Result = getEmptyContext();
1225 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001226 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001227 unsigned i = I.getData();
1228 Result = addReference(Dec, i, Result);
1229 }
1230 return Result;
1231}
1232
1233// This routine also takes the intersection of C1 and C2, but it does so by
1234// altering the VarDefinitions. C1 must be the result of an earlier call to
1235// createReferenceContext.
1236void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1237 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001238 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001239 unsigned i1 = I.getData();
1240 VarDefinition *VDef = &VarDefinitions[i1];
1241 assert(VDef->isReference());
1242
1243 const unsigned *i2 = C2.lookup(Dec);
1244 if (!i2 || (*i2 != i1))
1245 VDef->Ref = 0; // Mark this variable as undefined
1246 }
1247}
1248
1249
1250// Traverse the CFG in topological order, so all predecessors of a block
1251// (excluding back-edges) are visited before the block itself. At
1252// each point in the code, we calculate a Context, which holds the set of
1253// variable definitions which are visible at that point in execution.
1254// Visible variables are mapped to their definitions using an array that
1255// contains all definitions.
1256//
1257// At join points in the CFG, the set is computed as the intersection of
1258// the incoming sets along each edge, E.g.
1259//
1260// { Context | VarDefinitions }
1261// int x = 0; { x -> x1 | x1 = 0 }
1262// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1263// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1264// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1265// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1266//
1267// This is essentially a simpler and more naive version of the standard SSA
1268// algorithm. Those definitions that remain in the intersection are from blocks
1269// that strictly dominate the current block. We do not bother to insert proper
1270// phi nodes, because they are not used in our analysis; instead, wherever
1271// a phi node would be required, we simply remove that definition from the
1272// context (E.g. x above).
1273//
1274// The initial traversal does not capture back-edges, so those need to be
1275// handled on a separate pass. Whenever the first pass encounters an
1276// incoming back edge, it duplicates the context, creating new definitions
1277// that refer back to the originals. (These correspond to places where SSA
1278// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001279// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001280// node was actually required.) E.g.
1281//
1282// { Context | VarDefinitions }
1283// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1284// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1285// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1286// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1287//
1288void LocalVariableMap::traverseCFG(CFG *CFGraph,
1289 PostOrderCFGView *SortedGraph,
1290 std::vector<CFGBlockInfo> &BlockInfo) {
1291 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1292
1293 CtxIndices.resize(CFGraph->getNumBlockIDs());
1294
1295 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1296 E = SortedGraph->end(); I!= E; ++I) {
1297 const CFGBlock *CurrBlock = *I;
1298 int CurrBlockID = CurrBlock->getBlockID();
1299 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1300
1301 VisitedBlocks.insert(CurrBlock);
1302
1303 // Calculate the entry context for the current block
1304 bool HasBackEdges = false;
1305 bool CtxInit = true;
1306 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1307 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1308 // if *PI -> CurrBlock is a back edge, so skip it
1309 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1310 HasBackEdges = true;
1311 continue;
1312 }
1313
1314 int PrevBlockID = (*PI)->getBlockID();
1315 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1316
1317 if (CtxInit) {
1318 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1319 CtxInit = false;
1320 }
1321 else {
1322 CurrBlockInfo->EntryContext =
1323 intersectContexts(CurrBlockInfo->EntryContext,
1324 PrevBlockInfo->ExitContext);
1325 }
1326 }
1327
1328 // Duplicate the context if we have back-edges, so we can call
1329 // intersectBackEdges later.
1330 if (HasBackEdges)
1331 CurrBlockInfo->EntryContext =
1332 createReferenceContext(CurrBlockInfo->EntryContext);
1333
1334 // Create a starting context index for the current block
1335 saveContext(0, CurrBlockInfo->EntryContext);
1336 CurrBlockInfo->EntryIndex = getContextIndex();
1337
1338 // Visit all the statements in the basic block.
1339 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1340 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1341 BE = CurrBlock->end(); BI != BE; ++BI) {
1342 switch (BI->getKind()) {
1343 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00001344 CFGStmt CS = BI->castAs<CFGStmt>();
1345 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001346 break;
1347 }
1348 default:
1349 break;
1350 }
1351 }
1352 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1353
1354 // Mark variables on back edges as "unknown" if they've been changed.
1355 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1356 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1357 // if CurrBlock -> *SI is *not* a back edge
1358 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1359 continue;
1360
1361 CFGBlock *FirstLoopBlock = *SI;
1362 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1363 Context LoopEnd = CurrBlockInfo->ExitContext;
1364 intersectBackEdge(LoopBegin, LoopEnd);
1365 }
1366 }
1367
1368 // Put an extra entry at the end of the indexed context array
1369 unsigned exitID = CFGraph->getExit().getBlockID();
1370 saveContext(0, BlockInfo[exitID].ExitContext);
1371}
1372
Richard Smith92286672012-02-03 04:45:26 +00001373/// Find the appropriate source locations to use when producing diagnostics for
1374/// each block in the CFG.
1375static void findBlockLocations(CFG *CFGraph,
1376 PostOrderCFGView *SortedGraph,
1377 std::vector<CFGBlockInfo> &BlockInfo) {
1378 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1379 E = SortedGraph->end(); I!= E; ++I) {
1380 const CFGBlock *CurrBlock = *I;
1381 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1382
1383 // Find the source location of the last statement in the block, if the
1384 // block is not empty.
1385 if (const Stmt *S = CurrBlock->getTerminator()) {
1386 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1387 } else {
1388 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1389 BE = CurrBlock->rend(); BI != BE; ++BI) {
1390 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001391 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1392 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001393 break;
1394 }
1395 }
1396 }
1397
1398 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1399 // This block contains at least one statement. Find the source location
1400 // of the first statement in the block.
1401 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1402 BE = CurrBlock->end(); BI != BE; ++BI) {
1403 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001404 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1405 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001406 break;
1407 }
1408 }
1409 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1410 CurrBlock != &CFGraph->getExit()) {
1411 // The block is empty, and has a single predecessor. Use its exit
1412 // location.
1413 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1414 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1415 }
1416 }
1417}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001418
1419/// \brief Class which implements the core thread safety analysis routines.
1420class ThreadSafetyAnalyzer {
1421 friend class BuildLockset;
1422
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001423 ThreadSafetyHandler &Handler;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001424 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001425 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001426 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001427
1428public:
1429 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1430
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001431 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1432 void removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001433 SourceLocation UnlockLoc, bool FullyRemove=false);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001434
1435 template <typename AttrType>
1436 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001437 const NamedDecl *D, VarDecl *SelfDecl=0);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001438
1439 template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001440 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1441 const NamedDecl *D,
1442 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1443 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001444
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001445 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1446 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001447
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001448 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1449 const CFGBlock* PredBlock,
1450 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001451
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001452 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1453 SourceLocation JoinLoc,
1454 LockErrorKind LEK1, LockErrorKind LEK2,
1455 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001456
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001457 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1458 SourceLocation JoinLoc, LockErrorKind LEK1,
1459 bool Modify=true) {
1460 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001461 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001462
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001463 void runAnalysis(AnalysisDeclContext &AC);
1464};
1465
Caitlin Sadowski33208342011-09-09 16:11:56 +00001466
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001467/// \brief Add a new lock to the lockset, warning if the lock is already there.
1468/// \param Mutex -- the Mutex expression for the lock
1469/// \param LDat -- the LockData for the lock
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001470void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001471 const LockData &LDat) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001472 // FIXME: deal with acquired before/after annotations.
1473 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001474 if (Mutex.shouldIgnore())
1475 return;
1476
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001477 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001478 if (!LDat.Asserted)
1479 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001480 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001481 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001482 }
1483}
1484
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001485
1486/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenek78094ca2012-08-22 23:50:41 +00001487/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001488/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001489void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001490 const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001491 SourceLocation UnlockLoc,
1492 bool FullyRemove) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001493 if (Mutex.shouldIgnore())
1494 return;
1495
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001496 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001497 if (!LDat) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001498 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001499 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001500 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001501
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001502 if (LDat->UnderlyingMutex.isValid()) {
1503 // This is scoped lockable object, which manages the real mutex.
1504 if (FullyRemove) {
1505 // We're destroying the managing object.
1506 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001507 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1508 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001509 } else {
1510 // We're releasing the underlying mutex, but not destroying the
1511 // managing object. Warn on dual release.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001512 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001513 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001514 UnlockLoc);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001515 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001516 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1517 return;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001518 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001519 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001520 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001521}
1522
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001523
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001524/// \brief Extract the list of mutexIDs from the attribute on an expression,
1525/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001526template <typename AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001527void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001528 Expr *Exp, const NamedDecl *D,
1529 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001530 typedef typename AttrType::args_iterator iterator_type;
1531
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001532 if (Attr->args_size() == 0) {
1533 // The mutex held is the "this" object.
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001534 SExpr Mu(0, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001535 if (!Mu.isValid())
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001536 SExpr::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001537 else
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001538 Mtxs.push_back_nodup(Mu);
1539 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001540 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001541
1542 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001543 SExpr Mu(*I, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001544 if (!Mu.isValid())
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001545 SExpr::warnInvalidLock(Handler, *I, Exp, D);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001546 else
1547 Mtxs.push_back_nodup(Mu);
1548 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001549}
1550
1551
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001552/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1553/// trylock applies to the given edge, then push them onto Mtxs, discarding
1554/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001555template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001556void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1557 Expr *Exp, const NamedDecl *D,
1558 const CFGBlock *PredBlock,
1559 const CFGBlock *CurrBlock,
1560 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001561 // Find out which branch has the lock
1562 bool branch = 0;
1563 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1564 branch = BLE->getValue();
1565 }
1566 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1567 branch = ILE->getValue().getBoolValue();
1568 }
1569 int branchnum = branch ? 0 : 1;
1570 if (Neg) branchnum = !branchnum;
1571
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001572 // If we've taken the trylock branch, then add the lock
1573 int i = 0;
1574 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1575 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1576 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001577 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001578 }
1579 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001580}
1581
1582
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001583bool getStaticBooleanValue(Expr* E, bool& TCond) {
1584 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1585 TCond = false;
1586 return true;
1587 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1588 TCond = BLE->getValue();
1589 return true;
1590 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1591 TCond = ILE->getValue().getBoolValue();
1592 return true;
1593 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1594 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1595 }
1596 return false;
1597}
1598
1599
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001600// If Cond can be traced back to a function call, return the call expression.
1601// The negate variable should be called with false, and will be set to true
1602// if the function call is negated, e.g. if (!mu.tryLock(...))
1603const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1604 LocalVarContext C,
1605 bool &Negate) {
1606 if (!Cond)
1607 return 0;
1608
1609 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1610 return CallExp;
1611 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001612 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1613 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1614 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001615 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1616 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1617 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001618 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1619 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1620 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001621 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1622 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1623 return getTrylockCallExpr(E, C, Negate);
1624 }
1625 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1626 if (UOP->getOpcode() == UO_LNot) {
1627 Negate = !Negate;
1628 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1629 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001630 return 0;
1631 }
1632 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1633 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1634 if (BOP->getOpcode() == BO_NE)
1635 Negate = !Negate;
1636
1637 bool TCond = false;
1638 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1639 if (!TCond) Negate = !Negate;
1640 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1641 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001642 TCond = false;
1643 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001644 if (!TCond) Negate = !Negate;
1645 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1646 }
1647 return 0;
1648 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001649 if (BOP->getOpcode() == BO_LAnd) {
1650 // LHS must have been evaluated in a different block.
1651 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1652 }
1653 if (BOP->getOpcode() == BO_LOr) {
1654 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1655 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001656 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001657 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001658 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001659}
1660
1661
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001662/// \brief Find the lockset that holds on the edge between PredBlock
1663/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1664/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001665void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1666 const FactSet &ExitSet,
1667 const CFGBlock *PredBlock,
1668 const CFGBlock *CurrBlock) {
1669 Result = ExitSet;
1670
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001671 const Stmt *Cond = PredBlock->getTerminatorCondition();
1672 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001673 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001674
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001675 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001676 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1677 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1678
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001679 CallExpr *Exp =
1680 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001681 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001682 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001683
1684 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1685 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001686 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001687
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001688 MutexIDList ExclusiveLocksToAdd;
1689 MutexIDList SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001690
1691 // If the condition is a call to a Trylock function, then grab the attributes
1692 AttrVec &ArgAttrs = FunDecl->getAttrs();
1693 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1694 Attr *Attr = ArgAttrs[i];
1695 switch (Attr->getKind()) {
1696 case attr::ExclusiveTrylockFunction: {
1697 ExclusiveTrylockFunctionAttr *A =
1698 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001699 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1700 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001701 break;
1702 }
1703 case attr::SharedTrylockFunction: {
1704 SharedTrylockFunctionAttr *A =
1705 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001706 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001707 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001708 break;
1709 }
1710 default:
1711 break;
1712 }
1713 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001714
1715 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001716 SourceLocation Loc = Exp->getExprLoc();
1717 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001718 addLock(Result, ExclusiveLocksToAdd[i],
1719 LockData(Loc, LK_Exclusive));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001720 }
1721 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001722 addLock(Result, SharedLocksToAdd[i],
1723 LockData(Loc, LK_Shared));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001724 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001725}
1726
1727
Caitlin Sadowski33208342011-09-09 16:11:56 +00001728/// \brief We use this class to visit different types of expressions in
1729/// CFGBlocks, and build up the lockset.
1730/// An expression may cause us to add or remove locks from the lockset, or else
1731/// output error messages related to missing locks.
1732/// FIXME: In future, we may be able to not inherit from a visitor.
1733class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001734 friend class ThreadSafetyAnalyzer;
1735
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001736 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001737 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001738 LocalVariableMap::Context LVarCtx;
1739 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001740
1741 // Helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001742 const ValueDecl *getValueDecl(const Expr *Exp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001743
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001744 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001745 Expr *MutexExp, ProtectedOperationKind POK);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001746 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001747
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001748 void checkAccess(const Expr *Exp, AccessKind AK);
1749 void checkPtAccess(const Expr *Exp, AccessKind AK);
1750
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001751 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001752
Caitlin Sadowski33208342011-09-09 16:11:56 +00001753public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001754 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001755 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001756 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001757 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001758 LVarCtx(Info.EntryContext),
1759 CtxIndex(Info.EntryIndex)
1760 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001761
1762 void VisitUnaryOperator(UnaryOperator *UO);
1763 void VisitBinaryOperator(BinaryOperator *BO);
1764 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001765 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001766 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001767 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001768};
1769
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001770
Caitlin Sadowski33208342011-09-09 16:11:56 +00001771/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001772const ValueDecl *BuildLockset::getValueDecl(const Expr *Exp) {
1773 if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Exp))
1774 return getValueDecl(CE->getSubExpr());
1775
Caitlin Sadowski33208342011-09-09 16:11:56 +00001776 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1777 return DR->getDecl();
1778
1779 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1780 return ME->getMemberDecl();
1781
1782 return 0;
1783}
1784
1785/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001786/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001787void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001788 AccessKind AK, Expr *MutexExp,
1789 ProtectedOperationKind POK) {
1790 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001791
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001792 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001793 if (!Mutex.isValid()) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001794 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001795 return;
1796 } else if (Mutex.shouldIgnore()) {
1797 return;
1798 }
1799
1800 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001801 bool NoError = true;
1802 if (!LDat) {
1803 // No exact match found. Look for a partial match.
1804 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1805 if (FEntry) {
1806 // Warn that there's no precise match.
1807 LDat = &FEntry->LDat;
1808 std::string PartMatchStr = FEntry->MutID.toString();
1809 StringRef PartMatchName(PartMatchStr);
1810 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1811 Exp->getExprLoc(), &PartMatchName);
1812 } else {
1813 // Warn that there's no match at all.
1814 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1815 Exp->getExprLoc());
1816 }
1817 NoError = false;
1818 }
1819 // Make sure the mutex we found is the right kind.
1820 if (NoError && LDat && !LDat->isAtLeast(LK))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001821 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001822 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001823}
1824
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001825/// \brief Warn if the LSet contains the given lock.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001826void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr* Exp,
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001827 Expr *MutexExp) {
1828 SExpr Mutex(MutexExp, Exp, D);
1829 if (!Mutex.isValid()) {
1830 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1831 return;
1832 }
1833
1834 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001835 if (LDat) {
1836 std::string DeclName = D->getNameAsString();
1837 StringRef DeclNameSR (DeclName);
1838 Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(),
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001839 Exp->getExprLoc());
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001840 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001841}
1842
1843
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001844/// \brief Checks guarded_by and pt_guarded_by attributes.
1845/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1846/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1847/// Similarly, we check if the access is to an expression that dereferences
1848/// a pointer marked with pt_guarded_by.
1849void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1850 Exp = Exp->IgnoreParenCasts();
1851
1852 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1853 // For dereferences
1854 if (UO->getOpcode() == clang::UO_Deref)
1855 checkPtAccess(UO->getSubExpr(), AK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001856 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001857 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001858
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001859 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001860 checkPtAccess(AE->getLHS(), AK);
1861 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001862 }
1863
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001864 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1865 if (ME->isArrow())
1866 checkPtAccess(ME->getBase(), AK);
1867 else
1868 checkAccess(ME->getBase(), AK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001869 }
1870
Caitlin Sadowski33208342011-09-09 16:11:56 +00001871 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001872 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001873 return;
1874
Aaron Ballman9ead1242013-12-19 02:39:40 +00001875 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001876 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1877 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001878
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001879 for (const auto *I : D->specific_attrs<GuardedByAttr>())
1880 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001881}
1882
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001883/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1884void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001885 while (true) {
1886 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1887 Exp = PE->getSubExpr();
1888 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001889 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001890 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1891 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1892 // If it's an actual array, and not a pointer, then it's elements
1893 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1894 checkAccess(CE->getSubExpr(), AK);
1895 return;
1896 }
1897 Exp = CE->getSubExpr();
1898 continue;
1899 }
1900 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001901 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001902
1903 const ValueDecl *D = getValueDecl(Exp);
1904 if (!D || !D->hasAttrs())
1905 return;
1906
Aaron Ballman9ead1242013-12-19 02:39:40 +00001907 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001908 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1909 Exp->getExprLoc());
1910
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001911 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1912 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001913}
1914
1915
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001916/// \brief Process a function call, method call, constructor call,
1917/// or destructor call. This involves looking at the attributes on the
1918/// corresponding function/method/constructor/destructor, issuing warnings,
1919/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001920///
1921/// FIXME: For classes annotated with one of the guarded annotations, we need
1922/// to treat const method calls as reads and non-const method calls as writes,
1923/// and check that the appropriate locks are held. Non-const method calls with
1924/// the same signature as const method calls can be also treated as reads.
1925///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001926void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001927 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001928 const AttrVec &ArgAttrs = D->getAttrs();
1929 MutexIDList ExclusiveLocksToAdd;
1930 MutexIDList SharedLocksToAdd;
1931 MutexIDList LocksToRemove;
1932
Caitlin Sadowski33208342011-09-09 16:11:56 +00001933 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001934 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1935 switch (At->getKind()) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001936 // When we encounter an exclusive lock function, we need to add the lock
1937 // to our lockset with kind exclusive.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001938 case attr::ExclusiveLockFunction: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001939 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001940 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D, VD);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001941 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001942 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001943
1944 // When we encounter a shared lock function, we need to add the lock
1945 // to our lockset with kind shared.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001946 case attr::SharedLockFunction: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001947 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001948 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D, VD);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001949 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001950 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001951
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001952 // An assert will add a lock to the lockset, but will not generate
1953 // a warning if it is already there, and will not generate a warning
1954 // if it is not removed.
1955 case attr::AssertExclusiveLock: {
1956 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1957
1958 MutexIDList AssertLocks;
1959 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1960 for (unsigned i=0,n=AssertLocks.size(); i<n; ++i) {
1961 Analyzer->addLock(FSet, AssertLocks[i],
1962 LockData(Loc, LK_Exclusive, false, true));
1963 }
1964 break;
1965 }
1966 case attr::AssertSharedLock: {
1967 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1968
1969 MutexIDList AssertLocks;
1970 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1971 for (unsigned i=0,n=AssertLocks.size(); i<n; ++i) {
1972 Analyzer->addLock(FSet, AssertLocks[i],
1973 LockData(Loc, LK_Shared, false, true));
1974 }
1975 break;
1976 }
1977
Caitlin Sadowski33208342011-09-09 16:11:56 +00001978 // When we encounter an unlock function, we need to remove unlocked
1979 // mutexes from the lockset, and flag a warning if they are not there.
1980 case attr::UnlockFunction: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001981 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001982 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D, VD);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001983 break;
1984 }
1985
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001986 case attr::RequiresCapability: {
1987 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001988
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001989 for (RequiresCapabilityAttr::args_iterator I = A->args_begin(),
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001990 E = A->args_end(); I != E; ++I)
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001991 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, *I,
1992 POK_FunctionCall);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001993 break;
1994 }
1995
1996 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001997 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001998
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001999 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
2000 E = A->args_end(); I != E; ++I) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00002001 warnIfMutexHeld(D, Exp, *I);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002002 }
2003 break;
2004 }
2005
Alp Tokerd4733632013-12-05 04:47:09 +00002006 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00002007 default:
2008 break;
2009 }
2010 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002011
2012 // Figure out if we're calling the constructor of scoped lockable class
2013 bool isScopedVar = false;
2014 if (VD) {
2015 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
2016 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00002017 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002018 isScopedVar = true;
2019 }
2020 }
2021
2022 // Add locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002023 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002024 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
2025 LockData(Loc, LK_Exclusive, isScopedVar));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002026 }
2027 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002028 Analyzer->addLock(FSet, SharedLocksToAdd[i],
2029 LockData(Loc, LK_Shared, isScopedVar));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002030 }
2031
2032 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2033 // FIXME -- this doesn't work if we acquire multiple locks.
2034 if (isScopedVar) {
2035 SourceLocation MLoc = VD->getLocation();
2036 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002037 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002038
2039 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002040 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
2041 ExclusiveLocksToAdd[i]));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002042 }
2043 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002044 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
2045 SharedLocksToAdd[i]));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002046 }
2047 }
2048
2049 // Remove locks.
2050 // FIXME -- should only fully remove if the attribute refers to 'this'.
2051 bool Dtor = isa<CXXDestructorDecl>(D);
2052 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002053 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002054 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002055}
2056
DeLesley Hutchins9d530332012-01-06 19:16:50 +00002057
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002058/// \brief For unary operations which read and write a variable, we need to
2059/// check whether we hold any required mutexes. Reads are checked in
2060/// VisitCastExpr.
2061void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2062 switch (UO->getOpcode()) {
2063 case clang::UO_PostDec:
2064 case clang::UO_PostInc:
2065 case clang::UO_PreDec:
2066 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002067 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002068 break;
2069 }
2070 default:
2071 break;
2072 }
2073}
2074
2075/// For binary operations which assign to a variable (writes), we need to check
2076/// whether we hold any required mutexes.
2077/// FIXME: Deal with non-primitive types.
2078void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2079 if (!BO->isAssignmentOp())
2080 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002081
2082 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002083 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002084
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002085 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002086}
2087
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002088
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002089/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2090/// need to ensure we hold any required mutexes.
2091/// FIXME: Deal with non-primitive types.
2092void BuildLockset::VisitCastExpr(CastExpr *CE) {
2093 if (CE->getCastKind() != CK_LValueToRValue)
2094 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002095 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002096}
2097
2098
DeLesley Hutchins714296c2011-12-29 00:56:48 +00002099void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002100 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2101 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2102 // ME can be null when calling a method pointer
2103 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002104
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002105 if (ME && MD) {
2106 if (ME->isArrow()) {
2107 if (MD->isConst()) {
2108 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2109 } else { // FIXME -- should be AK_Written
2110 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002111 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002112 } else {
2113 if (MD->isConst())
2114 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2115 else // FIXME -- should be AK_Written
2116 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002117 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002118 }
2119 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2120 switch (OE->getOperator()) {
2121 case OO_Equal: {
2122 const Expr *Target = OE->getArg(0);
2123 const Expr *Source = OE->getArg(1);
2124 checkAccess(Target, AK_Written);
2125 checkAccess(Source, AK_Read);
2126 break;
2127 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002128 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002129 case OO_Arrow:
2130 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00002131 const Expr *Obj = OE->getArg(0);
2132 checkAccess(Obj, AK_Read);
2133 checkPtAccess(Obj, AK_Read);
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002134 break;
2135 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002136 default: {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002137 const Expr *Obj = OE->getArg(0);
2138 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002139 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002140 }
2141 }
2142 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002143 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2144 if(!D || !D->hasAttrs())
2145 return;
2146 handleCall(Exp, D);
2147}
2148
2149void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002150 const CXXConstructorDecl *D = Exp->getConstructor();
2151 if (D && D->isCopyConstructor()) {
2152 const Expr* Source = Exp->getArg(0);
2153 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002154 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002155 // FIXME -- only handles constructors in DeclStmt below.
2156}
2157
2158void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002159 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002160 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002161
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002162 DeclGroupRef DGrp = S->getDeclGroup();
2163 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2164 Decl *D = *I;
2165 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2166 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002167 // handle constructors that involve temporaries
2168 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2169 E = EWC->getSubExpr();
2170
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002171 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2172 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2173 if (!CtorD || !CtorD->hasAttrs())
2174 return;
2175 handleCall(CE, CtorD, VD);
2176 }
2177 }
2178 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002179}
2180
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002181
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002182
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002183/// \brief Compute the intersection of two locksets and issue warnings for any
2184/// locks in the symmetric difference.
2185///
2186/// This function is used at a merge point in the CFG when comparing the lockset
2187/// of each branch being merged. For example, given the following sequence:
2188/// A; if () then B; else C; D; we need to check that the lockset after B and C
2189/// are the same. In the event of a difference, we use the intersection of these
2190/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002191///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002192/// \param FSet1 The first lockset.
2193/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002194/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002195/// \param LEK1 The error message to report if a mutex is missing from LSet1
2196/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002197void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2198 const FactSet &FSet2,
2199 SourceLocation JoinLoc,
2200 LockErrorKind LEK1,
2201 LockErrorKind LEK2,
2202 bool Modify) {
2203 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002204
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002205 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002206 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2207 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002208 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002209 const LockData &LDat2 = FactMan[*I].LDat;
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002210 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002211
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002212 if (I1 != FSet1.end()) {
2213 const LockData* LDat1 = &FactMan[*I1].LDat;
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002214 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002215 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002216 LDat2.AcquireLoc,
2217 LDat1->AcquireLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002218 if (Modify && LDat1->LKind != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002219 // Take the exclusive lock, which is the one in FSet2.
2220 *I1 = *I;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002221 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002222 }
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002223 else if (LDat1->Asserted && !LDat2.Asserted) {
2224 // The non-asserted lock in FSet2 is the one we want to track.
2225 *I1 = *I;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002226 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002227 } else {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002228 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002229 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002230 // If this is a scoped lock that manages another mutex, and if the
2231 // underlying mutex is still held, then warn about the underlying
2232 // mutex.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002233 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002234 LDat2.AcquireLoc,
2235 JoinLoc, LEK1);
2236 }
2237 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002238 else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted)
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002239 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002240 LDat2.AcquireLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002241 JoinLoc, LEK1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002242 }
2243 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002244
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002245 // Find locks in FSet1 that are not in FSet2, and remove them.
2246 for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002247 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002248 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002249 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002250
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002251 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002252 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002253 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002254 // If this is a scoped lock that manages another mutex, and if the
2255 // underlying mutex is still held, then warn about the underlying
2256 // mutex.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002257 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002258 LDat1.AcquireLoc,
2259 JoinLoc, LEK1);
2260 }
2261 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002262 else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted)
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002263 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002264 LDat1.AcquireLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002265 JoinLoc, LEK2);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002266 if (Modify)
2267 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002268 }
2269 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002270}
2271
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002272
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002273// Return true if block B never continues to its successors.
2274inline bool neverReturns(const CFGBlock* B) {
2275 if (B->hasNoReturnElement())
2276 return true;
2277 if (B->empty())
2278 return false;
2279
2280 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002281 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2282 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002283 return true;
2284 }
2285 return false;
2286}
2287
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002288
Caitlin Sadowski33208342011-09-09 16:11:56 +00002289/// \brief Check a function's CFG for thread-safety violations.
2290///
2291/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2292/// at the end of each block, and issue warnings for thread safety violations.
2293/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002294void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002295 CFG *CFGraph = AC.getCFG();
2296 if (!CFGraph) return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002297 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2298
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002299 // AC.dumpCFG(true);
2300
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002301 if (!D)
2302 return; // Ignore anonymous functions for now.
Aaron Ballman9ead1242013-12-19 02:39:40 +00002303 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002304 return;
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002305 // FIXME: Do something a bit more intelligent inside constructor and
2306 // destructor code. Constructors and destructors must assume unique access
2307 // to 'this', so checks on member variable access is disabled, but we should
2308 // still enable checks on other objects.
2309 if (isa<CXXConstructorDecl>(D))
2310 return; // Don't check inside constructors.
2311 if (isa<CXXDestructorDecl>(D))
2312 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002313
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002314 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002315 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002316
2317 // We need to explore the CFG via a "topological" ordering.
2318 // That way, we will be guaranteed to have information about required
2319 // predecessor locksets when exploring a new block.
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002320 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2321 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002322
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002323 // Mark entry block as reachable
2324 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2325
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002326 // Compute SSA names for local variables
2327 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2328
Richard Smith92286672012-02-03 04:45:26 +00002329 // Fill in source locations for all CFGBlocks.
2330 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2331
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002332 MutexIDList ExclusiveLocksAcquired;
2333 MutexIDList SharedLocksAcquired;
2334 MutexIDList LocksReleased;
2335
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002336 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002337 // to initial lockset. Also turn off checking for lock and unlock functions.
2338 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002339 if (!SortedGraph->empty() && D->hasAttrs()) {
2340 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002341 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002342 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002343
2344 MutexIDList ExclusiveLocksToAdd;
2345 MutexIDList SharedLocksToAdd;
2346
2347 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002348 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002349 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002350 Loc = Attr->getLocation();
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002351 if (RequiresCapabilityAttr *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2352 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2353 0, D);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002354 } else if (UnlockFunctionAttr *A = dyn_cast<UnlockFunctionAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002355 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2356 // We must ignore such methods.
2357 if (A->args_size() == 0)
2358 return;
2359 // FIXME -- deal with exclusive vs. shared unlock functions?
2360 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2361 getMutexIDs(LocksReleased, A, (Expr*) 0, D);
2362 } else if (ExclusiveLockFunctionAttr *A
2363 = dyn_cast<ExclusiveLockFunctionAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002364 if (A->args_size() == 0)
2365 return;
2366 getMutexIDs(ExclusiveLocksAcquired, A, (Expr*) 0, D);
2367 } else if (SharedLockFunctionAttr *A
2368 = dyn_cast<SharedLockFunctionAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002369 if (A->args_size() == 0)
2370 return;
2371 getMutexIDs(SharedLocksAcquired, A, (Expr*) 0, D);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002372 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2373 // Don't try to check trylock functions for now
2374 return;
2375 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2376 // Don't try to check trylock functions for now
2377 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002378 }
2379 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002380
2381 // FIXME -- Loc can be wrong here.
2382 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002383 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2384 LockData(Loc, LK_Exclusive));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002385 }
2386 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002387 addLock(InitialLockset, SharedLocksToAdd[i],
2388 LockData(Loc, LK_Shared));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002389 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002390 }
2391
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002392 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2393 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002394 const CFGBlock *CurrBlock = *I;
2395 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002396 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002397
2398 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002399 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002400
2401 // Iterate through the predecessor blocks and warn if the lockset for all
2402 // predecessors is not the same. We take the entry lockset of the current
2403 // block to be the intersection of all previous locksets.
2404 // FIXME: By keeping the intersection, we may output more errors in future
2405 // for a lock which is not in the intersection, but was in the union. We
2406 // may want to also keep the union in future. As an example, let's say
2407 // the intersection contains Mutex L, and the union contains L and M.
2408 // Later we unlock M. At this point, we would output an error because we
2409 // never locked M; although the real error is probably that we forgot to
2410 // lock M on all code paths. Conversely, let's say that later we lock M.
2411 // In this case, we should compare against the intersection instead of the
2412 // union because the real error is probably that we forgot to unlock M on
2413 // all code paths.
2414 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002415 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002416 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2417 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2418
2419 // if *PI -> CurrBlock is a back edge
2420 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2421 continue;
2422
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002423 int PrevBlockID = (*PI)->getBlockID();
2424 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2425
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002426 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002427 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002428 continue;
2429
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002430 // Okay, we can reach this block from the entry.
2431 CurrBlockInfo->Reachable = true;
2432
Richard Smith815b29d2012-02-03 03:30:07 +00002433 // If the previous block ended in a 'continue' or 'break' statement, then
2434 // a difference in locksets is probably due to a bug in that block, rather
2435 // than in some other predecessor. In that case, keep the other
2436 // predecessor's lockset.
2437 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2438 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2439 SpecialBlocks.push_back(*PI);
2440 continue;
2441 }
2442 }
2443
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002444 FactSet PrevLockset;
2445 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002446
Caitlin Sadowski33208342011-09-09 16:11:56 +00002447 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002448 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002449 LocksetInitialized = true;
2450 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002451 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2452 CurrBlockInfo->EntryLoc,
2453 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002454 }
2455 }
2456
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002457 // Skip rest of block if it's not reachable.
2458 if (!CurrBlockInfo->Reachable)
2459 continue;
2460
Richard Smith815b29d2012-02-03 03:30:07 +00002461 // Process continue and break blocks. Assume that the lockset for the
2462 // resulting block is unaffected by any discrepancies in them.
2463 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2464 SpecialI < SpecialN; ++SpecialI) {
2465 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2466 int PrevBlockID = PrevBlock->getBlockID();
2467 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2468
2469 if (!LocksetInitialized) {
2470 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2471 LocksetInitialized = true;
2472 } else {
2473 // Determine whether this edge is a loop terminator for diagnostic
2474 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2475 // it might also be part of a switch. Also, a subsequent destructor
2476 // might add to the lockset, in which case the real issue might be a
2477 // double lock on the other path.
2478 const Stmt *Terminator = PrevBlock->getTerminator();
2479 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2480
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002481 FactSet PrevLockset;
2482 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2483 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002484
Richard Smith815b29d2012-02-03 03:30:07 +00002485 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002486 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2487 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002488 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002489 : LEK_LockedSomePredecessors,
2490 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002491 }
2492 }
2493
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002494 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2495
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002496 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002497 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2498 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002499 switch (BI->getKind()) {
2500 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002501 CFGStmt CS = BI->castAs<CFGStmt>();
2502 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002503 break;
2504 }
2505 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2506 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002507 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2508 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2509 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002510 if (!DD->hasAttrs())
2511 break;
2512
2513 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002514 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002515 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002516 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002517 LocksetBuilder.handleCall(&DRE, DD);
2518 break;
2519 }
2520 default:
2521 break;
2522 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002523 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002524 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002525
2526 // For every back edge from CurrBlock (the end of the loop) to another block
2527 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2528 // the one held at the beginning of FirstLoopBlock. We can look up the
2529 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2530 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2531 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2532
2533 // if CurrBlock -> *SI is *not* a back edge
2534 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2535 continue;
2536
2537 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002538 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2539 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2540 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2541 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002542 LEK_LockedSomeLoopIterations,
2543 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002544 }
2545 }
2546
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002547 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2548 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002549
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002550 // Skip the final check if the exit block is unreachable.
2551 if (!Final->Reachable)
2552 return;
2553
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002554 // By default, we expect all locks held on entry to be held on exit.
2555 FactSet ExpectedExitSet = Initial->EntrySet;
2556
2557 // Adjust the expected exit set by adding or removing locks, as declared
2558 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2559 // issue the appropriate warning.
2560 // FIXME: the location here is not quite right.
2561 for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) {
2562 ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i],
2563 LockData(D->getLocation(), LK_Exclusive));
2564 }
2565 for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) {
2566 ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i],
2567 LockData(D->getLocation(), LK_Shared));
2568 }
2569 for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) {
2570 ExpectedExitSet.removeLock(FactMan, LocksReleased[i]);
2571 }
2572
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002573 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002574 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002575 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002576 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002577 LEK_NotLockedAtEndOfFunction,
2578 false);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002579}
2580
2581} // end anonymous namespace
2582
2583
2584namespace clang {
2585namespace thread_safety {
2586
2587/// \brief Check a function's CFG for thread-safety violations.
2588///
2589/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2590/// at the end of each block, and issue warnings for thread safety violations.
2591/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002592void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002593 ThreadSafetyHandler &Handler) {
2594 ThreadSafetyAnalyzer Analyzer(Handler);
2595 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002596}
2597
2598/// \brief Helper function that returns a LockKind required for the given level
2599/// of access.
2600LockKind getLockKindFromAccessKind(AccessKind AK) {
2601 switch (AK) {
2602 case AK_Read :
2603 return LK_Shared;
2604 case AK_Written :
2605 return LK_Exclusive;
2606 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002607 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002608}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002609
Caitlin Sadowski33208342011-09-09 16:11:56 +00002610}} // end namespace clang::thread_safety