blob: b6a73bd2d891c0956f705c12ec98aa9599b3a4e4 [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//
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000013// See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
Aaron Ballmanfcd5b7e2013-06-26 19:17:19 +000014// for more information.
Caitlin Sadowski33208342011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Analysis/Analyses/PostOrderCFGView.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000024#include "clang/Analysis/Analyses/ThreadSafety.h"
25#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000026#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000027#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Analysis/AnalysisContext.h"
29#include "clang/Analysis/CFG.h"
30#include "clang/Analysis/CFGStmtMap.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000031#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000032#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/SourceManager.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000034#include "llvm/ADT/BitVector.h"
35#include "llvm/ADT/FoldingSet.h"
36#include "llvm/ADT/ImmutableMap.h"
37#include "llvm/ADT/PostOrderIterator.h"
38#include "llvm/ADT/SmallVector.h"
39#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000040#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000041#include <algorithm>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000042#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000043#include <vector>
44
45using namespace clang;
46using namespace thread_safety;
47
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000048// Key method definition
49ThreadSafetyHandler::~ThreadSafetyHandler() {}
50
Caitlin Sadowski33208342011-09-09 16:11:56 +000051namespace {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +000052
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000053/// SExpr implements a simple expression language that is used to store,
54/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
55/// does not capture surface syntax, and it does not distinguish between
56/// C++ concepts, like pointers and references, that have no real semantic
57/// differences. This simplicity allows SExprs to be meaningfully compared,
58/// e.g.
59/// (x) = x
60/// (*this).foo = this->foo
61/// *&a = a
Caitlin Sadowski33208342011-09-09 16:11:56 +000062///
63/// Thread-safety analysis works by comparing lock expressions. Within the
64/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
65/// a particular mutex object at run-time. Subsequent occurrences of the same
66/// expression (where "same" means syntactic equality) will refer to the same
67/// run-time object if three conditions hold:
68/// (1) Local variables in the expression, such as "x" have not changed.
69/// (2) Values on the heap that affect the expression have not changed.
70/// (3) The expression involves only pure function calls.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +000071///
Caitlin Sadowski33208342011-09-09 16:11:56 +000072/// The current implementation assumes, but does not verify, that multiple uses
73/// of the same lock expression satisfies these criteria.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000074class SExpr {
75private:
76 enum ExprOp {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +000077 EOP_Nop, ///< No-op
78 EOP_Wildcard, ///< Matches anything.
79 EOP_Universal, ///< Universal lock.
80 EOP_This, ///< This keyword.
81 EOP_NVar, ///< Named variable.
82 EOP_LVar, ///< Local variable.
83 EOP_Dot, ///< Field access
84 EOP_Call, ///< Function call
85 EOP_MCall, ///< Method call
86 EOP_Index, ///< Array index
87 EOP_Unary, ///< Unary operation
88 EOP_Binary, ///< Binary operation
89 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000090 };
91
92
93 class SExprNode {
94 private:
Ted Kremenek78094ca2012-08-22 23:50:41 +000095 unsigned char Op; ///< Opcode of the root node
96 unsigned char Flags; ///< Additional opcode-specific data
97 unsigned short Sz; ///< Number of child nodes
98 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000099
100 public:
101 SExprNode(ExprOp O, unsigned F, const void* D)
102 : Op(static_cast<unsigned char>(O)),
103 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
104 { }
105
106 unsigned size() const { return Sz; }
107 void setSize(unsigned S) { Sz = S; }
108
109 ExprOp kind() const { return static_cast<ExprOp>(Op); }
110
111 const NamedDecl* getNamedDecl() const {
112 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
113 return reinterpret_cast<const NamedDecl*>(Data);
114 }
115
116 const NamedDecl* getFunctionDecl() const {
117 assert(Op == EOP_Call || Op == EOP_MCall);
118 return reinterpret_cast<const NamedDecl*>(Data);
119 }
120
121 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
122 void setArrow(bool A) { Flags = A ? 1 : 0; }
123
124 unsigned arity() const {
125 switch (Op) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000126 case EOP_Nop: return 0;
127 case EOP_Wildcard: return 0;
128 case EOP_Universal: return 0;
129 case EOP_NVar: return 0;
130 case EOP_LVar: return 0;
131 case EOP_This: return 0;
132 case EOP_Dot: return 1;
133 case EOP_Call: return Flags+1; // First arg is function.
134 case EOP_MCall: return Flags+1; // First arg is implicit obj.
135 case EOP_Index: return 2;
136 case EOP_Unary: return 1;
137 case EOP_Binary: return 2;
138 case EOP_Unknown: return Flags;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000139 }
140 return 0;
141 }
142
143 bool operator==(const SExprNode& Other) const {
144 // Ignore flags and size -- they don't matter.
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000145 return (Op == Other.Op &&
146 Data == Other.Data);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000147 }
148
149 bool operator!=(const SExprNode& Other) const {
150 return !(*this == Other);
151 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000152
153 bool matches(const SExprNode& Other) const {
154 return (*this == Other) ||
155 (Op == EOP_Wildcard) ||
156 (Other.Op == EOP_Wildcard);
157 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000158 };
159
Caitlin Sadowski33208342011-09-09 16:11:56 +0000160
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000161 /// \brief Encapsulates the lexical context of a function call. The lexical
162 /// context includes the arguments to the call, including the implicit object
163 /// argument. When an attribute containing a mutex expression is attached to
164 /// a method, the expression may refer to formal parameters of the method.
165 /// Actual arguments must be substituted for formal parameters to derive
166 /// the appropriate mutex expression in the lexical context where the function
167 /// is called. PrevCtx holds the context in which the arguments themselves
168 /// should be evaluated; multiple calling contexts can be chained together
169 /// by the lock_returned attribute.
170 struct CallingContext {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000171 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
172 const Expr* SelfArg; // Implicit object argument -- e.g. 'this'
173 bool SelfArrow; // is Self referred to with -> or .?
174 unsigned NumArgs; // Number of funArgs
175 const Expr* const* FunArgs; // Function arguments
176 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000177
Aaron Ballman69bb5922014-03-06 19:37:24 +0000178 CallingContext(const NamedDecl *D)
179 : AttrDecl(D), SelfArg(0), SelfArrow(false), NumArgs(0), FunArgs(0),
180 PrevCtx(0) {}
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000181 };
182
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000183 typedef SmallVector<SExprNode, 4> NodeVector;
184
185private:
186 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
187 // the list to be traversed as a tree.
188 NodeVector NodeVec;
189
190private:
Aaron Ballman19842c42014-03-06 19:25:11 +0000191 unsigned make(ExprOp O, unsigned F = 0, const void *D = 0) {
192 NodeVec.push_back(SExprNode(O, F, D));
193 return NodeVec.size() - 1;
194 }
195
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000196 unsigned makeNop() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000197 return make(EOP_Nop);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000198 }
199
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000200 unsigned makeWildcard() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000201 return make(EOP_Wildcard);
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000202 }
203
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000204 unsigned makeUniversal() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000205 return make(EOP_Universal);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000206 }
207
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000208 unsigned makeNamedVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000209 return make(EOP_NVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000210 }
211
212 unsigned makeLocalVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000213 return make(EOP_LVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000214 }
215
216 unsigned makeThis() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000217 return make(EOP_This);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000218 }
219
220 unsigned makeDot(const NamedDecl *D, bool Arrow) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000221 return make(EOP_Dot, Arrow ? 1 : 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000222 }
223
224 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000225 return make(EOP_Call, NumArgs, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000226 }
227
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000228 // Grab the very first declaration of virtual method D
229 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
230 while (true) {
231 D = D->getCanonicalDecl();
232 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
233 E = D->end_overridden_methods();
234 if (I == E)
235 return D; // Method does not override anything
236 D = *I; // FIXME: this does not work with multiple inheritance.
237 }
238 return 0;
239 }
240
241 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000242 return make(EOP_MCall, NumArgs, getFirstVirtualDecl(D));
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000243 }
244
245 unsigned makeIndex() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000246 return make(EOP_Index);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000247 }
248
249 unsigned makeUnary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000250 return make(EOP_Unary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000251 }
252
253 unsigned makeBinary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000254 return make(EOP_Binary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000255 }
256
257 unsigned makeUnknown(unsigned Arity) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000258 return make(EOP_Unknown, Arity);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000259 }
260
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000261 inline bool isCalleeArrow(const Expr *E) {
262 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
263 return ME ? ME->isArrow() : false;
264 }
265
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000266 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000267 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000268 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000269 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000270 ///
271 /// NDeref returns the number of Derefence and AddressOf operations
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000272 /// preceding the Expr; this is used to decide whether to pretty-print
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000273 /// SExprs with . or ->.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000274 unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx,
275 int* NDeref = 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000276 if (!Exp)
277 return 0;
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000278
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000279 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
280 const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
281 const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000282 if (PV) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000283 const FunctionDecl *FD =
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000284 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
285 unsigned i = PV->getFunctionScopeIndex();
286
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000287 if (CallCtx && CallCtx->FunArgs &&
288 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000289 // Substitute call arguments for references to function parameters
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000290 assert(i < CallCtx->NumArgs);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000291 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000292 }
293 // Map the param back to the param of the original function declaration.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000294 makeNamedVar(FD->getParamDecl(i));
295 return 1;
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000296 }
297 // Not a function parameter -- just store the reference.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000298 makeNamedVar(ND);
299 return 1;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000300 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000301 // Substitute parent for 'this'
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000302 if (CallCtx && CallCtx->SelfArg) {
303 if (!CallCtx->SelfArrow && NDeref)
304 // 'this' is a pointer, but self is not, so need to take address.
305 --(*NDeref);
306 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
307 }
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000308 else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000309 makeThis();
310 return 1;
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000311 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000312 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
313 const NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000314 int ImplicitDeref = ME->isArrow() ? 1 : 0;
315 unsigned Root = makeDot(ND, false);
316 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
317 NodeVec[Root].setArrow(ImplicitDeref > 0);
318 NodeVec[Root].setSize(Sz + 1);
319 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000320 } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000321 // When calling a function with a lock_returned attribute, replace
322 // the function call with the expression in lock_returned.
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000323 const CXXMethodDecl *MD = CMCE->getMethodDecl()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000324 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000325 CallingContext LRCallCtx(CMCE->getMethodDecl());
326 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000327 LRCallCtx.SelfArrow = isCalleeArrow(CMCE->getCallee());
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000328 LRCallCtx.NumArgs = CMCE->getNumArgs();
329 LRCallCtx.FunArgs = CMCE->getArgs();
330 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000331 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000332 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000333 // Hack to treat smart pointers and iterators as pointers;
334 // ignore any method named get().
335 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
336 CMCE->getNumArgs() == 0) {
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000337 if (NDeref && isCalleeArrow(CMCE->getCallee()))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000338 ++(*NDeref);
339 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000340 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000341 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000342 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000343 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000344 const Expr* const* CallArgs = CMCE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000345 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000346 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000347 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000348 NodeVec[Root].setSize(Sz + 1);
349 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000350 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000351 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000352 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000353 CallingContext LRCallCtx(CE->getDirectCallee());
354 LRCallCtx.NumArgs = CE->getNumArgs();
355 LRCallCtx.FunArgs = CE->getArgs();
356 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000357 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000358 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000359 // Treat smart pointers and iterators as pointers;
360 // ignore the * and -> operators.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000361 if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000362 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000363 if (k == OO_Star) {
364 if (NDeref) ++(*NDeref);
365 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
366 }
367 else if (k == OO_Arrow) {
368 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000369 }
370 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000371 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000372 unsigned Root = makeCall(NumCallArgs, 0);
373 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000374 const Expr* const* CallArgs = CE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000375 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000376 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000377 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000378 NodeVec[Root].setSize(Sz+1);
379 return Sz+1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000380 } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000381 unsigned Root = makeBinary();
382 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
383 Sz += buildSExpr(BOE->getRHS(), CallCtx);
384 NodeVec[Root].setSize(Sz);
385 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000386 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000387 // Ignore & and * operators -- they're no-ops.
388 // However, we try to figure out whether the expression is a pointer,
389 // so we can use . and -> appropriately in error messages.
390 if (UOE->getOpcode() == UO_Deref) {
391 if (NDeref) ++(*NDeref);
392 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
393 }
394 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000395 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
396 if (DRE->getDecl()->isCXXInstanceMember()) {
397 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
398 // We interpret this syntax specially, as a wildcard.
399 unsigned Root = makeDot(DRE->getDecl(), false);
400 makeWildcard();
401 NodeVec[Root].setSize(2);
402 return 2;
403 }
404 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000405 if (NDeref) --(*NDeref);
406 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
407 }
408 unsigned Root = makeUnary();
409 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
410 NodeVec[Root].setSize(Sz);
411 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000412 } else if (const ArraySubscriptExpr *ASE =
413 dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000414 unsigned Root = makeIndex();
415 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
416 Sz += buildSExpr(ASE->getIdx(), CallCtx);
417 NodeVec[Root].setSize(Sz);
418 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000419 } else if (const AbstractConditionalOperator *CE =
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000420 dyn_cast<AbstractConditionalOperator>(Exp)) {
421 unsigned Root = makeUnknown(3);
422 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
423 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
424 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
425 NodeVec[Root].setSize(Sz);
426 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000427 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000428 unsigned Root = makeUnknown(3);
429 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
430 Sz += buildSExpr(CE->getLHS(), CallCtx);
431 Sz += buildSExpr(CE->getRHS(), CallCtx);
432 NodeVec[Root].setSize(Sz);
433 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000434 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000435 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000436 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000437 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000438 } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000439 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000440 } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000441 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000442 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins0c1da202012-07-03 18:25:56 +0000443 isa<CXXNullPtrLiteralExpr>(Exp) ||
444 isa<GNUNullExpr>(Exp) ||
445 isa<CXXBoolLiteralExpr>(Exp) ||
446 isa<FloatingLiteral>(Exp) ||
447 isa<ImaginaryLiteral>(Exp) ||
448 isa<IntegerLiteral>(Exp) ||
449 isa<StringLiteral>(Exp) ||
450 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000451 makeNop();
452 return 1; // FIXME: Ignore literals for now
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000453 } else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000454 makeNop();
455 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000456 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000457 }
458
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000459 /// \brief Construct a SExpr from an expression.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000460 /// \param MutexExp The original mutex expression within an attribute
461 /// \param DeclExp An expression involving the Decl on which the attribute
462 /// occurs.
463 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000464 void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp,
465 const NamedDecl *D, VarDecl *SelfDecl = 0) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000466 CallingContext CallCtx(D);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000467
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000468 if (MutexExp) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000469 if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000470 if (SLit->getString() == StringRef("*"))
471 // The "*" expr is a universal lock, which essentially turns off
472 // checks until it is removed from the lockset.
473 makeUniversal();
474 else
475 // Ignore other string literals for now.
476 makeNop();
477 return;
478 }
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000479 }
480
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000481 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000482 if (DeclExp == 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000483 buildSExpr(MutexExp, 0);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000484 return;
485 }
486
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000487 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000488 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000489 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000490 CallCtx.SelfArg = ME->getBase();
491 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000492 } else if (const CXXMemberCallExpr *CE =
493 dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000494 CallCtx.SelfArg = CE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000495 CallCtx.SelfArrow = isCalleeArrow(CE->getCallee());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000496 CallCtx.NumArgs = CE->getNumArgs();
497 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000498 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000499 CallCtx.NumArgs = CE->getNumArgs();
500 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000501 } else if (const CXXConstructExpr *CE =
502 dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000503 CallCtx.SelfArg = 0; // Will be set below
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000504 CallCtx.NumArgs = CE->getNumArgs();
505 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +0000506 } else if (D && isa<CXXDestructorDecl>(D)) {
507 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000508 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000509 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000510
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000511 // Hack to handle constructors, where self cannot be recovered from
512 // the expression.
513 if (SelfDecl && !CallCtx.SelfArg) {
514 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
515 SelfDecl->getLocation());
516 CallCtx.SelfArg = &SelfDRE;
517
518 // If the attribute has no arguments, then assume the argument is "this".
519 if (MutexExp == 0)
520 buildSExpr(CallCtx.SelfArg, 0);
521 else // For most attributes.
522 buildSExpr(MutexExp, &CallCtx);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000523 return;
524 }
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000525
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000526 // If the attribute has no arguments, then assume the argument is "this".
527 if (MutexExp == 0)
528 buildSExpr(CallCtx.SelfArg, 0);
529 else // For most attributes.
530 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski33208342011-09-09 16:11:56 +0000531 }
532
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000533 /// \brief Get index of next sibling of node i.
534 unsigned getNextSibling(unsigned i) const {
535 return i + NodeVec[i].size();
536 }
537
Caitlin Sadowski33208342011-09-09 16:11:56 +0000538public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000539 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000540
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000541 /// \param MutexExp The original mutex expression within an attribute
542 /// \param DeclExp An expression involving the Decl on which the attribute
543 /// occurs.
544 /// \param D The declaration to which the lock/unlock attribute is attached.
545 /// Caller must check isValid() after construction.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000546 SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000547 VarDecl *SelfDecl=0) {
548 buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000549 }
550
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000551 /// Return true if this is a valid decl sequence.
552 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000553 bool isValid() const {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000554 return !NodeVec.empty();
Caitlin Sadowski33208342011-09-09 16:11:56 +0000555 }
556
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000557 bool shouldIgnore() const {
558 // Nop is a mutex that we have decided to deliberately ignore.
559 assert(NodeVec.size() > 0 && "Invalid Mutex");
560 return NodeVec[0].kind() == EOP_Nop;
561 }
562
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000563 bool isUniversal() const {
564 assert(NodeVec.size() > 0 && "Invalid Mutex");
565 return NodeVec[0].kind() == EOP_Universal;
566 }
567
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000568 /// Issue a warning about an invalid lock expression
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000569 static void warnInvalidLock(ThreadSafetyHandler &Handler,
Aaron Ballmane0449042014-04-01 21:43:23 +0000570 const Expr *MutexExp, const Expr *DeclExp,
571 const NamedDecl *D, StringRef Kind) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000572 SourceLocation Loc;
573 if (DeclExp)
574 Loc = DeclExp->getExprLoc();
575
576 // FIXME: add a note about the attribute location in MutexExp or D
577 if (Loc.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +0000578 Handler.handleInvalidLockExp(Kind, Loc);
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000579 }
580
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000581 bool operator==(const SExpr &other) const {
582 return NodeVec == other.NodeVec;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000583 }
584
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000585 bool operator!=(const SExpr &other) const {
Caitlin Sadowski33208342011-09-09 16:11:56 +0000586 return !(*this == other);
587 }
588
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000589 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
590 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchins138568b2012-09-11 23:04:49 +0000591 unsigned ni = NodeVec[i].arity();
592 unsigned nj = Other.NodeVec[j].arity();
593 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000594 bool Result = true;
595 unsigned ci = i+1; // first child of i
596 unsigned cj = j+1; // first child of j
597 for (unsigned k = 0; k < n;
598 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
599 Result = Result && matches(Other, ci, cj);
600 }
601 return Result;
602 }
603 return false;
604 }
605
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000606 // A partial match between a.mu and b.mu returns true a and b have the same
607 // type (and thus mu refers to the same mutex declaration), regardless of
608 // whether a and b are different objects or not.
609 bool partiallyMatches(const SExpr &Other) const {
610 if (NodeVec[0].kind() == EOP_Dot)
611 return NodeVec[0].matches(Other.NodeVec[0]);
612 return false;
613 }
614
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000615 /// \brief Pretty print a lock expression for use in error messages.
616 std::string toString(unsigned i = 0) const {
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000617 assert(isValid());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000618 if (i >= NodeVec.size())
619 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000620
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000621 const SExprNode* N = &NodeVec[i];
622 switch (N->kind()) {
623 case EOP_Nop:
624 return "_";
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000625 case EOP_Wildcard:
626 return "(?)";
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000627 case EOP_Universal:
628 return "*";
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000629 case EOP_This:
630 return "this";
631 case EOP_NVar:
632 case EOP_LVar: {
633 return N->getNamedDecl()->getNameAsString();
634 }
635 case EOP_Dot: {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000636 if (NodeVec[i+1].kind() == EOP_Wildcard) {
637 std::string S = "&";
638 S += N->getNamedDecl()->getQualifiedNameAsString();
639 return S;
640 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000641 std::string FieldName = N->getNamedDecl()->getNameAsString();
642 if (NodeVec[i+1].kind() == EOP_This)
643 return FieldName;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000644
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000645 std::string S = toString(i+1);
646 if (N->isArrow())
647 return S + "->" + FieldName;
648 else
649 return S + "." + FieldName;
650 }
651 case EOP_Call: {
652 std::string S = toString(i+1) + "(";
653 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000654 unsigned ci = getNextSibling(i+1);
655 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000656 S += toString(ci);
657 if (k+1 < NumArgs) S += ",";
658 }
659 S += ")";
660 return S;
661 }
662 case EOP_MCall: {
663 std::string S = "";
664 if (NodeVec[i+1].kind() != EOP_This)
665 S = toString(i+1) + ".";
666 if (const NamedDecl *D = N->getFunctionDecl())
667 S += D->getNameAsString() + "(";
668 else
669 S += "#(";
670 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000671 unsigned ci = getNextSibling(i+1);
672 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000673 S += toString(ci);
674 if (k+1 < NumArgs) S += ",";
675 }
676 S += ")";
677 return S;
678 }
679 case EOP_Index: {
680 std::string S1 = toString(i+1);
681 std::string S2 = toString(i+1 + NodeVec[i+1].size());
682 return S1 + "[" + S2 + "]";
683 }
684 case EOP_Unary: {
685 std::string S = toString(i+1);
686 return "#" + S;
687 }
688 case EOP_Binary: {
689 std::string S1 = toString(i+1);
690 std::string S2 = toString(i+1 + NodeVec[i+1].size());
691 return "(" + S1 + "#" + S2 + ")";
692 }
693 case EOP_Unknown: {
694 unsigned NumChildren = N->arity();
695 if (NumChildren == 0)
696 return "(...)";
697 std::string S = "(";
698 unsigned ci = i+1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000699 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000700 S += toString(ci);
701 if (j+1 < NumChildren) S += "#";
702 }
703 S += ")";
704 return S;
705 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000706 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000707 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000708 }
709};
710
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000711/// \brief A short list of SExprs
712class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000713public:
Aaron Ballmancea26092014-03-06 19:10:16 +0000714 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000715 void push_back_nodup(const SExpr& M) {
Aaron Ballmancea26092014-03-06 19:10:16 +0000716 if (end() == std::find(begin(), end(), M))
717 push_back(M);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000718 }
719};
720
Caitlin Sadowski33208342011-09-09 16:11:56 +0000721/// \brief This is a helper class that stores info about the most recent
722/// accquire of a Lock.
723///
724/// The main body of the analysis maps MutexIDs to LockDatas.
725struct LockData {
726 SourceLocation AcquireLoc;
727
728 /// \brief LKind stores whether a lock is held shared or exclusively.
729 /// Note that this analysis does not currently support either re-entrant
730 /// locking or lock "upgrading" and "downgrading" between exclusive and
731 /// shared.
732 ///
733 /// FIXME: add support for re-entrant locking and lock up/downgrading
734 LockKind LKind;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000735 bool Asserted; // for asserted locks
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000736 bool Managed; // for ScopedLockable objects
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000737 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski33208342011-09-09 16:11:56 +0000738
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000739 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false,
740 bool Asrt=false)
741 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000742 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000743 {}
744
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000745 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000746 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000747 UnderlyingMutex(Mu)
748 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000749
750 bool operator==(const LockData &other) const {
751 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
752 }
753
754 bool operator!=(const LockData &other) const {
755 return !(*this == other);
756 }
757
758 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000759 ID.AddInteger(AcquireLoc.getRawEncoding());
760 ID.AddInteger(LKind);
761 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000762
763 bool isAtLeast(LockKind LK) {
764 return (LK == LK_Shared) || (LKind == LK_Exclusive);
765 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000766};
767
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000768
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000769/// \brief A FactEntry stores a single fact that is known at a particular point
770/// in the program execution. Currently, this is information regarding a lock
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000771/// that is held at that point.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000772struct FactEntry {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000773 SExpr MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000774 LockData LDat;
775
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000776 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000777 : MutID(M), LDat(L)
778 { }
779};
780
781
782typedef unsigned short FactID;
783
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000784/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000785/// the analysis of a single routine.
786class FactManager {
787private:
788 std::vector<FactEntry> Facts;
789
790public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000791 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000792 Facts.push_back(FactEntry(M,L));
793 return static_cast<unsigned short>(Facts.size() - 1);
794 }
795
796 const FactEntry& operator[](FactID F) const { return Facts[F]; }
797 FactEntry& operator[](FactID F) { return Facts[F]; }
798};
799
800
801/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000802/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000803/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000804/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000805/// locks, so we can get away with doing a linear search for lookup. Note
806/// that a hashtable or map is inappropriate in this case, because lookups
807/// may involve partial pattern matches, rather than exact matches.
808class FactSet {
809private:
810 typedef SmallVector<FactID, 4> FactVec;
811
812 FactVec FactIDs;
813
814public:
815 typedef FactVec::iterator iterator;
816 typedef FactVec::const_iterator const_iterator;
817
818 iterator begin() { return FactIDs.begin(); }
819 const_iterator begin() const { return FactIDs.begin(); }
820
821 iterator end() { return FactIDs.end(); }
822 const_iterator end() const { return FactIDs.end(); }
823
824 bool isEmpty() const { return FactIDs.size() == 0; }
825
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000826 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000827 FactID F = FM.newLock(M, L);
828 FactIDs.push_back(F);
829 return F;
830 }
831
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000832 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000833 unsigned n = FactIDs.size();
834 if (n == 0)
835 return false;
836
837 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000838 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000839 FactIDs[i] = FactIDs[n-1];
840 FactIDs.pop_back();
841 return true;
842 }
843 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000844 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000845 FactIDs.pop_back();
846 return true;
847 }
848 return false;
849 }
850
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000851 // Returns an iterator
852 iterator findLockIter(FactManager &FM, const SExpr &M) {
853 for (iterator I = begin(), E = end(); I != E; ++I) {
854 const SExpr &Exp = FM[*I].MutID;
855 if (Exp.matches(M))
856 return I;
857 }
858 return end();
859 }
860
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000861 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000862 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000863 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000864 if (Exp.matches(M))
865 return &FM[*I].LDat;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000866 }
867 return 0;
868 }
869
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000870 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000871 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000872 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000873 if (Exp.matches(M) || Exp.isUniversal())
874 return &FM[*I].LDat;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000875 }
876 return 0;
877 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000878
879 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
880 for (const_iterator I=begin(), E=end(); I != E; ++I) {
881 const SExpr& Exp = FM[*I].MutID;
882 if (Exp.partiallyMatches(M)) return &FM[*I];
883 }
884 return 0;
885 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000886};
887
888
889
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000890/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski33208342011-09-09 16:11:56 +0000891/// been locked.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000892typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000893typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000894
895class LocalVariableMap;
896
Richard Smith92286672012-02-03 04:45:26 +0000897/// A side (entry or exit) of a CFG node.
898enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000899
900/// CFGBlockInfo is a struct which contains all the information that is
901/// maintained for each block in the CFG. See LocalVariableMap for more
902/// information about the contexts.
903struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000904 FactSet EntrySet; // Lockset held at entry to block
905 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000906 LocalVarContext EntryContext; // Context held at entry to block
907 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000908 SourceLocation EntryLoc; // Location of first statement in block
909 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000910 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000911 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000912
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000913 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000914 return Side == CBS_Entry ? EntrySet : ExitSet;
915 }
916 SourceLocation getLocation(CFGBlockSide Side) const {
917 return Side == CBS_Entry ? EntryLoc : ExitLoc;
918 }
919
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000920private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000921 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000922 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000923 { }
924
925public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000926 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000927};
928
929
930
931// A LocalVariableMap maintains a map from local variables to their currently
932// valid definitions. It provides SSA-like functionality when traversing the
933// CFG. Like SSA, each definition or assignment to a variable is assigned a
934// unique name (an integer), which acts as the SSA name for that definition.
935// The total set of names is shared among all CFG basic blocks.
936// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
937// with their SSA-names. Instead, we compute a Context for each point in the
938// code, which maps local variables to the appropriate SSA-name. This map
939// changes with each assignment.
940//
941// The map is computed in a single pass over the CFG. Subsequent analyses can
942// then query the map to find the appropriate Context for a statement, and use
943// that Context to look up the definitions of variables.
944class LocalVariableMap {
945public:
946 typedef LocalVarContext Context;
947
948 /// A VarDefinition consists of an expression, representing the value of the
949 /// variable, along with the context in which that expression should be
950 /// interpreted. A reference VarDefinition does not itself contain this
951 /// information, but instead contains a pointer to a previous VarDefinition.
952 struct VarDefinition {
953 public:
954 friend class LocalVariableMap;
955
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000956 const NamedDecl *Dec; // The original declaration for this variable.
957 const Expr *Exp; // The expression for this variable, OR
958 unsigned Ref; // Reference to another VarDefinition
959 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000960
961 bool isReference() { return !Exp; }
962
963 private:
964 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000965 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000966 : Dec(D), Exp(E), Ref(0), Ctx(C)
967 { }
968
969 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000970 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000971 : Dec(D), Exp(0), Ref(R), Ctx(C)
972 { }
973 };
974
975private:
976 Context::Factory ContextFactory;
977 std::vector<VarDefinition> VarDefinitions;
978 std::vector<unsigned> CtxIndices;
979 std::vector<std::pair<Stmt*, Context> > SavedContexts;
980
981public:
982 LocalVariableMap() {
983 // index 0 is a placeholder for undefined variables (aka phi-nodes).
984 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
985 }
986
987 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000988 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000989 const unsigned *i = Ctx.lookup(D);
990 if (!i)
991 return 0;
992 assert(*i < VarDefinitions.size());
993 return &VarDefinitions[*i];
994 }
995
996 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000997 /// NULL if the expression is not statically known. If successful, also
998 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000999 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001000 const unsigned *P = Ctx.lookup(D);
1001 if (!P)
1002 return 0;
1003
1004 unsigned i = *P;
1005 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001006 if (VarDefinitions[i].Exp) {
1007 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001008 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001009 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001010 i = VarDefinitions[i].Ref;
1011 }
1012 return 0;
1013 }
1014
1015 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1016
1017 /// Return the next context after processing S. This function is used by
1018 /// clients of the class to get the appropriate context when traversing the
1019 /// CFG. It must be called for every assignment or DeclStmt.
1020 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1021 if (SavedContexts[CtxIndex+1].first == S) {
1022 CtxIndex++;
1023 Context Result = SavedContexts[CtxIndex].second;
1024 return Result;
1025 }
1026 return C;
1027 }
1028
1029 void dumpVarDefinitionName(unsigned i) {
1030 if (i == 0) {
1031 llvm::errs() << "Undefined";
1032 return;
1033 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001034 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001035 if (!Dec) {
1036 llvm::errs() << "<<NULL>>";
1037 return;
1038 }
1039 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +00001040 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001041 }
1042
1043 /// Dumps an ASCII representation of the variable map to llvm::errs()
1044 void dump() {
1045 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001046 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001047 unsigned Ref = VarDefinitions[i].Ref;
1048
1049 dumpVarDefinitionName(i);
1050 llvm::errs() << " = ";
1051 if (Exp) Exp->dump();
1052 else {
1053 dumpVarDefinitionName(Ref);
1054 llvm::errs() << "\n";
1055 }
1056 }
1057 }
1058
1059 /// Dumps an ASCII representation of a Context to llvm::errs()
1060 void dumpContext(Context C) {
1061 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001062 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001063 D->printName(llvm::errs());
1064 const unsigned *i = C.lookup(D);
1065 llvm::errs() << " -> ";
1066 dumpVarDefinitionName(*i);
1067 llvm::errs() << "\n";
1068 }
1069 }
1070
1071 /// Builds the variable map.
1072 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1073 std::vector<CFGBlockInfo> &BlockInfo);
1074
1075protected:
1076 // Get the current context index
1077 unsigned getContextIndex() { return SavedContexts.size()-1; }
1078
1079 // Save the current context for later replay
1080 void saveContext(Stmt *S, Context C) {
1081 SavedContexts.push_back(std::make_pair(S,C));
1082 }
1083
1084 // Adds a new definition to the given context, and returns a new context.
1085 // This method should be called when declaring a new variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001086 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001087 assert(!Ctx.contains(D));
1088 unsigned newID = VarDefinitions.size();
1089 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1090 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1091 return NewCtx;
1092 }
1093
1094 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001095 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001096 unsigned newID = VarDefinitions.size();
1097 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1098 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1099 return NewCtx;
1100 }
1101
1102 // Updates a definition only if that definition is already in the map.
1103 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001104 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001105 if (Ctx.contains(D)) {
1106 unsigned newID = VarDefinitions.size();
1107 Context NewCtx = ContextFactory.remove(Ctx, D);
1108 NewCtx = ContextFactory.add(NewCtx, D, newID);
1109 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1110 return NewCtx;
1111 }
1112 return Ctx;
1113 }
1114
1115 // Removes a definition from the context, but keeps the variable name
1116 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001117 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001118 Context NewCtx = Ctx;
1119 if (NewCtx.contains(D)) {
1120 NewCtx = ContextFactory.remove(NewCtx, D);
1121 NewCtx = ContextFactory.add(NewCtx, D, 0);
1122 }
1123 return NewCtx;
1124 }
1125
1126 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001127 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001128 Context NewCtx = Ctx;
1129 if (NewCtx.contains(D)) {
1130 NewCtx = ContextFactory.remove(NewCtx, D);
1131 }
1132 return NewCtx;
1133 }
1134
1135 Context intersectContexts(Context C1, Context C2);
1136 Context createReferenceContext(Context C);
1137 void intersectBackEdge(Context C1, Context C2);
1138
1139 friend class VarMapBuilder;
1140};
1141
1142
1143// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001144CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1145 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001146}
1147
1148
1149/// Visitor which builds a LocalVariableMap
1150class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1151public:
1152 LocalVariableMap* VMap;
1153 LocalVariableMap::Context Ctx;
1154
1155 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1156 : VMap(VM), Ctx(C) {}
1157
1158 void VisitDeclStmt(DeclStmt *S);
1159 void VisitBinaryOperator(BinaryOperator *BO);
1160};
1161
1162
1163// Add new local variables to the variable map
1164void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1165 bool modifiedCtx = false;
1166 DeclGroupRef DGrp = S->getDeclGroup();
1167 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1168 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1169 Expr *E = VD->getInit();
1170
1171 // Add local variables with trivial type to the variable map
1172 QualType T = VD->getType();
1173 if (T.isTrivialType(VD->getASTContext())) {
1174 Ctx = VMap->addDefinition(VD, E, Ctx);
1175 modifiedCtx = true;
1176 }
1177 }
1178 }
1179 if (modifiedCtx)
1180 VMap->saveContext(S, Ctx);
1181}
1182
1183// Update local variable definitions in variable map
1184void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1185 if (!BO->isAssignmentOp())
1186 return;
1187
1188 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1189
1190 // Update the variable map and current context.
1191 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1192 ValueDecl *VDec = DRE->getDecl();
1193 if (Ctx.lookup(VDec)) {
1194 if (BO->getOpcode() == BO_Assign)
1195 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1196 else
1197 // FIXME -- handle compound assignment operators
1198 Ctx = VMap->clearDefinition(VDec, Ctx);
1199 VMap->saveContext(BO, Ctx);
1200 }
1201 }
1202}
1203
1204
1205// Computes the intersection of two contexts. The intersection is the
1206// set of variables which have the same definition in both contexts;
1207// variables with different definitions are discarded.
1208LocalVariableMap::Context
1209LocalVariableMap::intersectContexts(Context C1, Context C2) {
1210 Context Result = C1;
1211 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001212 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001213 unsigned i1 = I.getData();
1214 const unsigned *i2 = C2.lookup(Dec);
1215 if (!i2) // variable doesn't exist on second path
1216 Result = removeDefinition(Dec, Result);
1217 else if (*i2 != i1) // variable exists, but has different definition
1218 Result = clearDefinition(Dec, Result);
1219 }
1220 return Result;
1221}
1222
1223// For every variable in C, create a new variable that refers to the
1224// definition in C. Return a new context that contains these new variables.
1225// (We use this for a naive implementation of SSA on loop back-edges.)
1226LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1227 Context Result = getEmptyContext();
1228 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001229 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001230 unsigned i = I.getData();
1231 Result = addReference(Dec, i, Result);
1232 }
1233 return Result;
1234}
1235
1236// This routine also takes the intersection of C1 and C2, but it does so by
1237// altering the VarDefinitions. C1 must be the result of an earlier call to
1238// createReferenceContext.
1239void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1240 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001241 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001242 unsigned i1 = I.getData();
1243 VarDefinition *VDef = &VarDefinitions[i1];
1244 assert(VDef->isReference());
1245
1246 const unsigned *i2 = C2.lookup(Dec);
1247 if (!i2 || (*i2 != i1))
1248 VDef->Ref = 0; // Mark this variable as undefined
1249 }
1250}
1251
1252
1253// Traverse the CFG in topological order, so all predecessors of a block
1254// (excluding back-edges) are visited before the block itself. At
1255// each point in the code, we calculate a Context, which holds the set of
1256// variable definitions which are visible at that point in execution.
1257// Visible variables are mapped to their definitions using an array that
1258// contains all definitions.
1259//
1260// At join points in the CFG, the set is computed as the intersection of
1261// the incoming sets along each edge, E.g.
1262//
1263// { Context | VarDefinitions }
1264// int x = 0; { x -> x1 | x1 = 0 }
1265// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1266// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1267// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1268// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1269//
1270// This is essentially a simpler and more naive version of the standard SSA
1271// algorithm. Those definitions that remain in the intersection are from blocks
1272// that strictly dominate the current block. We do not bother to insert proper
1273// phi nodes, because they are not used in our analysis; instead, wherever
1274// a phi node would be required, we simply remove that definition from the
1275// context (E.g. x above).
1276//
1277// The initial traversal does not capture back-edges, so those need to be
1278// handled on a separate pass. Whenever the first pass encounters an
1279// incoming back edge, it duplicates the context, creating new definitions
1280// that refer back to the originals. (These correspond to places where SSA
1281// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001282// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001283// node was actually required.) E.g.
1284//
1285// { Context | VarDefinitions }
1286// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1287// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1288// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1289// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1290//
1291void LocalVariableMap::traverseCFG(CFG *CFGraph,
1292 PostOrderCFGView *SortedGraph,
1293 std::vector<CFGBlockInfo> &BlockInfo) {
1294 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1295
1296 CtxIndices.resize(CFGraph->getNumBlockIDs());
1297
1298 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1299 E = SortedGraph->end(); I!= E; ++I) {
1300 const CFGBlock *CurrBlock = *I;
1301 int CurrBlockID = CurrBlock->getBlockID();
1302 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1303
1304 VisitedBlocks.insert(CurrBlock);
1305
1306 // Calculate the entry context for the current block
1307 bool HasBackEdges = false;
1308 bool CtxInit = true;
1309 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1310 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1311 // if *PI -> CurrBlock is a back edge, so skip it
1312 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1313 HasBackEdges = true;
1314 continue;
1315 }
1316
1317 int PrevBlockID = (*PI)->getBlockID();
1318 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1319
1320 if (CtxInit) {
1321 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1322 CtxInit = false;
1323 }
1324 else {
1325 CurrBlockInfo->EntryContext =
1326 intersectContexts(CurrBlockInfo->EntryContext,
1327 PrevBlockInfo->ExitContext);
1328 }
1329 }
1330
1331 // Duplicate the context if we have back-edges, so we can call
1332 // intersectBackEdges later.
1333 if (HasBackEdges)
1334 CurrBlockInfo->EntryContext =
1335 createReferenceContext(CurrBlockInfo->EntryContext);
1336
1337 // Create a starting context index for the current block
1338 saveContext(0, CurrBlockInfo->EntryContext);
1339 CurrBlockInfo->EntryIndex = getContextIndex();
1340
1341 // Visit all the statements in the basic block.
1342 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1343 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1344 BE = CurrBlock->end(); BI != BE; ++BI) {
1345 switch (BI->getKind()) {
1346 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00001347 CFGStmt CS = BI->castAs<CFGStmt>();
1348 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001349 break;
1350 }
1351 default:
1352 break;
1353 }
1354 }
1355 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1356
1357 // Mark variables on back edges as "unknown" if they've been changed.
1358 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1359 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1360 // if CurrBlock -> *SI is *not* a back edge
1361 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1362 continue;
1363
1364 CFGBlock *FirstLoopBlock = *SI;
1365 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1366 Context LoopEnd = CurrBlockInfo->ExitContext;
1367 intersectBackEdge(LoopBegin, LoopEnd);
1368 }
1369 }
1370
1371 // Put an extra entry at the end of the indexed context array
1372 unsigned exitID = CFGraph->getExit().getBlockID();
1373 saveContext(0, BlockInfo[exitID].ExitContext);
1374}
1375
Richard Smith92286672012-02-03 04:45:26 +00001376/// Find the appropriate source locations to use when producing diagnostics for
1377/// each block in the CFG.
1378static void findBlockLocations(CFG *CFGraph,
1379 PostOrderCFGView *SortedGraph,
1380 std::vector<CFGBlockInfo> &BlockInfo) {
1381 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1382 E = SortedGraph->end(); I!= E; ++I) {
1383 const CFGBlock *CurrBlock = *I;
1384 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1385
1386 // Find the source location of the last statement in the block, if the
1387 // block is not empty.
1388 if (const Stmt *S = CurrBlock->getTerminator()) {
1389 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1390 } else {
1391 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1392 BE = CurrBlock->rend(); BI != BE; ++BI) {
1393 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001394 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1395 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001396 break;
1397 }
1398 }
1399 }
1400
1401 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1402 // This block contains at least one statement. Find the source location
1403 // of the first statement in the block.
1404 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1405 BE = CurrBlock->end(); BI != BE; ++BI) {
1406 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001407 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1408 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001409 break;
1410 }
1411 }
1412 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1413 CurrBlock != &CFGraph->getExit()) {
1414 // The block is empty, and has a single predecessor. Use its exit
1415 // location.
1416 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1417 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1418 }
1419 }
1420}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001421
1422/// \brief Class which implements the core thread safety analysis routines.
1423class ThreadSafetyAnalyzer {
1424 friend class BuildLockset;
1425
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001426 ThreadSafetyHandler &Handler;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001427 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001428 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001429 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001430
1431public:
1432 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1433
Aaron Ballmane0449042014-04-01 21:43:23 +00001434 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat,
1435 StringRef DiagKind);
1436 void removeLock(FactSet &FSet, const SExpr &Mutex, SourceLocation UnlockLoc,
1437 bool FullyRemove, LockKind Kind, StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001438
1439 template <typename AttrType>
1440 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001441 const NamedDecl *D, VarDecl *SelfDecl=0);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001442
1443 template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001444 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1445 const NamedDecl *D,
1446 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1447 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001448
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001449 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1450 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001451
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001452 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1453 const CFGBlock* PredBlock,
1454 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001455
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001456 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1457 SourceLocation JoinLoc,
1458 LockErrorKind LEK1, LockErrorKind LEK2,
1459 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001460
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001461 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1462 SourceLocation JoinLoc, LockErrorKind LEK1,
1463 bool Modify=true) {
1464 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001465 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001466
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001467 void runAnalysis(AnalysisDeclContext &AC);
1468};
1469
Aaron Ballmane0449042014-04-01 21:43:23 +00001470/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1471static const ValueDecl *getValueDecl(const Expr *Exp) {
1472 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1473 return getValueDecl(CE->getSubExpr());
1474
1475 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1476 return DR->getDecl();
1477
1478 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1479 return ME->getMemberDecl();
1480
1481 return nullptr;
1482}
1483
1484template <typename Ty>
1485class has_arg_iterator {
1486 typedef char yes[1];
1487 typedef char no[2];
1488
1489 template <typename Inner>
1490 static yes& test(Inner *I, decltype(I->args_begin()) * = nullptr);
1491
1492 template <typename>
1493 static no& test(...);
1494
1495public:
1496 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1497};
1498
1499static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1500 return A->getName();
1501}
1502
1503static StringRef ClassifyDiagnostic(QualType VDT) {
1504 // We need to look at the declaration of the type of the value to determine
1505 // which it is. The type should either be a record or a typedef, or a pointer
1506 // or reference thereof.
1507 if (const auto *RT = VDT->getAs<RecordType>()) {
1508 if (const auto *RD = RT->getDecl())
1509 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1510 return ClassifyDiagnostic(CA);
1511 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1512 if (const auto *TD = TT->getDecl())
1513 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1514 return ClassifyDiagnostic(CA);
1515 } else if (VDT->isPointerType() || VDT->isReferenceType())
1516 return ClassifyDiagnostic(VDT->getPointeeType());
1517
1518 return "mutex";
1519}
1520
1521static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1522 assert(VD && "No ValueDecl passed");
1523
1524 // The ValueDecl is the declaration of a mutex or role (hopefully).
1525 return ClassifyDiagnostic(VD->getType());
1526}
1527
1528template <typename AttrTy>
1529static typename std::enable_if<!has_arg_iterator<AttrTy>::value,
1530 StringRef>::type
1531ClassifyDiagnostic(const AttrTy *A) {
1532 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1533 return ClassifyDiagnostic(VD);
1534 return "mutex";
1535}
1536
1537template <typename AttrTy>
1538static typename std::enable_if<has_arg_iterator<AttrTy>::value,
1539 StringRef>::type
1540ClassifyDiagnostic(const AttrTy *A) {
1541 for (auto I = A->args_begin(), E = A->args_end(); I != E; ++I) {
1542 if (const ValueDecl *VD = getValueDecl(*I))
1543 return ClassifyDiagnostic(VD);
1544 }
1545 return "mutex";
1546}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001547
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001548/// \brief Add a new lock to the lockset, warning if the lock is already there.
1549/// \param Mutex -- the Mutex expression for the lock
1550/// \param LDat -- the LockData for the lock
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001551void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
Aaron Ballmane0449042014-04-01 21:43:23 +00001552 const LockData &LDat, StringRef DiagKind) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001553 // FIXME: deal with acquired before/after annotations.
1554 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001555 if (Mutex.shouldIgnore())
1556 return;
1557
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001558 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001559 if (!LDat.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00001560 Handler.handleDoubleLock(DiagKind, Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001561 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001562 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001563 }
1564}
1565
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001566
1567/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenek78094ca2012-08-22 23:50:41 +00001568/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001569/// \param UnlockLoc The source location of the unlock (only used in error msg)
Aaron Ballmandf115d92014-03-21 14:48:48 +00001570void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001571 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001572 bool FullyRemove, LockKind ReceivedKind,
1573 StringRef DiagKind) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001574 if (Mutex.shouldIgnore())
1575 return;
1576
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001577 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001578 if (!LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001579 Handler.handleUnmatchedUnlock(DiagKind, Mutex.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001580 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001581 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001582
Aaron Ballmandf115d92014-03-21 14:48:48 +00001583 // Generic lock removal doesn't care about lock kind mismatches, but
1584 // otherwise diagnose when the lock kinds are mismatched.
1585 if (ReceivedKind != LK_Generic && LDat->LKind != ReceivedKind) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001586 Handler.handleIncorrectUnlockKind(DiagKind, Mutex.toString(), LDat->LKind,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001587 ReceivedKind, UnlockLoc);
1588 return;
1589 }
1590
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001591 if (LDat->UnderlyingMutex.isValid()) {
1592 // This is scoped lockable object, which manages the real mutex.
1593 if (FullyRemove) {
1594 // We're destroying the managing object.
1595 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001596 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1597 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001598 } else {
1599 // We're releasing the underlying mutex, but not destroying the
1600 // managing object. Warn on dual release.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001601 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001602 Handler.handleUnmatchedUnlock(
1603 DiagKind, LDat->UnderlyingMutex.toString(), UnlockLoc);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001604 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001605 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1606 return;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001607 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001608 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001609 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001610}
1611
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001612
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001613/// \brief Extract the list of mutexIDs from the attribute on an expression,
1614/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001615template <typename AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001616void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001617 Expr *Exp, const NamedDecl *D,
1618 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001619 typedef typename AttrType::args_iterator iterator_type;
1620
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001621 if (Attr->args_size() == 0) {
1622 // The mutex held is the "this" object.
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001623 SExpr Mu(0, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001624 if (!Mu.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +00001625 SExpr::warnInvalidLock(Handler, 0, Exp, D, ClassifyDiagnostic(Attr));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001626 else
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001627 Mtxs.push_back_nodup(Mu);
1628 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001629 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001630
1631 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001632 SExpr Mu(*I, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001633 if (!Mu.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +00001634 SExpr::warnInvalidLock(Handler, *I, Exp, D, ClassifyDiagnostic(Attr));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001635 else
1636 Mtxs.push_back_nodup(Mu);
1637 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001638}
1639
1640
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001641/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1642/// trylock applies to the given edge, then push them onto Mtxs, discarding
1643/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001644template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001645void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1646 Expr *Exp, const NamedDecl *D,
1647 const CFGBlock *PredBlock,
1648 const CFGBlock *CurrBlock,
1649 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001650 // Find out which branch has the lock
1651 bool branch = 0;
1652 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1653 branch = BLE->getValue();
1654 }
1655 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1656 branch = ILE->getValue().getBoolValue();
1657 }
1658 int branchnum = branch ? 0 : 1;
1659 if (Neg) branchnum = !branchnum;
1660
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001661 // If we've taken the trylock branch, then add the lock
1662 int i = 0;
1663 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1664 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1665 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001666 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001667 }
1668 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001669}
1670
1671
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001672bool getStaticBooleanValue(Expr* E, bool& TCond) {
1673 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1674 TCond = false;
1675 return true;
1676 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1677 TCond = BLE->getValue();
1678 return true;
1679 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1680 TCond = ILE->getValue().getBoolValue();
1681 return true;
1682 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1683 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1684 }
1685 return false;
1686}
1687
1688
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001689// If Cond can be traced back to a function call, return the call expression.
1690// The negate variable should be called with false, and will be set to true
1691// if the function call is negated, e.g. if (!mu.tryLock(...))
1692const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1693 LocalVarContext C,
1694 bool &Negate) {
1695 if (!Cond)
1696 return 0;
1697
1698 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1699 return CallExp;
1700 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001701 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1702 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1703 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001704 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1705 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1706 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001707 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1708 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1709 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001710 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1711 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1712 return getTrylockCallExpr(E, C, Negate);
1713 }
1714 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1715 if (UOP->getOpcode() == UO_LNot) {
1716 Negate = !Negate;
1717 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1718 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001719 return 0;
1720 }
1721 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1722 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1723 if (BOP->getOpcode() == BO_NE)
1724 Negate = !Negate;
1725
1726 bool TCond = false;
1727 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1728 if (!TCond) Negate = !Negate;
1729 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1730 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001731 TCond = false;
1732 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001733 if (!TCond) Negate = !Negate;
1734 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1735 }
1736 return 0;
1737 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001738 if (BOP->getOpcode() == BO_LAnd) {
1739 // LHS must have been evaluated in a different block.
1740 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1741 }
1742 if (BOP->getOpcode() == BO_LOr) {
1743 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1744 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001745 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001746 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001747 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001748}
1749
1750
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001751/// \brief Find the lockset that holds on the edge between PredBlock
1752/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1753/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001754void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1755 const FactSet &ExitSet,
1756 const CFGBlock *PredBlock,
1757 const CFGBlock *CurrBlock) {
1758 Result = ExitSet;
1759
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001760 const Stmt *Cond = PredBlock->getTerminatorCondition();
1761 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001762 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001763
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001764 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001765 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1766 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001767 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001768
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001769 CallExpr *Exp =
1770 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001771 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001772 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001773
1774 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1775 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001776 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001777
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001778 MutexIDList ExclusiveLocksToAdd;
1779 MutexIDList SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001780
1781 // If the condition is a call to a Trylock function, then grab the attributes
1782 AttrVec &ArgAttrs = FunDecl->getAttrs();
1783 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1784 Attr *Attr = ArgAttrs[i];
1785 switch (Attr->getKind()) {
1786 case attr::ExclusiveTrylockFunction: {
1787 ExclusiveTrylockFunctionAttr *A =
1788 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001789 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1790 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001791 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001792 break;
1793 }
1794 case attr::SharedTrylockFunction: {
1795 SharedTrylockFunctionAttr *A =
1796 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001797 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001798 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001799 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001800 break;
1801 }
1802 default:
1803 break;
1804 }
1805 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001806
1807 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001808 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001809 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1810 addLock(Result, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
1811 CapDiagKind);
1812 for (const auto &SharedLockToAdd : SharedLocksToAdd)
1813 addLock(Result, SharedLockToAdd, LockData(Loc, LK_Shared), CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001814}
1815
Caitlin Sadowski33208342011-09-09 16:11:56 +00001816/// \brief We use this class to visit different types of expressions in
1817/// CFGBlocks, and build up the lockset.
1818/// An expression may cause us to add or remove locks from the lockset, or else
1819/// output error messages related to missing locks.
1820/// FIXME: In future, we may be able to not inherit from a visitor.
1821class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001822 friend class ThreadSafetyAnalyzer;
1823
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001824 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001825 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001826 LocalVariableMap::Context LVarCtx;
1827 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001828
1829 // Helper functions
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001830
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001831 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001832 Expr *MutexExp, ProtectedOperationKind POK,
1833 StringRef DiagKind);
1834 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1835 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001836
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001837 void checkAccess(const Expr *Exp, AccessKind AK);
1838 void checkPtAccess(const Expr *Exp, AccessKind AK);
1839
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001840 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001841
Caitlin Sadowski33208342011-09-09 16:11:56 +00001842public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001843 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001844 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001845 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001846 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001847 LVarCtx(Info.EntryContext),
1848 CtxIndex(Info.EntryIndex)
1849 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001850
1851 void VisitUnaryOperator(UnaryOperator *UO);
1852 void VisitBinaryOperator(BinaryOperator *BO);
1853 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001854 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001855 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001856 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001857};
1858
Caitlin Sadowski33208342011-09-09 16:11:56 +00001859/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001860/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001861void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001862 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001863 ProtectedOperationKind POK,
1864 StringRef DiagKind) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001865 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001866
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001867 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001868 if (!Mutex.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001869 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001870 return;
1871 } else if (Mutex.shouldIgnore()) {
1872 return;
1873 }
1874
1875 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001876 bool NoError = true;
1877 if (!LDat) {
1878 // No exact match found. Look for a partial match.
1879 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1880 if (FEntry) {
1881 // Warn that there's no precise match.
1882 LDat = &FEntry->LDat;
1883 std::string PartMatchStr = FEntry->MutID.toString();
1884 StringRef PartMatchName(PartMatchStr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001885 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1886 LK, Exp->getExprLoc(),
1887 &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001888 } else {
1889 // Warn that there's no match at all.
Aaron Ballmane0449042014-04-01 21:43:23 +00001890 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1891 LK, Exp->getExprLoc());
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001892 }
1893 NoError = false;
1894 }
1895 // Make sure the mutex we found is the right kind.
1896 if (NoError && LDat && !LDat->isAtLeast(LK))
Aaron Ballmane0449042014-04-01 21:43:23 +00001897 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(), LK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001898 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001899}
1900
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001901/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001902void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1903 Expr *MutexExp,
1904 StringRef DiagKind) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001905 SExpr Mutex(MutexExp, Exp, D);
1906 if (!Mutex.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001907 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001908 return;
1909 }
1910
1911 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
Aaron Ballmane0449042014-04-01 21:43:23 +00001912 if (LDat)
1913 Analyzer->Handler.handleFunExcludesLock(
1914 DiagKind, D->getNameAsString(), Mutex.toString(), Exp->getExprLoc());
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001915}
1916
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001917/// \brief Checks guarded_by and pt_guarded_by attributes.
1918/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1919/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1920/// Similarly, we check if the access is to an expression that dereferences
1921/// a pointer marked with pt_guarded_by.
1922void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1923 Exp = Exp->IgnoreParenCasts();
1924
1925 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1926 // For dereferences
1927 if (UO->getOpcode() == clang::UO_Deref)
1928 checkPtAccess(UO->getSubExpr(), AK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001929 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001930 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001931
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001932 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001933 checkPtAccess(AE->getLHS(), AK);
1934 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001935 }
1936
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001937 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1938 if (ME->isArrow())
1939 checkPtAccess(ME->getBase(), AK);
1940 else
1941 checkAccess(ME->getBase(), AK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001942 }
1943
Caitlin Sadowski33208342011-09-09 16:11:56 +00001944 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001945 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001946 return;
1947
Aaron Ballman9ead1242013-12-19 02:39:40 +00001948 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001949 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarAccess, AK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001950 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001951
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001952 for (const auto *I : D->specific_attrs<GuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001953 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess,
1954 ClassifyDiagnostic(I));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001955}
1956
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001957/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1958void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001959 while (true) {
1960 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1961 Exp = PE->getSubExpr();
1962 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001963 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001964 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1965 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1966 // If it's an actual array, and not a pointer, then it's elements
1967 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1968 checkAccess(CE->getSubExpr(), AK);
1969 return;
1970 }
1971 Exp = CE->getSubExpr();
1972 continue;
1973 }
1974 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001975 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001976
1977 const ValueDecl *D = getValueDecl(Exp);
1978 if (!D || !D->hasAttrs())
1979 return;
1980
Aaron Ballman9ead1242013-12-19 02:39:40 +00001981 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001982 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarDereference, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001983 Exp->getExprLoc());
1984
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001985 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001986 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference,
1987 ClassifyDiagnostic(I));
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001988}
1989
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001990/// \brief Process a function call, method call, constructor call,
1991/// or destructor call. This involves looking at the attributes on the
1992/// corresponding function/method/constructor/destructor, issuing warnings,
1993/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001994///
1995/// FIXME: For classes annotated with one of the guarded annotations, we need
1996/// to treat const method calls as reads and non-const method calls as writes,
1997/// and check that the appropriate locks are held. Non-const method calls with
1998/// the same signature as const method calls can be also treated as reads.
1999///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002000void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002001 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002002 const AttrVec &ArgAttrs = D->getAttrs();
Aaron Ballmandf115d92014-03-21 14:48:48 +00002003 MutexIDList ExclusiveLocksToAdd, SharedLocksToAdd;
2004 MutexIDList ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
Aaron Ballmane0449042014-04-01 21:43:23 +00002005 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002006
Caitlin Sadowski33208342011-09-09 16:11:56 +00002007 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002008 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
2009 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002010 // When we encounter a lock function, we need to add the lock to our
2011 // lockset.
2012 case attr::AcquireCapability: {
2013 auto *A = cast<AcquireCapabilityAttr>(At);
2014 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
2015 : ExclusiveLocksToAdd,
2016 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002017
2018 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002019 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002020 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002021
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002022 // An assert will add a lock to the lockset, but will not generate
2023 // a warning if it is already there, and will not generate a warning
2024 // if it is not removed.
2025 case attr::AssertExclusiveLock: {
2026 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
2027
2028 MutexIDList AssertLocks;
2029 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002030 for (const auto &AssertLock : AssertLocks)
2031 Analyzer->addLock(FSet, AssertLock,
2032 LockData(Loc, LK_Exclusive, false, true),
2033 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002034 break;
2035 }
2036 case attr::AssertSharedLock: {
2037 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
2038
2039 MutexIDList AssertLocks;
2040 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002041 for (const auto &AssertLock : AssertLocks)
2042 Analyzer->addLock(FSet, AssertLock,
2043 LockData(Loc, LK_Shared, false, true),
2044 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002045 break;
2046 }
2047
Caitlin Sadowski33208342011-09-09 16:11:56 +00002048 // When we encounter an unlock function, we need to remove unlocked
2049 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002050 case attr::ReleaseCapability: {
2051 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002052 if (A->isGeneric())
2053 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
2054 else if (A->isShared())
2055 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
2056 else
2057 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002058
2059 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002060 break;
2061 }
2062
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002063 case attr::RequiresCapability: {
2064 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002065
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002066 for (RequiresCapabilityAttr::args_iterator I = A->args_begin(),
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002067 E = A->args_end(); I != E; ++I)
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002068 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, *I,
Aaron Ballmane0449042014-04-01 21:43:23 +00002069 POK_FunctionCall, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002070 break;
2071 }
2072
2073 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002074 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00002075
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002076 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
2077 E = A->args_end(); I != E; ++I) {
Aaron Ballmane0449042014-04-01 21:43:23 +00002078 warnIfMutexHeld(D, Exp, *I, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002079 }
2080 break;
2081 }
2082
Alp Tokerd4733632013-12-05 04:47:09 +00002083 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00002084 default:
2085 break;
2086 }
2087 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002088
2089 // Figure out if we're calling the constructor of scoped lockable class
2090 bool isScopedVar = false;
2091 if (VD) {
2092 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
2093 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00002094 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002095 isScopedVar = true;
2096 }
2097 }
2098
2099 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00002100 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002101 Analyzer->addLock(FSet, M, LockData(Loc, LK_Exclusive, isScopedVar),
2102 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002103 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002104 Analyzer->addLock(FSet, M, LockData(Loc, LK_Shared, isScopedVar),
2105 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002106
2107 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2108 // FIXME -- this doesn't work if we acquire multiple locks.
2109 if (isScopedVar) {
2110 SourceLocation MLoc = VD->getLocation();
2111 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002112 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002113
Aaron Ballmandf115d92014-03-21 14:48:48 +00002114 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002115 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive, M),
2116 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002117 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002118 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared, M),
2119 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002120 }
2121
2122 // Remove locks.
2123 // FIXME -- should only fully remove if the attribute refers to 'this'.
2124 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002125 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002126 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002127 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002128 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002129 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002130 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002131}
2132
DeLesley Hutchins9d530332012-01-06 19:16:50 +00002133
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002134/// \brief For unary operations which read and write a variable, we need to
2135/// check whether we hold any required mutexes. Reads are checked in
2136/// VisitCastExpr.
2137void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2138 switch (UO->getOpcode()) {
2139 case clang::UO_PostDec:
2140 case clang::UO_PostInc:
2141 case clang::UO_PreDec:
2142 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002143 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002144 break;
2145 }
2146 default:
2147 break;
2148 }
2149}
2150
2151/// For binary operations which assign to a variable (writes), we need to check
2152/// whether we hold any required mutexes.
2153/// FIXME: Deal with non-primitive types.
2154void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2155 if (!BO->isAssignmentOp())
2156 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002157
2158 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002159 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002160
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002161 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002162}
2163
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002164
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002165/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2166/// need to ensure we hold any required mutexes.
2167/// FIXME: Deal with non-primitive types.
2168void BuildLockset::VisitCastExpr(CastExpr *CE) {
2169 if (CE->getCastKind() != CK_LValueToRValue)
2170 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002171 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002172}
2173
2174
DeLesley Hutchins714296c2011-12-29 00:56:48 +00002175void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002176 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2177 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2178 // ME can be null when calling a method pointer
2179 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002180
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002181 if (ME && MD) {
2182 if (ME->isArrow()) {
2183 if (MD->isConst()) {
2184 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2185 } else { // FIXME -- should be AK_Written
2186 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002187 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002188 } else {
2189 if (MD->isConst())
2190 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2191 else // FIXME -- should be AK_Written
2192 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002193 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002194 }
2195 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2196 switch (OE->getOperator()) {
2197 case OO_Equal: {
2198 const Expr *Target = OE->getArg(0);
2199 const Expr *Source = OE->getArg(1);
2200 checkAccess(Target, AK_Written);
2201 checkAccess(Source, AK_Read);
2202 break;
2203 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002204 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002205 case OO_Arrow:
2206 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00002207 const Expr *Obj = OE->getArg(0);
2208 checkAccess(Obj, AK_Read);
2209 checkPtAccess(Obj, AK_Read);
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002210 break;
2211 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002212 default: {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002213 const Expr *Obj = OE->getArg(0);
2214 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002215 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002216 }
2217 }
2218 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002219 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2220 if(!D || !D->hasAttrs())
2221 return;
2222 handleCall(Exp, D);
2223}
2224
2225void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002226 const CXXConstructorDecl *D = Exp->getConstructor();
2227 if (D && D->isCopyConstructor()) {
2228 const Expr* Source = Exp->getArg(0);
2229 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002230 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002231 // FIXME -- only handles constructors in DeclStmt below.
2232}
2233
2234void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002235 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002236 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002237
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002238 DeclGroupRef DGrp = S->getDeclGroup();
2239 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2240 Decl *D = *I;
2241 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2242 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002243 // handle constructors that involve temporaries
2244 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2245 E = EWC->getSubExpr();
2246
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002247 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2248 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2249 if (!CtorD || !CtorD->hasAttrs())
2250 return;
2251 handleCall(CE, CtorD, VD);
2252 }
2253 }
2254 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002255}
2256
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002257
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002258
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002259/// \brief Compute the intersection of two locksets and issue warnings for any
2260/// locks in the symmetric difference.
2261///
2262/// This function is used at a merge point in the CFG when comparing the lockset
2263/// of each branch being merged. For example, given the following sequence:
2264/// A; if () then B; else C; D; we need to check that the lockset after B and C
2265/// are the same. In the event of a difference, we use the intersection of these
2266/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002267///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002268/// \param FSet1 The first lockset.
2269/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002270/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002271/// \param LEK1 The error message to report if a mutex is missing from LSet1
2272/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002273void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2274 const FactSet &FSet2,
2275 SourceLocation JoinLoc,
2276 LockErrorKind LEK1,
2277 LockErrorKind LEK2,
2278 bool Modify) {
2279 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002280
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002281 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002282 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2283 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002284 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002285 const LockData &LDat2 = FactMan[*I].LDat;
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002286 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002287
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002288 if (I1 != FSet1.end()) {
2289 const LockData* LDat1 = &FactMan[*I1].LDat;
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002290 if (LDat1->LKind != LDat2.LKind) {
Aaron Ballmane0449042014-04-01 21:43:23 +00002291 Handler.handleExclusiveAndShared("mutex", FSet2Mutex.toString(),
2292 LDat2.AcquireLoc, LDat1->AcquireLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002293 if (Modify && LDat1->LKind != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002294 // Take the exclusive lock, which is the one in FSet2.
2295 *I1 = *I;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002296 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002297 }
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002298 else if (LDat1->Asserted && !LDat2.Asserted) {
2299 // The non-asserted lock in FSet2 is the one we want to track.
2300 *I1 = *I;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002301 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002302 } else {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002303 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002304 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002305 // If this is a scoped lock that manages another mutex, and if the
2306 // underlying mutex is still held, then warn about the underlying
2307 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00002308 Handler.handleMutexHeldEndOfScope("mutex",
2309 LDat2.UnderlyingMutex.toString(),
2310 LDat2.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002311 }
2312 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002313 else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00002314 Handler.handleMutexHeldEndOfScope("mutex", FSet2Mutex.toString(),
2315 LDat2.AcquireLoc, JoinLoc, LEK1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002316 }
2317 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002318
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002319 // Find locks in FSet1 that are not in FSet2, and remove them.
2320 for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002321 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002322 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002323 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002324
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002325 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002326 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002327 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002328 // If this is a scoped lock that manages another mutex, and if the
2329 // underlying mutex is still held, then warn about the underlying
2330 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00002331 Handler.handleMutexHeldEndOfScope("mutex",
2332 LDat1.UnderlyingMutex.toString(),
2333 LDat1.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002334 }
2335 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002336 else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00002337 Handler.handleMutexHeldEndOfScope("mutex", FSet1Mutex.toString(),
2338 LDat1.AcquireLoc, JoinLoc, LEK2);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002339 if (Modify)
2340 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002341 }
2342 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002343}
2344
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002345
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002346// Return true if block B never continues to its successors.
2347inline bool neverReturns(const CFGBlock* B) {
2348 if (B->hasNoReturnElement())
2349 return true;
2350 if (B->empty())
2351 return false;
2352
2353 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002354 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2355 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002356 return true;
2357 }
2358 return false;
2359}
2360
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002361
Caitlin Sadowski33208342011-09-09 16:11:56 +00002362/// \brief Check a function's CFG for thread-safety violations.
2363///
2364/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2365/// at the end of each block, and issue warnings for thread safety violations.
2366/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002367void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002368 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2369 // For now, we just use the walker to set things up.
2370 threadSafety::CFGWalker walker;
2371 if (!walker.init(AC))
2372 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002373
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002374 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002375 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002376
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002377 CFG *CFGraph = walker.CFGraph;
2378 const NamedDecl *D = walker.FDecl;
2379
Aaron Ballman9ead1242013-12-19 02:39:40 +00002380 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002381 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002382
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002383 // FIXME: Do something a bit more intelligent inside constructor and
2384 // destructor code. Constructors and destructors must assume unique access
2385 // to 'this', so checks on member variable access is disabled, but we should
2386 // still enable checks on other objects.
2387 if (isa<CXXConstructorDecl>(D))
2388 return; // Don't check inside constructors.
2389 if (isa<CXXDestructorDecl>(D))
2390 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002391
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002392 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002393 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002394
2395 // We need to explore the CFG via a "topological" ordering.
2396 // That way, we will be guaranteed to have information about required
2397 // predecessor locksets when exploring a new block.
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002398 PostOrderCFGView *SortedGraph = walker.SortedGraph;
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002399 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002400
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002401 // Mark entry block as reachable
2402 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2403
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002404 // Compute SSA names for local variables
2405 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2406
Richard Smith92286672012-02-03 04:45:26 +00002407 // Fill in source locations for all CFGBlocks.
2408 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2409
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002410 MutexIDList ExclusiveLocksAcquired;
2411 MutexIDList SharedLocksAcquired;
2412 MutexIDList LocksReleased;
2413
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002414 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002415 // to initial lockset. Also turn off checking for lock and unlock functions.
2416 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002417 if (!SortedGraph->empty() && D->hasAttrs()) {
2418 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002419 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002420 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002421
2422 MutexIDList ExclusiveLocksToAdd;
2423 MutexIDList SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002424 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002425
2426 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002427 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002428 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002429 Loc = Attr->getLocation();
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002430 if (RequiresCapabilityAttr *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2431 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2432 0, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002433 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002434 } else if (auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002435 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2436 // We must ignore such methods.
2437 if (A->args_size() == 0)
2438 return;
2439 // FIXME -- deal with exclusive vs. shared unlock functions?
2440 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2441 getMutexIDs(LocksReleased, A, (Expr*) 0, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002442 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002443 } else if (auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002444 if (A->args_size() == 0)
2445 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002446 getMutexIDs(A->isShared() ? SharedLocksAcquired
2447 : ExclusiveLocksAcquired,
2448 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002449 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002450 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2451 // Don't try to check trylock functions for now
2452 return;
2453 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2454 // Don't try to check trylock functions for now
2455 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002456 }
2457 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002458
2459 // FIXME -- Loc can be wrong here.
Aaron Ballmane0449042014-04-01 21:43:23 +00002460 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
2461 addLock(InitialLockset, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
2462 CapDiagKind);
2463 for (const auto &SharedLockToAdd : SharedLocksToAdd)
2464 addLock(InitialLockset, SharedLockToAdd, LockData(Loc, LK_Shared),
2465 CapDiagKind);
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002466 }
2467
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002468 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2469 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002470 const CFGBlock *CurrBlock = *I;
2471 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002472 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002473
2474 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002475 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002476
2477 // Iterate through the predecessor blocks and warn if the lockset for all
2478 // predecessors is not the same. We take the entry lockset of the current
2479 // block to be the intersection of all previous locksets.
2480 // FIXME: By keeping the intersection, we may output more errors in future
2481 // for a lock which is not in the intersection, but was in the union. We
2482 // may want to also keep the union in future. As an example, let's say
2483 // the intersection contains Mutex L, and the union contains L and M.
2484 // Later we unlock M. At this point, we would output an error because we
2485 // never locked M; although the real error is probably that we forgot to
2486 // lock M on all code paths. Conversely, let's say that later we lock M.
2487 // In this case, we should compare against the intersection instead of the
2488 // union because the real error is probably that we forgot to unlock M on
2489 // all code paths.
2490 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002491 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002492 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2493 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2494
2495 // if *PI -> CurrBlock is a back edge
2496 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2497 continue;
2498
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002499 int PrevBlockID = (*PI)->getBlockID();
2500 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2501
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002502 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002503 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002504 continue;
2505
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002506 // Okay, we can reach this block from the entry.
2507 CurrBlockInfo->Reachable = true;
2508
Richard Smith815b29d2012-02-03 03:30:07 +00002509 // If the previous block ended in a 'continue' or 'break' statement, then
2510 // a difference in locksets is probably due to a bug in that block, rather
2511 // than in some other predecessor. In that case, keep the other
2512 // predecessor's lockset.
2513 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2514 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2515 SpecialBlocks.push_back(*PI);
2516 continue;
2517 }
2518 }
2519
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002520 FactSet PrevLockset;
2521 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002522
Caitlin Sadowski33208342011-09-09 16:11:56 +00002523 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002524 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002525 LocksetInitialized = true;
2526 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002527 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2528 CurrBlockInfo->EntryLoc,
2529 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002530 }
2531 }
2532
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002533 // Skip rest of block if it's not reachable.
2534 if (!CurrBlockInfo->Reachable)
2535 continue;
2536
Richard Smith815b29d2012-02-03 03:30:07 +00002537 // Process continue and break blocks. Assume that the lockset for the
2538 // resulting block is unaffected by any discrepancies in them.
2539 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2540 SpecialI < SpecialN; ++SpecialI) {
2541 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2542 int PrevBlockID = PrevBlock->getBlockID();
2543 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2544
2545 if (!LocksetInitialized) {
2546 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2547 LocksetInitialized = true;
2548 } else {
2549 // Determine whether this edge is a loop terminator for diagnostic
2550 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2551 // it might also be part of a switch. Also, a subsequent destructor
2552 // might add to the lockset, in which case the real issue might be a
2553 // double lock on the other path.
2554 const Stmt *Terminator = PrevBlock->getTerminator();
2555 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2556
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002557 FactSet PrevLockset;
2558 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2559 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002560
Richard Smith815b29d2012-02-03 03:30:07 +00002561 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002562 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2563 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002564 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002565 : LEK_LockedSomePredecessors,
2566 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002567 }
2568 }
2569
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002570 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2571
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002572 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002573 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2574 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002575 switch (BI->getKind()) {
2576 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002577 CFGStmt CS = BI->castAs<CFGStmt>();
2578 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002579 break;
2580 }
2581 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2582 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002583 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2584 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2585 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002586 if (!DD->hasAttrs())
2587 break;
2588
2589 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002590 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002591 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002592 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002593 LocksetBuilder.handleCall(&DRE, DD);
2594 break;
2595 }
2596 default:
2597 break;
2598 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002599 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002600 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002601
2602 // For every back edge from CurrBlock (the end of the loop) to another block
2603 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2604 // the one held at the beginning of FirstLoopBlock. We can look up the
2605 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2606 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2607 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2608
2609 // if CurrBlock -> *SI is *not* a back edge
2610 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2611 continue;
2612
2613 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002614 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2615 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2616 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2617 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002618 LEK_LockedSomeLoopIterations,
2619 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002620 }
2621 }
2622
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002623 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2624 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002625
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002626 // Skip the final check if the exit block is unreachable.
2627 if (!Final->Reachable)
2628 return;
2629
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002630 // By default, we expect all locks held on entry to be held on exit.
2631 FactSet ExpectedExitSet = Initial->EntrySet;
2632
2633 // Adjust the expected exit set by adding or removing locks, as declared
2634 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2635 // issue the appropriate warning.
2636 // FIXME: the location here is not quite right.
2637 for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) {
2638 ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i],
2639 LockData(D->getLocation(), LK_Exclusive));
2640 }
2641 for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) {
2642 ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i],
2643 LockData(D->getLocation(), LK_Shared));
2644 }
2645 for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) {
2646 ExpectedExitSet.removeLock(FactMan, LocksReleased[i]);
2647 }
2648
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002649 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002650 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002651 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002652 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002653 LEK_NotLockedAtEndOfFunction,
2654 false);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002655}
2656
2657} // end anonymous namespace
2658
2659
2660namespace clang {
2661namespace thread_safety {
2662
2663/// \brief Check a function's CFG for thread-safety violations.
2664///
2665/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2666/// at the end of each block, and issue warnings for thread safety violations.
2667/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002668void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002669 ThreadSafetyHandler &Handler) {
2670 ThreadSafetyAnalyzer Analyzer(Handler);
2671 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002672}
2673
2674/// \brief Helper function that returns a LockKind required for the given level
2675/// of access.
2676LockKind getLockKindFromAccessKind(AccessKind AK) {
2677 switch (AK) {
2678 case AK_Read :
2679 return LK_Shared;
2680 case AK_Written :
2681 return LK_Exclusive;
2682 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002683 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002684}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002685
Caitlin Sadowski33208342011-09-09 16:11:56 +00002686}} // end namespace clang::thread_safety