blob: 9cc2a55f0af9c69d1677368ce4d694d69dcff84d [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"
26#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/AnalysisContext.h"
28#include "clang/Analysis/CFG.h"
29#include "clang/Analysis/CFGStmtMap.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000030#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000031#include "clang/Basic/SourceLocation.h"
32#include "clang/Basic/SourceManager.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000033#include "llvm/ADT/BitVector.h"
34#include "llvm/ADT/FoldingSet.h"
35#include "llvm/ADT/ImmutableMap.h"
36#include "llvm/ADT/PostOrderIterator.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000039#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000040#include <algorithm>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000041#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000042#include <vector>
43
44using namespace clang;
45using namespace thread_safety;
46
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000047// Key method definition
48ThreadSafetyHandler::~ThreadSafetyHandler() {}
49
Caitlin Sadowski33208342011-09-09 16:11:56 +000050namespace {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +000051
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000052/// SExpr implements a simple expression language that is used to store,
53/// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
54/// does not capture surface syntax, and it does not distinguish between
55/// C++ concepts, like pointers and references, that have no real semantic
56/// differences. This simplicity allows SExprs to be meaningfully compared,
57/// e.g.
58/// (x) = x
59/// (*this).foo = this->foo
60/// *&a = a
Caitlin Sadowski33208342011-09-09 16:11:56 +000061///
62/// Thread-safety analysis works by comparing lock expressions. Within the
63/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
64/// a particular mutex object at run-time. Subsequent occurrences of the same
65/// expression (where "same" means syntactic equality) will refer to the same
66/// run-time object if three conditions hold:
67/// (1) Local variables in the expression, such as "x" have not changed.
68/// (2) Values on the heap that affect the expression have not changed.
69/// (3) The expression involves only pure function calls.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +000070///
Caitlin Sadowski33208342011-09-09 16:11:56 +000071/// The current implementation assumes, but does not verify, that multiple uses
72/// of the same lock expression satisfies these criteria.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000073class SExpr {
74private:
75 enum ExprOp {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +000076 EOP_Nop, ///< No-op
77 EOP_Wildcard, ///< Matches anything.
78 EOP_Universal, ///< Universal lock.
79 EOP_This, ///< This keyword.
80 EOP_NVar, ///< Named variable.
81 EOP_LVar, ///< Local variable.
82 EOP_Dot, ///< Field access
83 EOP_Call, ///< Function call
84 EOP_MCall, ///< Method call
85 EOP_Index, ///< Array index
86 EOP_Unary, ///< Unary operation
87 EOP_Binary, ///< Binary operation
88 EOP_Unknown ///< Catchall for everything else
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000089 };
90
91
92 class SExprNode {
93 private:
Ted Kremenek78094ca2012-08-22 23:50:41 +000094 unsigned char Op; ///< Opcode of the root node
95 unsigned char Flags; ///< Additional opcode-specific data
96 unsigned short Sz; ///< Number of child nodes
97 const void* Data; ///< Additional opcode-specific data
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000098
99 public:
100 SExprNode(ExprOp O, unsigned F, const void* D)
101 : Op(static_cast<unsigned char>(O)),
102 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
103 { }
104
105 unsigned size() const { return Sz; }
106 void setSize(unsigned S) { Sz = S; }
107
108 ExprOp kind() const { return static_cast<ExprOp>(Op); }
109
110 const NamedDecl* getNamedDecl() const {
111 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
112 return reinterpret_cast<const NamedDecl*>(Data);
113 }
114
115 const NamedDecl* getFunctionDecl() const {
116 assert(Op == EOP_Call || Op == EOP_MCall);
117 return reinterpret_cast<const NamedDecl*>(Data);
118 }
119
120 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
121 void setArrow(bool A) { Flags = A ? 1 : 0; }
122
123 unsigned arity() const {
124 switch (Op) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000125 case EOP_Nop: return 0;
126 case EOP_Wildcard: return 0;
127 case EOP_Universal: return 0;
128 case EOP_NVar: return 0;
129 case EOP_LVar: return 0;
130 case EOP_This: return 0;
131 case EOP_Dot: return 1;
132 case EOP_Call: return Flags+1; // First arg is function.
133 case EOP_MCall: return Flags+1; // First arg is implicit obj.
134 case EOP_Index: return 2;
135 case EOP_Unary: return 1;
136 case EOP_Binary: return 2;
137 case EOP_Unknown: return Flags;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000138 }
139 return 0;
140 }
141
142 bool operator==(const SExprNode& Other) const {
143 // Ignore flags and size -- they don't matter.
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000144 return (Op == Other.Op &&
145 Data == Other.Data);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000146 }
147
148 bool operator!=(const SExprNode& Other) const {
149 return !(*this == Other);
150 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000151
152 bool matches(const SExprNode& Other) const {
153 return (*this == Other) ||
154 (Op == EOP_Wildcard) ||
155 (Other.Op == EOP_Wildcard);
156 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000157 };
158
Caitlin Sadowski33208342011-09-09 16:11:56 +0000159
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000160 /// \brief Encapsulates the lexical context of a function call. The lexical
161 /// context includes the arguments to the call, including the implicit object
162 /// argument. When an attribute containing a mutex expression is attached to
163 /// a method, the expression may refer to formal parameters of the method.
164 /// Actual arguments must be substituted for formal parameters to derive
165 /// the appropriate mutex expression in the lexical context where the function
166 /// is called. PrevCtx holds the context in which the arguments themselves
167 /// should be evaluated; multiple calling contexts can be chained together
168 /// by the lock_returned attribute.
169 struct CallingContext {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000170 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
171 const Expr* SelfArg; // Implicit object argument -- e.g. 'this'
172 bool SelfArrow; // is Self referred to with -> or .?
173 unsigned NumArgs; // Number of funArgs
174 const Expr* const* FunArgs; // Function arguments
175 CallingContext* PrevCtx; // The previous context; or 0 if none.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000176
Aaron Ballman69bb5922014-03-06 19:37:24 +0000177 CallingContext(const NamedDecl *D)
178 : AttrDecl(D), SelfArg(0), SelfArrow(false), NumArgs(0), FunArgs(0),
179 PrevCtx(0) {}
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000180 };
181
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000182 typedef SmallVector<SExprNode, 4> NodeVector;
183
184private:
185 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
186 // the list to be traversed as a tree.
187 NodeVector NodeVec;
188
189private:
Aaron Ballman19842c42014-03-06 19:25:11 +0000190 unsigned make(ExprOp O, unsigned F = 0, const void *D = 0) {
191 NodeVec.push_back(SExprNode(O, F, D));
192 return NodeVec.size() - 1;
193 }
194
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000195 unsigned makeNop() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000196 return make(EOP_Nop);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000197 }
198
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000199 unsigned makeWildcard() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000200 return make(EOP_Wildcard);
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000201 }
202
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000203 unsigned makeUniversal() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000204 return make(EOP_Universal);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000205 }
206
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000207 unsigned makeNamedVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000208 return make(EOP_NVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000209 }
210
211 unsigned makeLocalVar(const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000212 return make(EOP_LVar, 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000213 }
214
215 unsigned makeThis() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000216 return make(EOP_This);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000217 }
218
219 unsigned makeDot(const NamedDecl *D, bool Arrow) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000220 return make(EOP_Dot, Arrow ? 1 : 0, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000221 }
222
223 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000224 return make(EOP_Call, NumArgs, D);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000225 }
226
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000227 // Grab the very first declaration of virtual method D
228 const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
229 while (true) {
230 D = D->getCanonicalDecl();
231 CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
232 E = D->end_overridden_methods();
233 if (I == E)
234 return D; // Method does not override anything
235 D = *I; // FIXME: this does not work with multiple inheritance.
236 }
237 return 0;
238 }
239
240 unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000241 return make(EOP_MCall, NumArgs, getFirstVirtualDecl(D));
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000242 }
243
244 unsigned makeIndex() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000245 return make(EOP_Index);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000246 }
247
248 unsigned makeUnary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000249 return make(EOP_Unary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000250 }
251
252 unsigned makeBinary() {
Aaron Ballman19842c42014-03-06 19:25:11 +0000253 return make(EOP_Binary);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000254 }
255
256 unsigned makeUnknown(unsigned Arity) {
Aaron Ballman19842c42014-03-06 19:25:11 +0000257 return make(EOP_Unknown, Arity);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000258 }
259
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000260 inline bool isCalleeArrow(const Expr *E) {
261 const MemberExpr *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
262 return ME ? ME->isArrow() : false;
263 }
264
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000265 /// Build an SExpr from the given C++ expression.
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000266 /// Recursive function that terminates on DeclRefExpr.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000267 /// Note: this function merely creates a SExpr; it does not check to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000268 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000269 ///
270 /// NDeref returns the number of Derefence and AddressOf operations
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000271 /// preceding the Expr; this is used to decide whether to pretty-print
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000272 /// SExprs with . or ->.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000273 unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx,
274 int* NDeref = 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000275 if (!Exp)
276 return 0;
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000277
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000278 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
279 const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
280 const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000281 if (PV) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000282 const FunctionDecl *FD =
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000283 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
284 unsigned i = PV->getFunctionScopeIndex();
285
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000286 if (CallCtx && CallCtx->FunArgs &&
287 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000288 // Substitute call arguments for references to function parameters
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000289 assert(i < CallCtx->NumArgs);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000290 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000291 }
292 // Map the param back to the param of the original function declaration.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000293 makeNamedVar(FD->getParamDecl(i));
294 return 1;
DeLesley Hutchins68f7b1a2012-01-20 23:24:41 +0000295 }
296 // Not a function parameter -- just store the reference.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000297 makeNamedVar(ND);
298 return 1;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000299 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000300 // Substitute parent for 'this'
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000301 if (CallCtx && CallCtx->SelfArg) {
302 if (!CallCtx->SelfArrow && NDeref)
303 // 'this' is a pointer, but self is not, so need to take address.
304 --(*NDeref);
305 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
306 }
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000307 else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000308 makeThis();
309 return 1;
DeLesley Hutchinsbc8ffdb2012-02-16 17:03:24 +0000310 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000311 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
312 const NamedDecl *ND = ME->getMemberDecl();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000313 int ImplicitDeref = ME->isArrow() ? 1 : 0;
314 unsigned Root = makeDot(ND, false);
315 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
316 NodeVec[Root].setArrow(ImplicitDeref > 0);
317 NodeVec[Root].setSize(Sz + 1);
318 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000319 } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000320 // When calling a function with a lock_returned attribute, replace
321 // the function call with the expression in lock_returned.
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000322 const CXXMethodDecl *MD = CMCE->getMethodDecl()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000323 if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000324 CallingContext LRCallCtx(CMCE->getMethodDecl());
325 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000326 LRCallCtx.SelfArrow = isCalleeArrow(CMCE->getCallee());
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000327 LRCallCtx.NumArgs = CMCE->getNumArgs();
328 LRCallCtx.FunArgs = CMCE->getArgs();
329 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000330 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000331 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000332 // Hack to treat smart pointers and iterators as pointers;
333 // ignore any method named get().
334 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
335 CMCE->getNumArgs() == 0) {
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000336 if (NDeref && isCalleeArrow(CMCE->getCallee()))
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000337 ++(*NDeref);
338 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000339 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000340 unsigned NumCallArgs = CMCE->getNumArgs();
DeLesley Hutchinsb78aeed2012-09-20 22:18:02 +0000341 unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000342 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000343 const Expr* const* CallArgs = CMCE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000344 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000345 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000346 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000347 NodeVec[Root].setSize(Sz + 1);
348 return Sz + 1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000349 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
Rafael Espindola7b56f6c2013-10-19 16:55:03 +0000350 const FunctionDecl *FD = CE->getDirectCallee()->getMostRecentDecl();
DeLesley Hutchinsf5cf7902012-08-31 22:09:53 +0000351 if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000352 CallingContext LRCallCtx(CE->getDirectCallee());
353 LRCallCtx.NumArgs = CE->getNumArgs();
354 LRCallCtx.FunArgs = CE->getArgs();
355 LRCallCtx.PrevCtx = CallCtx;
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000356 return buildSExpr(At->getArg(), &LRCallCtx);
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000357 }
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000358 // Treat smart pointers and iterators as pointers;
359 // ignore the * and -> operators.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000360 if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000361 OverloadedOperatorKind k = OE->getOperator();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000362 if (k == OO_Star) {
363 if (NDeref) ++(*NDeref);
364 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
365 }
366 else if (k == OO_Arrow) {
367 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +0000368 }
369 }
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000370 unsigned NumCallArgs = CE->getNumArgs();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000371 unsigned Root = makeCall(NumCallArgs, 0);
372 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000373 const Expr* const* CallArgs = CE->getArgs();
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000374 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000375 Sz += buildSExpr(CallArgs[i], CallCtx);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000376 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000377 NodeVec[Root].setSize(Sz+1);
378 return Sz+1;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000379 } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000380 unsigned Root = makeBinary();
381 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
382 Sz += buildSExpr(BOE->getRHS(), CallCtx);
383 NodeVec[Root].setSize(Sz);
384 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000385 } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000386 // Ignore & and * operators -- they're no-ops.
387 // However, we try to figure out whether the expression is a pointer,
388 // so we can use . and -> appropriately in error messages.
389 if (UOE->getOpcode() == UO_Deref) {
390 if (NDeref) ++(*NDeref);
391 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
392 }
393 if (UOE->getOpcode() == UO_AddrOf) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000394 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
395 if (DRE->getDecl()->isCXXInstanceMember()) {
396 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
397 // We interpret this syntax specially, as a wildcard.
398 unsigned Root = makeDot(DRE->getDecl(), false);
399 makeWildcard();
400 NodeVec[Root].setSize(2);
401 return 2;
402 }
403 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000404 if (NDeref) --(*NDeref);
405 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
406 }
407 unsigned Root = makeUnary();
408 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
409 NodeVec[Root].setSize(Sz);
410 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000411 } else if (const ArraySubscriptExpr *ASE =
412 dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000413 unsigned Root = makeIndex();
414 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
415 Sz += buildSExpr(ASE->getIdx(), CallCtx);
416 NodeVec[Root].setSize(Sz);
417 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000418 } else if (const AbstractConditionalOperator *CE =
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000419 dyn_cast<AbstractConditionalOperator>(Exp)) {
420 unsigned Root = makeUnknown(3);
421 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
422 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
423 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
424 NodeVec[Root].setSize(Sz);
425 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000426 } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000427 unsigned Root = makeUnknown(3);
428 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
429 Sz += buildSExpr(CE->getLHS(), CallCtx);
430 Sz += buildSExpr(CE->getRHS(), CallCtx);
431 NodeVec[Root].setSize(Sz);
432 return Sz;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000433 } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000434 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000435 } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000436 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000437 } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000438 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000439 } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000440 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000441 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins0c1da202012-07-03 18:25:56 +0000442 isa<CXXNullPtrLiteralExpr>(Exp) ||
443 isa<GNUNullExpr>(Exp) ||
444 isa<CXXBoolLiteralExpr>(Exp) ||
445 isa<FloatingLiteral>(Exp) ||
446 isa<ImaginaryLiteral>(Exp) ||
447 isa<IntegerLiteral>(Exp) ||
448 isa<StringLiteral>(Exp) ||
449 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000450 makeNop();
451 return 1; // FIXME: Ignore literals for now
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000452 } else {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000453 makeNop();
454 return 1; // Ignore. FIXME: mark as invalid expression?
DeLesley Hutchinse2a3f752012-03-02 23:36:05 +0000455 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000456 }
457
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000458 /// \brief Construct a SExpr from an expression.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000459 /// \param MutexExp The original mutex expression within an attribute
460 /// \param DeclExp An expression involving the Decl on which the attribute
461 /// occurs.
462 /// \param D The declaration to which the lock/unlock attribute is attached.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000463 void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp,
464 const NamedDecl *D, VarDecl *SelfDecl = 0) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000465 CallingContext CallCtx(D);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000466
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000467 if (MutexExp) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000468 if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000469 if (SLit->getString() == StringRef("*"))
470 // The "*" expr is a universal lock, which essentially turns off
471 // checks until it is removed from the lockset.
472 makeUniversal();
473 else
474 // Ignore other string literals for now.
475 makeNop();
476 return;
477 }
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000478 }
479
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000480 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000481 if (DeclExp == 0) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000482 buildSExpr(MutexExp, 0);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000483 return;
484 }
485
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000486 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +0000487 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000488 if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000489 CallCtx.SelfArg = ME->getBase();
490 CallCtx.SelfArrow = ME->isArrow();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000491 } else if (const CXXMemberCallExpr *CE =
492 dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000493 CallCtx.SelfArg = CE->getImplicitObjectArgument();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000494 CallCtx.SelfArrow = isCalleeArrow(CE->getCallee());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000495 CallCtx.NumArgs = CE->getNumArgs();
496 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins39b804f2013-11-26 19:45:21 +0000497 } else if (const CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000498 CallCtx.NumArgs = CE->getNumArgs();
499 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000500 } else if (const CXXConstructExpr *CE =
501 dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000502 CallCtx.SelfArg = 0; // Will be set below
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000503 CallCtx.NumArgs = CE->getNumArgs();
504 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +0000505 } else if (D && isa<CXXDestructorDecl>(D)) {
506 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchins49979f22012-06-25 18:33:18 +0000507 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000508 }
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000509
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000510 // Hack to handle constructors, where self cannot be recovered from
511 // the expression.
512 if (SelfDecl && !CallCtx.SelfArg) {
513 DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
514 SelfDecl->getLocation());
515 CallCtx.SelfArg = &SelfDRE;
516
517 // If the attribute has no arguments, then assume the argument is "this".
518 if (MutexExp == 0)
519 buildSExpr(CallCtx.SelfArg, 0);
520 else // For most attributes.
521 buildSExpr(MutexExp, &CallCtx);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000522 return;
523 }
DeLesley Hutchins30abeb12011-10-17 21:38:02 +0000524
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000525 // If the attribute has no arguments, then assume the argument is "this".
526 if (MutexExp == 0)
527 buildSExpr(CallCtx.SelfArg, 0);
528 else // For most attributes.
529 buildSExpr(MutexExp, &CallCtx);
Caitlin Sadowski33208342011-09-09 16:11:56 +0000530 }
531
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000532 /// \brief Get index of next sibling of node i.
533 unsigned getNextSibling(unsigned i) const {
534 return i + NodeVec[i].size();
535 }
536
Caitlin Sadowski33208342011-09-09 16:11:56 +0000537public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000538 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000539
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000540 /// \param MutexExp The original mutex expression within an attribute
541 /// \param DeclExp An expression involving the Decl on which the attribute
542 /// occurs.
543 /// \param D The declaration to which the lock/unlock attribute is attached.
544 /// Caller must check isValid() after construction.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000545 SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +0000546 VarDecl *SelfDecl=0) {
547 buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000548 }
549
DeLesley Hutchinsa088f672011-10-17 21:33:35 +0000550 /// Return true if this is a valid decl sequence.
551 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000552 bool isValid() const {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000553 return !NodeVec.empty();
Caitlin Sadowski33208342011-09-09 16:11:56 +0000554 }
555
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000556 bool shouldIgnore() const {
557 // Nop is a mutex that we have decided to deliberately ignore.
558 assert(NodeVec.size() > 0 && "Invalid Mutex");
559 return NodeVec[0].kind() == EOP_Nop;
560 }
561
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000562 bool isUniversal() const {
563 assert(NodeVec.size() > 0 && "Invalid Mutex");
564 return NodeVec[0].kind() == EOP_Universal;
565 }
566
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000567 /// Issue a warning about an invalid lock expression
DeLesley Hutchins5df82f22012-12-05 00:52:33 +0000568 static void warnInvalidLock(ThreadSafetyHandler &Handler,
Aaron Ballmane0449042014-04-01 21:43:23 +0000569 const Expr *MutexExp, const Expr *DeclExp,
570 const NamedDecl *D, StringRef Kind) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000571 SourceLocation Loc;
572 if (DeclExp)
573 Loc = DeclExp->getExprLoc();
574
575 // FIXME: add a note about the attribute location in MutexExp or D
576 if (Loc.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +0000577 Handler.handleInvalidLockExp(Kind, Loc);
DeLesley Hutchinsc2090512011-10-21 18:10:14 +0000578 }
579
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000580 bool operator==(const SExpr &other) const {
581 return NodeVec == other.NodeVec;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000582 }
583
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000584 bool operator!=(const SExpr &other) const {
Caitlin Sadowski33208342011-09-09 16:11:56 +0000585 return !(*this == other);
586 }
587
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000588 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
589 if (NodeVec[i].matches(Other.NodeVec[j])) {
DeLesley Hutchins138568b2012-09-11 23:04:49 +0000590 unsigned ni = NodeVec[i].arity();
591 unsigned nj = Other.NodeVec[j].arity();
592 unsigned n = (ni < nj) ? ni : nj;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000593 bool Result = true;
594 unsigned ci = i+1; // first child of i
595 unsigned cj = j+1; // first child of j
596 for (unsigned k = 0; k < n;
597 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
598 Result = Result && matches(Other, ci, cj);
599 }
600 return Result;
601 }
602 return false;
603 }
604
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000605 // A partial match between a.mu and b.mu returns true a and b have the same
606 // type (and thus mu refers to the same mutex declaration), regardless of
607 // whether a and b are different objects or not.
608 bool partiallyMatches(const SExpr &Other) const {
609 if (NodeVec[0].kind() == EOP_Dot)
610 return NodeVec[0].matches(Other.NodeVec[0]);
611 return false;
612 }
613
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000614 /// \brief Pretty print a lock expression for use in error messages.
615 std::string toString(unsigned i = 0) const {
Caitlin Sadowski787c2a12011-09-14 20:00:24 +0000616 assert(isValid());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000617 if (i >= NodeVec.size())
618 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000619
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000620 const SExprNode* N = &NodeVec[i];
621 switch (N->kind()) {
622 case EOP_Nop:
623 return "_";
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000624 case EOP_Wildcard:
625 return "(?)";
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000626 case EOP_Universal:
627 return "*";
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000628 case EOP_This:
629 return "this";
630 case EOP_NVar:
631 case EOP_LVar: {
632 return N->getNamedDecl()->getNameAsString();
633 }
634 case EOP_Dot: {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000635 if (NodeVec[i+1].kind() == EOP_Wildcard) {
636 std::string S = "&";
637 S += N->getNamedDecl()->getQualifiedNameAsString();
638 return S;
639 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000640 std::string FieldName = N->getNamedDecl()->getNameAsString();
641 if (NodeVec[i+1].kind() == EOP_This)
642 return FieldName;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000643
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000644 std::string S = toString(i+1);
645 if (N->isArrow())
646 return S + "->" + FieldName;
647 else
648 return S + "." + FieldName;
649 }
650 case EOP_Call: {
651 std::string S = toString(i+1) + "(";
652 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000653 unsigned ci = getNextSibling(i+1);
654 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000655 S += toString(ci);
656 if (k+1 < NumArgs) S += ",";
657 }
658 S += ")";
659 return S;
660 }
661 case EOP_MCall: {
662 std::string S = "";
663 if (NodeVec[i+1].kind() != EOP_This)
664 S = toString(i+1) + ".";
665 if (const NamedDecl *D = N->getFunctionDecl())
666 S += D->getNameAsString() + "(";
667 else
668 S += "#(";
669 unsigned NumArgs = N->arity()-1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000670 unsigned ci = getNextSibling(i+1);
671 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000672 S += toString(ci);
673 if (k+1 < NumArgs) S += ",";
674 }
675 S += ")";
676 return S;
677 }
678 case EOP_Index: {
679 std::string S1 = toString(i+1);
680 std::string S2 = toString(i+1 + NodeVec[i+1].size());
681 return S1 + "[" + S2 + "]";
682 }
683 case EOP_Unary: {
684 std::string S = toString(i+1);
685 return "#" + S;
686 }
687 case EOP_Binary: {
688 std::string S1 = toString(i+1);
689 std::string S2 = toString(i+1 + NodeVec[i+1].size());
690 return "(" + S1 + "#" + S2 + ")";
691 }
692 case EOP_Unknown: {
693 unsigned NumChildren = N->arity();
694 if (NumChildren == 0)
695 return "(...)";
696 std::string S = "(";
697 unsigned ci = i+1;
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000698 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000699 S += toString(ci);
700 if (j+1 < NumChildren) S += "#";
701 }
702 S += ")";
703 return S;
704 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000705 }
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000706 return "";
Caitlin Sadowski33208342011-09-09 16:11:56 +0000707 }
708};
709
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000710/// \brief A short list of SExprs
711class MutexIDList : public SmallVector<SExpr, 3> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000712public:
Aaron Ballmancea26092014-03-06 19:10:16 +0000713 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000714 void push_back_nodup(const SExpr& M) {
Aaron Ballmancea26092014-03-06 19:10:16 +0000715 if (end() == std::find(begin(), end(), M))
716 push_back(M);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000717 }
718};
719
Caitlin Sadowski33208342011-09-09 16:11:56 +0000720/// \brief This is a helper class that stores info about the most recent
721/// accquire of a Lock.
722///
723/// The main body of the analysis maps MutexIDs to LockDatas.
724struct LockData {
725 SourceLocation AcquireLoc;
726
727 /// \brief LKind stores whether a lock is held shared or exclusively.
728 /// Note that this analysis does not currently support either re-entrant
729 /// locking or lock "upgrading" and "downgrading" between exclusive and
730 /// shared.
731 ///
732 /// FIXME: add support for re-entrant locking and lock up/downgrading
733 LockKind LKind;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000734 bool Asserted; // for asserted locks
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000735 bool Managed; // for ScopedLockable objects
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000736 SExpr UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski33208342011-09-09 16:11:56 +0000737
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000738 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false,
739 bool Asrt=false)
740 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000741 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000742 {}
743
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000744 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000745 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000746 UnderlyingMutex(Mu)
747 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000748
749 bool operator==(const LockData &other) const {
750 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
751 }
752
753 bool operator!=(const LockData &other) const {
754 return !(*this == other);
755 }
756
757 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000758 ID.AddInteger(AcquireLoc.getRawEncoding());
759 ID.AddInteger(LKind);
760 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000761
762 bool isAtLeast(LockKind LK) {
763 return (LK == LK_Shared) || (LKind == LK_Exclusive);
764 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000765};
766
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000767
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000768/// \brief A FactEntry stores a single fact that is known at a particular point
769/// in the program execution. Currently, this is information regarding a lock
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000770/// that is held at that point.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000771struct FactEntry {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000772 SExpr MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000773 LockData LDat;
774
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000775 FactEntry(const SExpr& M, const LockData& L)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000776 : MutID(M), LDat(L)
777 { }
778};
779
780
781typedef unsigned short FactID;
782
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000783/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000784/// the analysis of a single routine.
785class FactManager {
786private:
787 std::vector<FactEntry> Facts;
788
789public:
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000790 FactID newLock(const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000791 Facts.push_back(FactEntry(M,L));
792 return static_cast<unsigned short>(Facts.size() - 1);
793 }
794
795 const FactEntry& operator[](FactID F) const { return Facts[F]; }
796 FactEntry& operator[](FactID F) { return Facts[F]; }
797};
798
799
800/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000801/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000802/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000803/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000804/// locks, so we can get away with doing a linear search for lookup. Note
805/// that a hashtable or map is inappropriate in this case, because lookups
806/// may involve partial pattern matches, rather than exact matches.
807class FactSet {
808private:
809 typedef SmallVector<FactID, 4> FactVec;
810
811 FactVec FactIDs;
812
813public:
814 typedef FactVec::iterator iterator;
815 typedef FactVec::const_iterator const_iterator;
816
817 iterator begin() { return FactIDs.begin(); }
818 const_iterator begin() const { return FactIDs.begin(); }
819
820 iterator end() { return FactIDs.end(); }
821 const_iterator end() const { return FactIDs.end(); }
822
823 bool isEmpty() const { return FactIDs.size() == 0; }
824
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000825 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000826 FactID F = FM.newLock(M, L);
827 FactIDs.push_back(F);
828 return F;
829 }
830
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000831 bool removeLock(FactManager& FM, const SExpr& M) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000832 unsigned n = FactIDs.size();
833 if (n == 0)
834 return false;
835
836 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000837 if (FM[FactIDs[i]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000838 FactIDs[i] = FactIDs[n-1];
839 FactIDs.pop_back();
840 return true;
841 }
842 }
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000843 if (FM[FactIDs[n-1]].MutID.matches(M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000844 FactIDs.pop_back();
845 return true;
846 }
847 return false;
848 }
849
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000850 // Returns an iterator
851 iterator findLockIter(FactManager &FM, const SExpr &M) {
852 for (iterator I = begin(), E = end(); I != E; ++I) {
853 const SExpr &Exp = FM[*I].MutID;
854 if (Exp.matches(M))
855 return I;
856 }
857 return end();
858 }
859
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000860 LockData* findLock(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000861 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000862 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000863 if (Exp.matches(M))
864 return &FM[*I].LDat;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000865 }
866 return 0;
867 }
868
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000869 LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
Chad Rosier78af00f2012-09-07 18:44:15 +0000870 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chad Rosier37a85632012-09-07 19:49:55 +0000871 const SExpr &Exp = FM[*I].MutID;
Chad Rosier78af00f2012-09-07 18:44:15 +0000872 if (Exp.matches(M) || Exp.isUniversal())
873 return &FM[*I].LDat;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000874 }
875 return 0;
876 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000877
878 FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
879 for (const_iterator I=begin(), E=end(); I != E; ++I) {
880 const SExpr& Exp = FM[*I].MutID;
881 if (Exp.partiallyMatches(M)) return &FM[*I];
882 }
883 return 0;
884 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000885};
886
887
888
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000889/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski33208342011-09-09 16:11:56 +0000890/// been locked.
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000891typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000892typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000893
894class LocalVariableMap;
895
Richard Smith92286672012-02-03 04:45:26 +0000896/// A side (entry or exit) of a CFG node.
897enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000898
899/// CFGBlockInfo is a struct which contains all the information that is
900/// maintained for each block in the CFG. See LocalVariableMap for more
901/// information about the contexts.
902struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000903 FactSet EntrySet; // Lockset held at entry to block
904 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000905 LocalVarContext EntryContext; // Context held at entry to block
906 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000907 SourceLocation EntryLoc; // Location of first statement in block
908 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000909 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000910 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000911
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000912 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000913 return Side == CBS_Entry ? EntrySet : ExitSet;
914 }
915 SourceLocation getLocation(CFGBlockSide Side) const {
916 return Side == CBS_Entry ? EntryLoc : ExitLoc;
917 }
918
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000919private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000920 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000921 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000922 { }
923
924public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000925 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000926};
927
928
929
930// A LocalVariableMap maintains a map from local variables to their currently
931// valid definitions. It provides SSA-like functionality when traversing the
932// CFG. Like SSA, each definition or assignment to a variable is assigned a
933// unique name (an integer), which acts as the SSA name for that definition.
934// The total set of names is shared among all CFG basic blocks.
935// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
936// with their SSA-names. Instead, we compute a Context for each point in the
937// code, which maps local variables to the appropriate SSA-name. This map
938// changes with each assignment.
939//
940// The map is computed in a single pass over the CFG. Subsequent analyses can
941// then query the map to find the appropriate Context for a statement, and use
942// that Context to look up the definitions of variables.
943class LocalVariableMap {
944public:
945 typedef LocalVarContext Context;
946
947 /// A VarDefinition consists of an expression, representing the value of the
948 /// variable, along with the context in which that expression should be
949 /// interpreted. A reference VarDefinition does not itself contain this
950 /// information, but instead contains a pointer to a previous VarDefinition.
951 struct VarDefinition {
952 public:
953 friend class LocalVariableMap;
954
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000955 const NamedDecl *Dec; // The original declaration for this variable.
956 const Expr *Exp; // The expression for this variable, OR
957 unsigned Ref; // Reference to another VarDefinition
958 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000959
960 bool isReference() { return !Exp; }
961
962 private:
963 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000964 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000965 : Dec(D), Exp(E), Ref(0), Ctx(C)
966 { }
967
968 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000969 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000970 : Dec(D), Exp(0), Ref(R), Ctx(C)
971 { }
972 };
973
974private:
975 Context::Factory ContextFactory;
976 std::vector<VarDefinition> VarDefinitions;
977 std::vector<unsigned> CtxIndices;
978 std::vector<std::pair<Stmt*, Context> > SavedContexts;
979
980public:
981 LocalVariableMap() {
982 // index 0 is a placeholder for undefined variables (aka phi-nodes).
983 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
984 }
985
986 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000987 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000988 const unsigned *i = Ctx.lookup(D);
989 if (!i)
990 return 0;
991 assert(*i < VarDefinitions.size());
992 return &VarDefinitions[*i];
993 }
994
995 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000996 /// NULL if the expression is not statically known. If successful, also
997 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000998 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000999 const unsigned *P = Ctx.lookup(D);
1000 if (!P)
1001 return 0;
1002
1003 unsigned i = *P;
1004 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001005 if (VarDefinitions[i].Exp) {
1006 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001007 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001008 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001009 i = VarDefinitions[i].Ref;
1010 }
1011 return 0;
1012 }
1013
1014 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1015
1016 /// Return the next context after processing S. This function is used by
1017 /// clients of the class to get the appropriate context when traversing the
1018 /// CFG. It must be called for every assignment or DeclStmt.
1019 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1020 if (SavedContexts[CtxIndex+1].first == S) {
1021 CtxIndex++;
1022 Context Result = SavedContexts[CtxIndex].second;
1023 return Result;
1024 }
1025 return C;
1026 }
1027
1028 void dumpVarDefinitionName(unsigned i) {
1029 if (i == 0) {
1030 llvm::errs() << "Undefined";
1031 return;
1032 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001033 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001034 if (!Dec) {
1035 llvm::errs() << "<<NULL>>";
1036 return;
1037 }
1038 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +00001039 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001040 }
1041
1042 /// Dumps an ASCII representation of the variable map to llvm::errs()
1043 void dump() {
1044 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001045 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001046 unsigned Ref = VarDefinitions[i].Ref;
1047
1048 dumpVarDefinitionName(i);
1049 llvm::errs() << " = ";
1050 if (Exp) Exp->dump();
1051 else {
1052 dumpVarDefinitionName(Ref);
1053 llvm::errs() << "\n";
1054 }
1055 }
1056 }
1057
1058 /// Dumps an ASCII representation of a Context to llvm::errs()
1059 void dumpContext(Context C) {
1060 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001061 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001062 D->printName(llvm::errs());
1063 const unsigned *i = C.lookup(D);
1064 llvm::errs() << " -> ";
1065 dumpVarDefinitionName(*i);
1066 llvm::errs() << "\n";
1067 }
1068 }
1069
1070 /// Builds the variable map.
1071 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1072 std::vector<CFGBlockInfo> &BlockInfo);
1073
1074protected:
1075 // Get the current context index
1076 unsigned getContextIndex() { return SavedContexts.size()-1; }
1077
1078 // Save the current context for later replay
1079 void saveContext(Stmt *S, Context C) {
1080 SavedContexts.push_back(std::make_pair(S,C));
1081 }
1082
1083 // Adds a new definition to the given context, and returns a new context.
1084 // This method should be called when declaring a new variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001085 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001086 assert(!Ctx.contains(D));
1087 unsigned newID = VarDefinitions.size();
1088 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1089 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1090 return NewCtx;
1091 }
1092
1093 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001094 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001095 unsigned newID = VarDefinitions.size();
1096 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1097 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1098 return NewCtx;
1099 }
1100
1101 // Updates a definition only if that definition is already in the map.
1102 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001103 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001104 if (Ctx.contains(D)) {
1105 unsigned newID = VarDefinitions.size();
1106 Context NewCtx = ContextFactory.remove(Ctx, D);
1107 NewCtx = ContextFactory.add(NewCtx, D, newID);
1108 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1109 return NewCtx;
1110 }
1111 return Ctx;
1112 }
1113
1114 // Removes a definition from the context, but keeps the variable name
1115 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001116 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001117 Context NewCtx = Ctx;
1118 if (NewCtx.contains(D)) {
1119 NewCtx = ContextFactory.remove(NewCtx, D);
1120 NewCtx = ContextFactory.add(NewCtx, D, 0);
1121 }
1122 return NewCtx;
1123 }
1124
1125 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001126 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001127 Context NewCtx = Ctx;
1128 if (NewCtx.contains(D)) {
1129 NewCtx = ContextFactory.remove(NewCtx, D);
1130 }
1131 return NewCtx;
1132 }
1133
1134 Context intersectContexts(Context C1, Context C2);
1135 Context createReferenceContext(Context C);
1136 void intersectBackEdge(Context C1, Context C2);
1137
1138 friend class VarMapBuilder;
1139};
1140
1141
1142// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001143CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1144 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001145}
1146
1147
1148/// Visitor which builds a LocalVariableMap
1149class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1150public:
1151 LocalVariableMap* VMap;
1152 LocalVariableMap::Context Ctx;
1153
1154 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1155 : VMap(VM), Ctx(C) {}
1156
1157 void VisitDeclStmt(DeclStmt *S);
1158 void VisitBinaryOperator(BinaryOperator *BO);
1159};
1160
1161
1162// Add new local variables to the variable map
1163void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1164 bool modifiedCtx = false;
1165 DeclGroupRef DGrp = S->getDeclGroup();
1166 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1167 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1168 Expr *E = VD->getInit();
1169
1170 // Add local variables with trivial type to the variable map
1171 QualType T = VD->getType();
1172 if (T.isTrivialType(VD->getASTContext())) {
1173 Ctx = VMap->addDefinition(VD, E, Ctx);
1174 modifiedCtx = true;
1175 }
1176 }
1177 }
1178 if (modifiedCtx)
1179 VMap->saveContext(S, Ctx);
1180}
1181
1182// Update local variable definitions in variable map
1183void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1184 if (!BO->isAssignmentOp())
1185 return;
1186
1187 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1188
1189 // Update the variable map and current context.
1190 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1191 ValueDecl *VDec = DRE->getDecl();
1192 if (Ctx.lookup(VDec)) {
1193 if (BO->getOpcode() == BO_Assign)
1194 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1195 else
1196 // FIXME -- handle compound assignment operators
1197 Ctx = VMap->clearDefinition(VDec, Ctx);
1198 VMap->saveContext(BO, Ctx);
1199 }
1200 }
1201}
1202
1203
1204// Computes the intersection of two contexts. The intersection is the
1205// set of variables which have the same definition in both contexts;
1206// variables with different definitions are discarded.
1207LocalVariableMap::Context
1208LocalVariableMap::intersectContexts(Context C1, Context C2) {
1209 Context Result = C1;
1210 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001211 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001212 unsigned i1 = I.getData();
1213 const unsigned *i2 = C2.lookup(Dec);
1214 if (!i2) // variable doesn't exist on second path
1215 Result = removeDefinition(Dec, Result);
1216 else if (*i2 != i1) // variable exists, but has different definition
1217 Result = clearDefinition(Dec, Result);
1218 }
1219 return Result;
1220}
1221
1222// For every variable in C, create a new variable that refers to the
1223// definition in C. Return a new context that contains these new variables.
1224// (We use this for a naive implementation of SSA on loop back-edges.)
1225LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1226 Context Result = getEmptyContext();
1227 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001228 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001229 unsigned i = I.getData();
1230 Result = addReference(Dec, i, Result);
1231 }
1232 return Result;
1233}
1234
1235// This routine also takes the intersection of C1 and C2, but it does so by
1236// altering the VarDefinitions. C1 must be the result of an earlier call to
1237// createReferenceContext.
1238void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1239 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001240 const NamedDecl *Dec = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001241 unsigned i1 = I.getData();
1242 VarDefinition *VDef = &VarDefinitions[i1];
1243 assert(VDef->isReference());
1244
1245 const unsigned *i2 = C2.lookup(Dec);
1246 if (!i2 || (*i2 != i1))
1247 VDef->Ref = 0; // Mark this variable as undefined
1248 }
1249}
1250
1251
1252// Traverse the CFG in topological order, so all predecessors of a block
1253// (excluding back-edges) are visited before the block itself. At
1254// each point in the code, we calculate a Context, which holds the set of
1255// variable definitions which are visible at that point in execution.
1256// Visible variables are mapped to their definitions using an array that
1257// contains all definitions.
1258//
1259// At join points in the CFG, the set is computed as the intersection of
1260// the incoming sets along each edge, E.g.
1261//
1262// { Context | VarDefinitions }
1263// int x = 0; { x -> x1 | x1 = 0 }
1264// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1265// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1266// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1267// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1268//
1269// This is essentially a simpler and more naive version of the standard SSA
1270// algorithm. Those definitions that remain in the intersection are from blocks
1271// that strictly dominate the current block. We do not bother to insert proper
1272// phi nodes, because they are not used in our analysis; instead, wherever
1273// a phi node would be required, we simply remove that definition from the
1274// context (E.g. x above).
1275//
1276// The initial traversal does not capture back-edges, so those need to be
1277// handled on a separate pass. Whenever the first pass encounters an
1278// incoming back edge, it duplicates the context, creating new definitions
1279// that refer back to the originals. (These correspond to places where SSA
1280// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +00001281// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001282// node was actually required.) E.g.
1283//
1284// { Context | VarDefinitions }
1285// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1286// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1287// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1288// ... { y -> y1 | x3 = 2, x2 = 1, ... }
1289//
1290void LocalVariableMap::traverseCFG(CFG *CFGraph,
1291 PostOrderCFGView *SortedGraph,
1292 std::vector<CFGBlockInfo> &BlockInfo) {
1293 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1294
1295 CtxIndices.resize(CFGraph->getNumBlockIDs());
1296
1297 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1298 E = SortedGraph->end(); I!= E; ++I) {
1299 const CFGBlock *CurrBlock = *I;
1300 int CurrBlockID = CurrBlock->getBlockID();
1301 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1302
1303 VisitedBlocks.insert(CurrBlock);
1304
1305 // Calculate the entry context for the current block
1306 bool HasBackEdges = false;
1307 bool CtxInit = true;
1308 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1309 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1310 // if *PI -> CurrBlock is a back edge, so skip it
1311 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1312 HasBackEdges = true;
1313 continue;
1314 }
1315
1316 int PrevBlockID = (*PI)->getBlockID();
1317 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1318
1319 if (CtxInit) {
1320 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1321 CtxInit = false;
1322 }
1323 else {
1324 CurrBlockInfo->EntryContext =
1325 intersectContexts(CurrBlockInfo->EntryContext,
1326 PrevBlockInfo->ExitContext);
1327 }
1328 }
1329
1330 // Duplicate the context if we have back-edges, so we can call
1331 // intersectBackEdges later.
1332 if (HasBackEdges)
1333 CurrBlockInfo->EntryContext =
1334 createReferenceContext(CurrBlockInfo->EntryContext);
1335
1336 // Create a starting context index for the current block
1337 saveContext(0, CurrBlockInfo->EntryContext);
1338 CurrBlockInfo->EntryIndex = getContextIndex();
1339
1340 // Visit all the statements in the basic block.
1341 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1342 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1343 BE = CurrBlock->end(); BI != BE; ++BI) {
1344 switch (BI->getKind()) {
1345 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00001346 CFGStmt CS = BI->castAs<CFGStmt>();
1347 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001348 break;
1349 }
1350 default:
1351 break;
1352 }
1353 }
1354 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1355
1356 // Mark variables on back edges as "unknown" if they've been changed.
1357 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1358 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1359 // if CurrBlock -> *SI is *not* a back edge
1360 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1361 continue;
1362
1363 CFGBlock *FirstLoopBlock = *SI;
1364 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1365 Context LoopEnd = CurrBlockInfo->ExitContext;
1366 intersectBackEdge(LoopBegin, LoopEnd);
1367 }
1368 }
1369
1370 // Put an extra entry at the end of the indexed context array
1371 unsigned exitID = CFGraph->getExit().getBlockID();
1372 saveContext(0, BlockInfo[exitID].ExitContext);
1373}
1374
Richard Smith92286672012-02-03 04:45:26 +00001375/// Find the appropriate source locations to use when producing diagnostics for
1376/// each block in the CFG.
1377static void findBlockLocations(CFG *CFGraph,
1378 PostOrderCFGView *SortedGraph,
1379 std::vector<CFGBlockInfo> &BlockInfo) {
1380 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1381 E = SortedGraph->end(); I!= E; ++I) {
1382 const CFGBlock *CurrBlock = *I;
1383 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1384
1385 // Find the source location of the last statement in the block, if the
1386 // block is not empty.
1387 if (const Stmt *S = CurrBlock->getTerminator()) {
1388 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1389 } else {
1390 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1391 BE = CurrBlock->rend(); BI != BE; ++BI) {
1392 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001393 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1394 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001395 break;
1396 }
1397 }
1398 }
1399
1400 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1401 // This block contains at least one statement. Find the source location
1402 // of the first statement in the block.
1403 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1404 BE = CurrBlock->end(); BI != BE; ++BI) {
1405 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +00001406 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1407 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +00001408 break;
1409 }
1410 }
1411 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1412 CurrBlock != &CFGraph->getExit()) {
1413 // The block is empty, and has a single predecessor. Use its exit
1414 // location.
1415 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1416 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1417 }
1418 }
1419}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001420
1421/// \brief Class which implements the core thread safety analysis routines.
1422class ThreadSafetyAnalyzer {
1423 friend class BuildLockset;
1424
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001425 ThreadSafetyHandler &Handler;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001426 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001427 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001428 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001429
1430public:
1431 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1432
Aaron Ballmane0449042014-04-01 21:43:23 +00001433 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat,
1434 StringRef DiagKind);
1435 void removeLock(FactSet &FSet, const SExpr &Mutex, SourceLocation UnlockLoc,
1436 bool FullyRemove, LockKind Kind, StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001437
1438 template <typename AttrType>
1439 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001440 const NamedDecl *D, VarDecl *SelfDecl=0);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001441
1442 template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001443 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1444 const NamedDecl *D,
1445 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1446 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001447
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001448 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1449 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001450
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001451 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1452 const CFGBlock* PredBlock,
1453 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001454
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001455 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1456 SourceLocation JoinLoc,
1457 LockErrorKind LEK1, LockErrorKind LEK2,
1458 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001459
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001460 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1461 SourceLocation JoinLoc, LockErrorKind LEK1,
1462 bool Modify=true) {
1463 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001464 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001465
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001466 void runAnalysis(AnalysisDeclContext &AC);
1467};
1468
Aaron Ballmane0449042014-04-01 21:43:23 +00001469/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1470static const ValueDecl *getValueDecl(const Expr *Exp) {
1471 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1472 return getValueDecl(CE->getSubExpr());
1473
1474 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1475 return DR->getDecl();
1476
1477 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1478 return ME->getMemberDecl();
1479
1480 return nullptr;
1481}
1482
1483template <typename Ty>
1484class has_arg_iterator {
1485 typedef char yes[1];
1486 typedef char no[2];
1487
1488 template <typename Inner>
1489 static yes& test(Inner *I, decltype(I->args_begin()) * = nullptr);
1490
1491 template <typename>
1492 static no& test(...);
1493
1494public:
1495 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1496};
1497
1498static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1499 return A->getName();
1500}
1501
1502static StringRef ClassifyDiagnostic(QualType VDT) {
1503 // We need to look at the declaration of the type of the value to determine
1504 // which it is. The type should either be a record or a typedef, or a pointer
1505 // or reference thereof.
1506 if (const auto *RT = VDT->getAs<RecordType>()) {
1507 if (const auto *RD = RT->getDecl())
1508 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1509 return ClassifyDiagnostic(CA);
1510 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1511 if (const auto *TD = TT->getDecl())
1512 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1513 return ClassifyDiagnostic(CA);
1514 } else if (VDT->isPointerType() || VDT->isReferenceType())
1515 return ClassifyDiagnostic(VDT->getPointeeType());
1516
1517 return "mutex";
1518}
1519
1520static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1521 assert(VD && "No ValueDecl passed");
1522
1523 // The ValueDecl is the declaration of a mutex or role (hopefully).
1524 return ClassifyDiagnostic(VD->getType());
1525}
1526
1527template <typename AttrTy>
1528static typename std::enable_if<!has_arg_iterator<AttrTy>::value,
1529 StringRef>::type
1530ClassifyDiagnostic(const AttrTy *A) {
1531 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1532 return ClassifyDiagnostic(VD);
1533 return "mutex";
1534}
1535
1536template <typename AttrTy>
1537static typename std::enable_if<has_arg_iterator<AttrTy>::value,
1538 StringRef>::type
1539ClassifyDiagnostic(const AttrTy *A) {
1540 for (auto I = A->args_begin(), E = A->args_end(); I != E; ++I) {
1541 if (const ValueDecl *VD = getValueDecl(*I))
1542 return ClassifyDiagnostic(VD);
1543 }
1544 return "mutex";
1545}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001546
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001547/// \brief Add a new lock to the lockset, warning if the lock is already there.
1548/// \param Mutex -- the Mutex expression for the lock
1549/// \param LDat -- the LockData for the lock
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001550void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
Aaron Ballmane0449042014-04-01 21:43:23 +00001551 const LockData &LDat, StringRef DiagKind) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001552 // FIXME: deal with acquired before/after annotations.
1553 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001554 if (Mutex.shouldIgnore())
1555 return;
1556
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001557 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001558 if (!LDat.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00001559 Handler.handleDoubleLock(DiagKind, Mutex.toString(), LDat.AcquireLoc);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001560 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001561 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001562 }
1563}
1564
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001565
1566/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenek78094ca2012-08-22 23:50:41 +00001567/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001568/// \param UnlockLoc The source location of the unlock (only used in error msg)
Aaron Ballmandf115d92014-03-21 14:48:48 +00001569void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const SExpr &Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001570 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001571 bool FullyRemove, LockKind ReceivedKind,
1572 StringRef DiagKind) {
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001573 if (Mutex.shouldIgnore())
1574 return;
1575
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001576 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001577 if (!LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001578 Handler.handleUnmatchedUnlock(DiagKind, Mutex.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001579 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001580 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001581
Aaron Ballmandf115d92014-03-21 14:48:48 +00001582 // Generic lock removal doesn't care about lock kind mismatches, but
1583 // otherwise diagnose when the lock kinds are mismatched.
1584 if (ReceivedKind != LK_Generic && LDat->LKind != ReceivedKind) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001585 Handler.handleIncorrectUnlockKind(DiagKind, Mutex.toString(), LDat->LKind,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001586 ReceivedKind, UnlockLoc);
1587 return;
1588 }
1589
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001590 if (LDat->UnderlyingMutex.isValid()) {
1591 // This is scoped lockable object, which manages the real mutex.
1592 if (FullyRemove) {
1593 // We're destroying the managing object.
1594 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001595 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1596 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001597 } else {
1598 // We're releasing the underlying mutex, but not destroying the
1599 // managing object. Warn on dual release.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001600 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001601 Handler.handleUnmatchedUnlock(
1602 DiagKind, LDat->UnderlyingMutex.toString(), UnlockLoc);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001603 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001604 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1605 return;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001606 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001607 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001608 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001609}
1610
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001611
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001612/// \brief Extract the list of mutexIDs from the attribute on an expression,
1613/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001614template <typename AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001615void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001616 Expr *Exp, const NamedDecl *D,
1617 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001618 typedef typename AttrType::args_iterator iterator_type;
1619
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001620 if (Attr->args_size() == 0) {
1621 // The mutex held is the "this" object.
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001622 SExpr Mu(0, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001623 if (!Mu.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +00001624 SExpr::warnInvalidLock(Handler, 0, Exp, D, ClassifyDiagnostic(Attr));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001625 else
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001626 Mtxs.push_back_nodup(Mu);
1627 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001628 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001629
1630 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001631 SExpr Mu(*I, Exp, D, SelfDecl);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001632 if (!Mu.isValid())
Aaron Ballmane0449042014-04-01 21:43:23 +00001633 SExpr::warnInvalidLock(Handler, *I, Exp, D, ClassifyDiagnostic(Attr));
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001634 else
1635 Mtxs.push_back_nodup(Mu);
1636 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001637}
1638
1639
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001640/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1641/// trylock applies to the given edge, then push them onto Mtxs, discarding
1642/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001643template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001644void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1645 Expr *Exp, const NamedDecl *D,
1646 const CFGBlock *PredBlock,
1647 const CFGBlock *CurrBlock,
1648 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001649 // Find out which branch has the lock
1650 bool branch = 0;
1651 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1652 branch = BLE->getValue();
1653 }
1654 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1655 branch = ILE->getValue().getBoolValue();
1656 }
1657 int branchnum = branch ? 0 : 1;
1658 if (Neg) branchnum = !branchnum;
1659
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001660 // If we've taken the trylock branch, then add the lock
1661 int i = 0;
1662 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1663 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1664 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001665 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001666 }
1667 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001668}
1669
1670
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001671bool getStaticBooleanValue(Expr* E, bool& TCond) {
1672 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1673 TCond = false;
1674 return true;
1675 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1676 TCond = BLE->getValue();
1677 return true;
1678 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1679 TCond = ILE->getValue().getBoolValue();
1680 return true;
1681 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1682 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1683 }
1684 return false;
1685}
1686
1687
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001688// If Cond can be traced back to a function call, return the call expression.
1689// The negate variable should be called with false, and will be set to true
1690// if the function call is negated, e.g. if (!mu.tryLock(...))
1691const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1692 LocalVarContext C,
1693 bool &Negate) {
1694 if (!Cond)
1695 return 0;
1696
1697 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1698 return CallExp;
1699 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001700 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1701 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1702 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001703 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1704 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1705 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001706 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1707 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1708 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001709 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1710 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1711 return getTrylockCallExpr(E, C, Negate);
1712 }
1713 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1714 if (UOP->getOpcode() == UO_LNot) {
1715 Negate = !Negate;
1716 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1717 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001718 return 0;
1719 }
1720 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1721 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1722 if (BOP->getOpcode() == BO_NE)
1723 Negate = !Negate;
1724
1725 bool TCond = false;
1726 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1727 if (!TCond) Negate = !Negate;
1728 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1729 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001730 TCond = false;
1731 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001732 if (!TCond) Negate = !Negate;
1733 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1734 }
1735 return 0;
1736 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001737 if (BOP->getOpcode() == BO_LAnd) {
1738 // LHS must have been evaluated in a different block.
1739 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1740 }
1741 if (BOP->getOpcode() == BO_LOr) {
1742 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1743 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001744 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001745 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001746 return 0;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001747}
1748
1749
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001750/// \brief Find the lockset that holds on the edge between PredBlock
1751/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1752/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001753void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1754 const FactSet &ExitSet,
1755 const CFGBlock *PredBlock,
1756 const CFGBlock *CurrBlock) {
1757 Result = ExitSet;
1758
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001759 const Stmt *Cond = PredBlock->getTerminatorCondition();
1760 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001761 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001762
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001763 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001764 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1765 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001766 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001767
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001768 CallExpr *Exp =
1769 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001770 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001771 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001772
1773 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1774 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001775 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001776
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001777 MutexIDList ExclusiveLocksToAdd;
1778 MutexIDList SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001779
1780 // If the condition is a call to a Trylock function, then grab the attributes
1781 AttrVec &ArgAttrs = FunDecl->getAttrs();
1782 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1783 Attr *Attr = ArgAttrs[i];
1784 switch (Attr->getKind()) {
1785 case attr::ExclusiveTrylockFunction: {
1786 ExclusiveTrylockFunctionAttr *A =
1787 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001788 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1789 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001790 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001791 break;
1792 }
1793 case attr::SharedTrylockFunction: {
1794 SharedTrylockFunctionAttr *A =
1795 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001796 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001797 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001798 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001799 break;
1800 }
1801 default:
1802 break;
1803 }
1804 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001805
1806 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001807 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001808 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1809 addLock(Result, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
1810 CapDiagKind);
1811 for (const auto &SharedLockToAdd : SharedLocksToAdd)
1812 addLock(Result, SharedLockToAdd, LockData(Loc, LK_Shared), CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001813}
1814
Caitlin Sadowski33208342011-09-09 16:11:56 +00001815/// \brief We use this class to visit different types of expressions in
1816/// CFGBlocks, and build up the lockset.
1817/// An expression may cause us to add or remove locks from the lockset, or else
1818/// output error messages related to missing locks.
1819/// FIXME: In future, we may be able to not inherit from a visitor.
1820class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001821 friend class ThreadSafetyAnalyzer;
1822
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001823 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001824 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001825 LocalVariableMap::Context LVarCtx;
1826 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001827
1828 // Helper functions
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001829
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001830 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001831 Expr *MutexExp, ProtectedOperationKind POK,
1832 StringRef DiagKind);
1833 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1834 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001835
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001836 void checkAccess(const Expr *Exp, AccessKind AK);
1837 void checkPtAccess(const Expr *Exp, AccessKind AK);
1838
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001839 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001840
Caitlin Sadowski33208342011-09-09 16:11:56 +00001841public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001842 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001843 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001844 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001845 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001846 LVarCtx(Info.EntryContext),
1847 CtxIndex(Info.EntryIndex)
1848 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001849
1850 void VisitUnaryOperator(UnaryOperator *UO);
1851 void VisitBinaryOperator(BinaryOperator *BO);
1852 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001853 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001854 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001855 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001856};
1857
Caitlin Sadowski33208342011-09-09 16:11:56 +00001858/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001859/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001860void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001861 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001862 ProtectedOperationKind POK,
1863 StringRef DiagKind) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001864 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001865
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00001866 SExpr Mutex(MutexExp, Exp, D);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001867 if (!Mutex.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001868 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001869 return;
1870 } else if (Mutex.shouldIgnore()) {
1871 return;
1872 }
1873
1874 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001875 bool NoError = true;
1876 if (!LDat) {
1877 // No exact match found. Look for a partial match.
1878 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1879 if (FEntry) {
1880 // Warn that there's no precise match.
1881 LDat = &FEntry->LDat;
1882 std::string PartMatchStr = FEntry->MutID.toString();
1883 StringRef PartMatchName(PartMatchStr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001884 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1885 LK, Exp->getExprLoc(),
1886 &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001887 } else {
1888 // Warn that there's no match at all.
Aaron Ballmane0449042014-04-01 21:43:23 +00001889 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(),
1890 LK, Exp->getExprLoc());
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001891 }
1892 NoError = false;
1893 }
1894 // Make sure the mutex we found is the right kind.
1895 if (NoError && LDat && !LDat->isAtLeast(LK))
Aaron Ballmane0449042014-04-01 21:43:23 +00001896 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Mutex.toString(), LK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001897 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001898}
1899
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001900/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001901void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1902 Expr *MutexExp,
1903 StringRef DiagKind) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001904 SExpr Mutex(MutexExp, Exp, D);
1905 if (!Mutex.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001906 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001907 return;
1908 }
1909
1910 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
Aaron Ballmane0449042014-04-01 21:43:23 +00001911 if (LDat)
1912 Analyzer->Handler.handleFunExcludesLock(
1913 DiagKind, D->getNameAsString(), Mutex.toString(), Exp->getExprLoc());
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001914}
1915
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001916/// \brief Checks guarded_by and pt_guarded_by attributes.
1917/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1918/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1919/// Similarly, we check if the access is to an expression that dereferences
1920/// a pointer marked with pt_guarded_by.
1921void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1922 Exp = Exp->IgnoreParenCasts();
1923
1924 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1925 // For dereferences
1926 if (UO->getOpcode() == clang::UO_Deref)
1927 checkPtAccess(UO->getSubExpr(), AK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001928 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001929 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001930
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001931 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001932 checkPtAccess(AE->getLHS(), AK);
1933 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001934 }
1935
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001936 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1937 if (ME->isArrow())
1938 checkPtAccess(ME->getBase(), AK);
1939 else
1940 checkAccess(ME->getBase(), AK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001941 }
1942
Caitlin Sadowski33208342011-09-09 16:11:56 +00001943 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001944 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001945 return;
1946
Aaron Ballman9ead1242013-12-19 02:39:40 +00001947 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001948 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarAccess, AK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001949 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001950
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001951 for (const auto *I : D->specific_attrs<GuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001952 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess,
1953 ClassifyDiagnostic(I));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001954}
1955
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001956/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1957void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001958 while (true) {
1959 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1960 Exp = PE->getSubExpr();
1961 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001962 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001963 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1964 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1965 // If it's an actual array, and not a pointer, then it's elements
1966 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1967 checkAccess(CE->getSubExpr(), AK);
1968 return;
1969 }
1970 Exp = CE->getSubExpr();
1971 continue;
1972 }
1973 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001974 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001975
1976 const ValueDecl *D = getValueDecl(Exp);
1977 if (!D || !D->hasAttrs())
1978 return;
1979
Aaron Ballman9ead1242013-12-19 02:39:40 +00001980 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001981 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarDereference, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001982 Exp->getExprLoc());
1983
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001984 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001985 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference,
1986 ClassifyDiagnostic(I));
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001987}
1988
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001989/// \brief Process a function call, method call, constructor call,
1990/// or destructor call. This involves looking at the attributes on the
1991/// corresponding function/method/constructor/destructor, issuing warnings,
1992/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001993///
1994/// FIXME: For classes annotated with one of the guarded annotations, we need
1995/// to treat const method calls as reads and non-const method calls as writes,
1996/// and check that the appropriate locks are held. Non-const method calls with
1997/// the same signature as const method calls can be also treated as reads.
1998///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001999void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002000 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002001 const AttrVec &ArgAttrs = D->getAttrs();
Aaron Ballmandf115d92014-03-21 14:48:48 +00002002 MutexIDList ExclusiveLocksToAdd, SharedLocksToAdd;
2003 MutexIDList ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
Aaron Ballmane0449042014-04-01 21:43:23 +00002004 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002005
Caitlin Sadowski33208342011-09-09 16:11:56 +00002006 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002007 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
2008 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002009 // When we encounter a lock function, we need to add the lock to our
2010 // lockset.
2011 case attr::AcquireCapability: {
2012 auto *A = cast<AcquireCapabilityAttr>(At);
2013 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
2014 : ExclusiveLocksToAdd,
2015 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002016
2017 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002018 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002019 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002020
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002021 // An assert will add a lock to the lockset, but will not generate
2022 // a warning if it is already there, and will not generate a warning
2023 // if it is not removed.
2024 case attr::AssertExclusiveLock: {
2025 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
2026
2027 MutexIDList AssertLocks;
2028 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002029 for (const auto &AssertLock : AssertLocks)
2030 Analyzer->addLock(FSet, AssertLock,
2031 LockData(Loc, LK_Exclusive, false, true),
2032 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002033 break;
2034 }
2035 case attr::AssertSharedLock: {
2036 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
2037
2038 MutexIDList AssertLocks;
2039 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002040 for (const auto &AssertLock : AssertLocks)
2041 Analyzer->addLock(FSet, AssertLock,
2042 LockData(Loc, LK_Shared, false, true),
2043 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002044 break;
2045 }
2046
Caitlin Sadowski33208342011-09-09 16:11:56 +00002047 // When we encounter an unlock function, we need to remove unlocked
2048 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002049 case attr::ReleaseCapability: {
2050 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002051 if (A->isGeneric())
2052 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
2053 else if (A->isShared())
2054 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
2055 else
2056 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00002057
2058 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002059 break;
2060 }
2061
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002062 case attr::RequiresCapability: {
2063 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002064
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002065 for (RequiresCapabilityAttr::args_iterator I = A->args_begin(),
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002066 E = A->args_end(); I != E; ++I)
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002067 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, *I,
Aaron Ballmane0449042014-04-01 21:43:23 +00002068 POK_FunctionCall, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002069 break;
2070 }
2071
2072 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002073 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00002074
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002075 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
2076 E = A->args_end(); I != E; ++I) {
Aaron Ballmane0449042014-04-01 21:43:23 +00002077 warnIfMutexHeld(D, Exp, *I, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002078 }
2079 break;
2080 }
2081
Alp Tokerd4733632013-12-05 04:47:09 +00002082 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00002083 default:
2084 break;
2085 }
2086 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002087
2088 // Figure out if we're calling the constructor of scoped lockable class
2089 bool isScopedVar = false;
2090 if (VD) {
2091 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
2092 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00002093 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002094 isScopedVar = true;
2095 }
2096 }
2097
2098 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00002099 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002100 Analyzer->addLock(FSet, M, LockData(Loc, LK_Exclusive, isScopedVar),
2101 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002102 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002103 Analyzer->addLock(FSet, M, LockData(Loc, LK_Shared, isScopedVar),
2104 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002105
2106 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2107 // FIXME -- this doesn't work if we acquire multiple locks.
2108 if (isScopedVar) {
2109 SourceLocation MLoc = VD->getLocation();
2110 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002111 SExpr SMutex(&DRE, 0, 0);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002112
Aaron Ballmandf115d92014-03-21 14:48:48 +00002113 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002114 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive, M),
2115 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002116 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00002117 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared, M),
2118 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002119 }
2120
2121 // Remove locks.
2122 // FIXME -- should only fully remove if the attribute refers to 'this'.
2123 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002124 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002125 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002126 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002127 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00002128 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00002129 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002130}
2131
DeLesley Hutchins9d530332012-01-06 19:16:50 +00002132
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002133/// \brief For unary operations which read and write a variable, we need to
2134/// check whether we hold any required mutexes. Reads are checked in
2135/// VisitCastExpr.
2136void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2137 switch (UO->getOpcode()) {
2138 case clang::UO_PostDec:
2139 case clang::UO_PostInc:
2140 case clang::UO_PreDec:
2141 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002142 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002143 break;
2144 }
2145 default:
2146 break;
2147 }
2148}
2149
2150/// For binary operations which assign to a variable (writes), we need to check
2151/// whether we hold any required mutexes.
2152/// FIXME: Deal with non-primitive types.
2153void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2154 if (!BO->isAssignmentOp())
2155 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002156
2157 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002158 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002159
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002160 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002161}
2162
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002163
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002164/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2165/// need to ensure we hold any required mutexes.
2166/// FIXME: Deal with non-primitive types.
2167void BuildLockset::VisitCastExpr(CastExpr *CE) {
2168 if (CE->getCastKind() != CK_LValueToRValue)
2169 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00002170 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002171}
2172
2173
DeLesley Hutchins714296c2011-12-29 00:56:48 +00002174void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002175 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2176 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2177 // ME can be null when calling a method pointer
2178 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002179
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002180 if (ME && MD) {
2181 if (ME->isArrow()) {
2182 if (MD->isConst()) {
2183 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2184 } else { // FIXME -- should be AK_Written
2185 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002186 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002187 } else {
2188 if (MD->isConst())
2189 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2190 else // FIXME -- should be AK_Written
2191 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002192 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002193 }
2194 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2195 switch (OE->getOperator()) {
2196 case OO_Equal: {
2197 const Expr *Target = OE->getArg(0);
2198 const Expr *Source = OE->getArg(1);
2199 checkAccess(Target, AK_Written);
2200 checkAccess(Source, AK_Read);
2201 break;
2202 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002203 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002204 case OO_Arrow:
2205 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00002206 const Expr *Obj = OE->getArg(0);
2207 checkAccess(Obj, AK_Read);
2208 checkPtAccess(Obj, AK_Read);
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002209 break;
2210 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002211 default: {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002212 const Expr *Obj = OE->getArg(0);
2213 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002214 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002215 }
2216 }
2217 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002218 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2219 if(!D || !D->hasAttrs())
2220 return;
2221 handleCall(Exp, D);
2222}
2223
2224void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002225 const CXXConstructorDecl *D = Exp->getConstructor();
2226 if (D && D->isCopyConstructor()) {
2227 const Expr* Source = Exp->getArg(0);
2228 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002229 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002230 // FIXME -- only handles constructors in DeclStmt below.
2231}
2232
2233void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002234 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002235 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002236
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002237 DeclGroupRef DGrp = S->getDeclGroup();
2238 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2239 Decl *D = *I;
2240 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2241 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002242 // handle constructors that involve temporaries
2243 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2244 E = EWC->getSubExpr();
2245
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002246 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2247 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2248 if (!CtorD || !CtorD->hasAttrs())
2249 return;
2250 handleCall(CE, CtorD, VD);
2251 }
2252 }
2253 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002254}
2255
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002256
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002257
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002258/// \brief Compute the intersection of two locksets and issue warnings for any
2259/// locks in the symmetric difference.
2260///
2261/// This function is used at a merge point in the CFG when comparing the lockset
2262/// of each branch being merged. For example, given the following sequence:
2263/// A; if () then B; else C; D; we need to check that the lockset after B and C
2264/// are the same. In the event of a difference, we use the intersection of these
2265/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002266///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002267/// \param FSet1 The first lockset.
2268/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002269/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002270/// \param LEK1 The error message to report if a mutex is missing from LSet1
2271/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002272void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2273 const FactSet &FSet2,
2274 SourceLocation JoinLoc,
2275 LockErrorKind LEK1,
2276 LockErrorKind LEK2,
2277 bool Modify) {
2278 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002279
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002280 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002281 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2282 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002283 const SExpr &FSet2Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002284 const LockData &LDat2 = FactMan[*I].LDat;
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002285 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002286
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002287 if (I1 != FSet1.end()) {
2288 const LockData* LDat1 = &FactMan[*I1].LDat;
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002289 if (LDat1->LKind != LDat2.LKind) {
Aaron Ballmane0449042014-04-01 21:43:23 +00002290 Handler.handleExclusiveAndShared("mutex", FSet2Mutex.toString(),
2291 LDat2.AcquireLoc, LDat1->AcquireLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002292 if (Modify && LDat1->LKind != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002293 // Take the exclusive lock, which is the one in FSet2.
2294 *I1 = *I;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002295 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002296 }
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002297 else if (LDat1->Asserted && !LDat2.Asserted) {
2298 // The non-asserted lock in FSet2 is the one we want to track.
2299 *I1 = *I;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002300 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002301 } else {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002302 if (LDat2.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002303 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002304 // If this is a scoped lock that manages another mutex, and if the
2305 // underlying mutex is still held, then warn about the underlying
2306 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00002307 Handler.handleMutexHeldEndOfScope("mutex",
2308 LDat2.UnderlyingMutex.toString(),
2309 LDat2.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002310 }
2311 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002312 else if (!LDat2.Managed && !FSet2Mutex.isUniversal() && !LDat2.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00002313 Handler.handleMutexHeldEndOfScope("mutex", FSet2Mutex.toString(),
2314 LDat2.AcquireLoc, JoinLoc, LEK1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002315 }
2316 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002317
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002318 // Find locks in FSet1 that are not in FSet2, and remove them.
2319 for (FactSet::const_iterator I = FSet1Orig.begin(), E = FSet1Orig.end();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002320 I != E; ++I) {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +00002321 const SExpr &FSet1Mutex = FactMan[*I].MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002322 const LockData &LDat1 = FactMan[*I].LDat;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002323
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002324 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002325 if (LDat1.UnderlyingMutex.isValid()) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002326 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002327 // If this is a scoped lock that manages another mutex, and if the
2328 // underlying mutex is still held, then warn about the underlying
2329 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00002330 Handler.handleMutexHeldEndOfScope("mutex",
2331 LDat1.UnderlyingMutex.toString(),
2332 LDat1.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00002333 }
2334 }
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002335 else if (!LDat1.Managed && !FSet1Mutex.isUniversal() && !LDat1.Asserted)
Aaron Ballmane0449042014-04-01 21:43:23 +00002336 Handler.handleMutexHeldEndOfScope("mutex", FSet1Mutex.toString(),
2337 LDat1.AcquireLoc, JoinLoc, LEK2);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002338 if (Modify)
2339 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002340 }
2341 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002342}
2343
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002344
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002345// Return true if block B never continues to its successors.
2346inline bool neverReturns(const CFGBlock* B) {
2347 if (B->hasNoReturnElement())
2348 return true;
2349 if (B->empty())
2350 return false;
2351
2352 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002353 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2354 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002355 return true;
2356 }
2357 return false;
2358}
2359
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002360
Caitlin Sadowski33208342011-09-09 16:11:56 +00002361/// \brief Check a function's CFG for thread-safety violations.
2362///
2363/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2364/// at the end of each block, and issue warnings for thread safety violations.
2365/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002366void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002367 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2368 // For now, we just use the walker to set things up.
2369 threadSafety::CFGWalker walker;
2370 if (!walker.init(AC))
2371 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002372
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002373 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002374 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002375
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002376 CFG *CFGraph = walker.CFGraph;
2377 const NamedDecl *D = walker.FDecl;
2378
Aaron Ballman9ead1242013-12-19 02:39:40 +00002379 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002380 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002381
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002382 // FIXME: Do something a bit more intelligent inside constructor and
2383 // destructor code. Constructors and destructors must assume unique access
2384 // to 'this', so checks on member variable access is disabled, but we should
2385 // still enable checks on other objects.
2386 if (isa<CXXConstructorDecl>(D))
2387 return; // Don't check inside constructors.
2388 if (isa<CXXDestructorDecl>(D))
2389 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002390
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002391 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002392 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002393
2394 // We need to explore the CFG via a "topological" ordering.
2395 // That way, we will be guaranteed to have information about required
2396 // predecessor locksets when exploring a new block.
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002397 PostOrderCFGView *SortedGraph = walker.SortedGraph;
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002398 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002399
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002400 // Mark entry block as reachable
2401 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2402
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002403 // Compute SSA names for local variables
2404 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2405
Richard Smith92286672012-02-03 04:45:26 +00002406 // Fill in source locations for all CFGBlocks.
2407 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2408
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002409 MutexIDList ExclusiveLocksAcquired;
2410 MutexIDList SharedLocksAcquired;
2411 MutexIDList LocksReleased;
2412
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002413 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002414 // to initial lockset. Also turn off checking for lock and unlock functions.
2415 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002416 if (!SortedGraph->empty() && D->hasAttrs()) {
2417 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002418 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002419 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002420
2421 MutexIDList ExclusiveLocksToAdd;
2422 MutexIDList SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002423 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002424
2425 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002426 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002427 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002428 Loc = Attr->getLocation();
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002429 if (RequiresCapabilityAttr *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2430 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2431 0, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002432 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002433 } else if (auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002434 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2435 // We must ignore such methods.
2436 if (A->args_size() == 0)
2437 return;
2438 // FIXME -- deal with exclusive vs. shared unlock functions?
2439 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2440 getMutexIDs(LocksReleased, A, (Expr*) 0, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002441 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002442 } else if (auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002443 if (A->args_size() == 0)
2444 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002445 getMutexIDs(A->isShared() ? SharedLocksAcquired
2446 : ExclusiveLocksAcquired,
2447 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002448 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002449 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2450 // Don't try to check trylock functions for now
2451 return;
2452 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2453 // Don't try to check trylock functions for now
2454 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002455 }
2456 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002457
2458 // FIXME -- Loc can be wrong here.
Aaron Ballmane0449042014-04-01 21:43:23 +00002459 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
2460 addLock(InitialLockset, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
2461 CapDiagKind);
2462 for (const auto &SharedLockToAdd : SharedLocksToAdd)
2463 addLock(InitialLockset, SharedLockToAdd, LockData(Loc, LK_Shared),
2464 CapDiagKind);
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002465 }
2466
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002467 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2468 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002469 const CFGBlock *CurrBlock = *I;
2470 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002471 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002472
2473 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002474 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002475
2476 // Iterate through the predecessor blocks and warn if the lockset for all
2477 // predecessors is not the same. We take the entry lockset of the current
2478 // block to be the intersection of all previous locksets.
2479 // FIXME: By keeping the intersection, we may output more errors in future
2480 // for a lock which is not in the intersection, but was in the union. We
2481 // may want to also keep the union in future. As an example, let's say
2482 // the intersection contains Mutex L, and the union contains L and M.
2483 // Later we unlock M. At this point, we would output an error because we
2484 // never locked M; although the real error is probably that we forgot to
2485 // lock M on all code paths. Conversely, let's say that later we lock M.
2486 // In this case, we should compare against the intersection instead of the
2487 // union because the real error is probably that we forgot to unlock M on
2488 // all code paths.
2489 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002490 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002491 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2492 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2493
2494 // if *PI -> CurrBlock is a back edge
2495 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2496 continue;
2497
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002498 int PrevBlockID = (*PI)->getBlockID();
2499 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2500
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002501 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002502 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002503 continue;
2504
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002505 // Okay, we can reach this block from the entry.
2506 CurrBlockInfo->Reachable = true;
2507
Richard Smith815b29d2012-02-03 03:30:07 +00002508 // If the previous block ended in a 'continue' or 'break' statement, then
2509 // a difference in locksets is probably due to a bug in that block, rather
2510 // than in some other predecessor. In that case, keep the other
2511 // predecessor's lockset.
2512 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2513 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2514 SpecialBlocks.push_back(*PI);
2515 continue;
2516 }
2517 }
2518
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002519 FactSet PrevLockset;
2520 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002521
Caitlin Sadowski33208342011-09-09 16:11:56 +00002522 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002523 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002524 LocksetInitialized = true;
2525 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002526 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2527 CurrBlockInfo->EntryLoc,
2528 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002529 }
2530 }
2531
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002532 // Skip rest of block if it's not reachable.
2533 if (!CurrBlockInfo->Reachable)
2534 continue;
2535
Richard Smith815b29d2012-02-03 03:30:07 +00002536 // Process continue and break blocks. Assume that the lockset for the
2537 // resulting block is unaffected by any discrepancies in them.
2538 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2539 SpecialI < SpecialN; ++SpecialI) {
2540 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2541 int PrevBlockID = PrevBlock->getBlockID();
2542 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2543
2544 if (!LocksetInitialized) {
2545 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2546 LocksetInitialized = true;
2547 } else {
2548 // Determine whether this edge is a loop terminator for diagnostic
2549 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2550 // it might also be part of a switch. Also, a subsequent destructor
2551 // might add to the lockset, in which case the real issue might be a
2552 // double lock on the other path.
2553 const Stmt *Terminator = PrevBlock->getTerminator();
2554 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2555
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002556 FactSet PrevLockset;
2557 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2558 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002559
Richard Smith815b29d2012-02-03 03:30:07 +00002560 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002561 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2562 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002563 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002564 : LEK_LockedSomePredecessors,
2565 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002566 }
2567 }
2568
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002569 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2570
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002571 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002572 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2573 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002574 switch (BI->getKind()) {
2575 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002576 CFGStmt CS = BI->castAs<CFGStmt>();
2577 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002578 break;
2579 }
2580 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2581 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002582 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2583 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2584 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002585 if (!DD->hasAttrs())
2586 break;
2587
2588 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002589 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002590 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002591 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002592 LocksetBuilder.handleCall(&DRE, DD);
2593 break;
2594 }
2595 default:
2596 break;
2597 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002598 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002599 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002600
2601 // For every back edge from CurrBlock (the end of the loop) to another block
2602 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2603 // the one held at the beginning of FirstLoopBlock. We can look up the
2604 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2605 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2606 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2607
2608 // if CurrBlock -> *SI is *not* a back edge
2609 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2610 continue;
2611
2612 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002613 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2614 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2615 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2616 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002617 LEK_LockedSomeLoopIterations,
2618 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002619 }
2620 }
2621
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002622 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2623 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002624
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002625 // Skip the final check if the exit block is unreachable.
2626 if (!Final->Reachable)
2627 return;
2628
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002629 // By default, we expect all locks held on entry to be held on exit.
2630 FactSet ExpectedExitSet = Initial->EntrySet;
2631
2632 // Adjust the expected exit set by adding or removing locks, as declared
2633 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2634 // issue the appropriate warning.
2635 // FIXME: the location here is not quite right.
2636 for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) {
2637 ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i],
2638 LockData(D->getLocation(), LK_Exclusive));
2639 }
2640 for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) {
2641 ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i],
2642 LockData(D->getLocation(), LK_Shared));
2643 }
2644 for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) {
2645 ExpectedExitSet.removeLock(FactMan, LocksReleased[i]);
2646 }
2647
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002648 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002649 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002650 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002651 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002652 LEK_NotLockedAtEndOfFunction,
2653 false);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002654}
2655
2656} // end anonymous namespace
2657
2658
2659namespace clang {
2660namespace thread_safety {
2661
2662/// \brief Check a function's CFG for thread-safety violations.
2663///
2664/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2665/// at the end of each block, and issue warnings for thread safety violations.
2666/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002667void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002668 ThreadSafetyHandler &Handler) {
2669 ThreadSafetyAnalyzer Analyzer(Handler);
2670 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002671}
2672
2673/// \brief Helper function that returns a LockKind required for the given level
2674/// of access.
2675LockKind getLockKindFromAccessKind(AccessKind AK) {
2676 switch (AK) {
2677 case AK_Read :
2678 return LK_Shared;
2679 case AK_Written :
2680 return LK_Exclusive;
2681 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002682 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002683}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002684
Caitlin Sadowski33208342011-09-09 16:11:56 +00002685}} // end namespace clang::thread_safety