blob: 5bf3f8c65a105343661942d453395b5179db4651 [file] [log] [blame]
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001//===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
Caitlin Sadowski19903462011-09-14 20:05:09 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
14// information.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Ted Kremenek439ed162011-10-22 02:14:27 +000019#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000020#include "clang/Analysis/AnalysisContext.h"
21#include "clang/Analysis/CFG.h"
22#include "clang/Analysis/CFGStmtMap.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000023#include "clang/AST/DeclCXX.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtVisitor.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000027#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/SourceLocation.h"
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +000029#include "clang/Basic/OperatorKinds.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/FoldingSet.h"
32#include "llvm/ADT/ImmutableMap.h"
33#include "llvm/ADT/PostOrderIterator.h"
34#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/StringRef.h"
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000036#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000037#include <algorithm>
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +000038#include <utility>
Caitlin Sadowski402aa062011-09-09 16:11:56 +000039#include <vector>
40
41using namespace clang;
42using namespace thread_safety;
43
Caitlin Sadowski19903462011-09-14 20:05:09 +000044// Key method definition
45ThreadSafetyHandler::~ThreadSafetyHandler() {}
46
Caitlin Sadowski402aa062011-09-09 16:11:56 +000047namespace {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +000048
Caitlin Sadowski402aa062011-09-09 16:11:56 +000049/// \brief A MutexID object uniquely identifies a particular mutex, and
50/// is built from an Expr* (i.e. calling a lock function).
51///
52/// Thread-safety analysis works by comparing lock expressions. Within the
53/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
54/// a particular mutex object at run-time. Subsequent occurrences of the same
55/// expression (where "same" means syntactic equality) will refer to the same
56/// run-time object if three conditions hold:
57/// (1) Local variables in the expression, such as "x" have not changed.
58/// (2) Values on the heap that affect the expression have not changed.
59/// (3) The expression involves only pure function calls.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +000060///
Caitlin Sadowski402aa062011-09-09 16:11:56 +000061/// The current implementation assumes, but does not verify, that multiple uses
62/// of the same lock expression satisfies these criteria.
63///
64/// Clang introduces an additional wrinkle, which is that it is difficult to
65/// derive canonical expressions, or compare expressions directly for equality.
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +000066/// Thus, we identify a mutex not by an Expr, but by the list of named
Caitlin Sadowski402aa062011-09-09 16:11:56 +000067/// declarations that are referenced by the Expr. In other words,
68/// x->foo->bar.mu will be a four element vector with the Decls for
69/// mu, bar, and foo, and x. The vector will uniquely identify the expression
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +000070/// for all practical purposes. Null is used to denote 'this'.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000071///
72/// Note we will need to perform substitution on "this" and function parameter
73/// names when constructing a lock expression.
74///
75/// For example:
76/// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
77/// void myFunc(C *X) { ... X->lock() ... }
78/// The original expression for the mutex acquired by myFunc is "this->Mu", but
79/// "X" is substituted for "this" so we get X->Mu();
80///
81/// For another example:
82/// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
83/// MyList *MyL;
84/// foo(MyL); // requires lock MyL->Mu to be held
85class MutexID {
86 SmallVector<NamedDecl*, 2> DeclSeq;
87
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +000088 /// \brief Encapsulates the lexical context of a function call. The lexical
89 /// context includes the arguments to the call, including the implicit object
90 /// argument. When an attribute containing a mutex expression is attached to
91 /// a method, the expression may refer to formal parameters of the method.
92 /// Actual arguments must be substituted for formal parameters to derive
93 /// the appropriate mutex expression in the lexical context where the function
94 /// is called. PrevCtx holds the context in which the arguments themselves
95 /// should be evaluated; multiple calling contexts can be chained together
96 /// by the lock_returned attribute.
97 struct CallingContext {
98 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
99 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
100 unsigned NumArgs; // Number of funArgs
101 Expr** FunArgs; // Function arguments
102 CallingContext* PrevCtx; // The previous context; or 0 if none.
103
104 CallingContext(const NamedDecl* D = 0, Expr* S = 0,
105 unsigned N = 0, Expr** A = 0, CallingContext* P = 0)
106 : AttrDecl(D), SelfArg(S), NumArgs(N), FunArgs(A), PrevCtx(P)
107 { }
108 };
109
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000110 /// Build a Decl sequence representing the lock from the given expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000111 /// Recursive function that terminates on DeclRefExpr.
112 /// Note: this function merely creates a MutexID; it does not check to
113 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000114 void buildMutexID(Expr *Exp, CallingContext* CallCtx) {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000115 if (!Exp) {
116 DeclSeq.clear();
117 return;
118 }
119
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000120 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
121 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000122 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
123 if (PV) {
124 FunctionDecl *FD =
125 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
126 unsigned i = PV->getFunctionScopeIndex();
127
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000128 if (CallCtx && CallCtx->FunArgs &&
129 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000130 // Substitute call arguments for references to function parameters
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000131 assert(i < CallCtx->NumArgs);
132 buildMutexID(CallCtx->FunArgs[i], CallCtx->PrevCtx);
DeLesley Hutchinse03b2b32012-01-20 23:24:41 +0000133 return;
134 }
135 // Map the param back to the param of the original function declaration.
136 DeclSeq.push_back(FD->getParamDecl(i));
137 return;
138 }
139 // Not a function parameter -- just store the reference.
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000140 DeclSeq.push_back(ND);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000141 } else if (isa<CXXThisExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000142 // Substitute parent for 'this'
143 if (CallCtx && CallCtx->SelfArg)
144 buildMutexID(CallCtx->SelfArg, CallCtx->PrevCtx);
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000145 else {
146 DeclSeq.push_back(0); // Use 0 to represent 'this'.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000147 return; // mutexID is still valid in this case
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000148 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000149 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
150 NamedDecl *ND = ME->getMemberDecl();
151 DeclSeq.push_back(ND);
152 buildMutexID(ME->getBase(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000153 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000154 // When calling a function with a lock_returned attribute, replace
155 // the function call with the expression in lock_returned.
156 if (LockReturnedAttr* At =
157 CMCE->getMethodDecl()->getAttr<LockReturnedAttr>()) {
158 CallingContext LRCallCtx(CMCE->getMethodDecl());
159 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
160 LRCallCtx.NumArgs = CMCE->getNumArgs();
161 LRCallCtx.FunArgs = CMCE->getArgs();
162 LRCallCtx.PrevCtx = CallCtx;
163 buildMutexID(At->getArg(), &LRCallCtx);
164 return;
165 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000166 // Hack to treat smart pointers and iterators as pointers;
167 // ignore any method named get().
168 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
169 CMCE->getNumArgs() == 0) {
170 buildMutexID(CMCE->getImplicitObjectArgument(), CallCtx);
171 return;
172 }
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000173 DeclSeq.push_back(CMCE->getMethodDecl()->getCanonicalDecl());
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000174 buildMutexID(CMCE->getImplicitObjectArgument(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000175 unsigned NumCallArgs = CMCE->getNumArgs();
176 Expr** CallArgs = CMCE->getArgs();
177 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000178 buildMutexID(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000179 }
180 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000181 if (LockReturnedAttr* At =
182 CE->getDirectCallee()->getAttr<LockReturnedAttr>()) {
183 CallingContext LRCallCtx(CE->getDirectCallee());
184 LRCallCtx.NumArgs = CE->getNumArgs();
185 LRCallCtx.FunArgs = CE->getArgs();
186 LRCallCtx.PrevCtx = CallCtx;
187 buildMutexID(At->getArg(), &LRCallCtx);
188 return;
189 }
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000190 // Treat smart pointers and iterators as pointers;
191 // ignore the * and -> operators.
192 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
193 OverloadedOperatorKind k = OE->getOperator();
194 if (k == OO_Arrow || k == OO_Star) {
195 buildMutexID(OE->getArg(0), CallCtx);
196 return;
197 }
198 }
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000199 buildMutexID(CE->getCallee(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000200 unsigned NumCallArgs = CE->getNumArgs();
201 Expr** CallArgs = CE->getArgs();
202 for (unsigned i = 0; i < NumCallArgs; ++i) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000203 buildMutexID(CallArgs[i], CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000204 }
205 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000206 buildMutexID(BOE->getLHS(), CallCtx);
207 buildMutexID(BOE->getRHS(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000208 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000209 buildMutexID(UOE->getSubExpr(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000210 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000211 buildMutexID(ASE->getBase(), CallCtx);
212 buildMutexID(ASE->getIdx(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000213 } else if (AbstractConditionalOperator *CE =
214 dyn_cast<AbstractConditionalOperator>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000215 buildMutexID(CE->getCond(), CallCtx);
216 buildMutexID(CE->getTrueExpr(), CallCtx);
217 buildMutexID(CE->getFalseExpr(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000218 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000219 buildMutexID(CE->getCond(), CallCtx);
220 buildMutexID(CE->getLHS(), CallCtx);
221 buildMutexID(CE->getRHS(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000222 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000223 buildMutexID(CE->getSubExpr(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000224 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000225 buildMutexID(PE->getSubExpr(), CallCtx);
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000226 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
227 buildMutexID(EWC->getSubExpr(), CallCtx);
DeLesley Hutchins96fac6a2012-07-03 19:47:18 +0000228 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
229 buildMutexID(E->getSubExpr(), CallCtx);
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000230 } else if (isa<CharacterLiteral>(Exp) ||
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +0000231 isa<CXXNullPtrLiteralExpr>(Exp) ||
232 isa<GNUNullExpr>(Exp) ||
233 isa<CXXBoolLiteralExpr>(Exp) ||
234 isa<FloatingLiteral>(Exp) ||
235 isa<ImaginaryLiteral>(Exp) ||
236 isa<IntegerLiteral>(Exp) ||
237 isa<StringLiteral>(Exp) ||
238 isa<ObjCStringLiteral>(Exp)) {
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000239 return; // FIXME: Ignore literals for now
240 } else {
241 // Ignore. FIXME: mark as invalid expression?
242 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000243 }
244
245 /// \brief Construct a MutexID from an expression.
246 /// \param MutexExp The original mutex expression within an attribute
247 /// \param DeclExp An expression involving the Decl on which the attribute
248 /// occurs.
249 /// \param D The declaration to which the lock/unlock attribute is attached.
250 void buildMutexIDFromExp(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000251 CallingContext CallCtx(D);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000252
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000253 // If we are processing a raw attribute expression, with no substitutions.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000254 if (DeclExp == 0) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000255 buildMutexID(MutexExp, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000256 return;
257 }
258
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000259 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000260 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000261 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000262 CallCtx.SelfArg = ME->getBase();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000263 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000264 CallCtx.SelfArg = CE->getImplicitObjectArgument();
265 CallCtx.NumArgs = CE->getNumArgs();
266 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinsdf497822011-12-29 00:56:48 +0000267 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000268 CallCtx.NumArgs = CE->getNumArgs();
269 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000270 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000271 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
272 CallCtx.NumArgs = CE->getNumArgs();
273 CallCtx.FunArgs = CE->getArgs();
DeLesley Hutchins6db51f72011-10-21 20:51:27 +0000274 } else if (D && isa<CXXDestructorDecl>(D)) {
275 // There's no such thing as a "destructor call" in the AST.
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000276 CallCtx.SelfArg = DeclExp;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000277 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000278
279 // If the attribute has no arguments, then assume the argument is "this".
280 if (MutexExp == 0) {
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000281 buildMutexID(CallCtx.SelfArg, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000282 return;
283 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000284
DeLesley Hutchinsf63797c2012-06-25 18:33:18 +0000285 // For most attributes.
286 buildMutexID(MutexExp, &CallCtx);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000287 }
288
289public:
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000290 explicit MutexID(clang::Decl::EmptyShell e) {
291 DeclSeq.clear();
292 }
293
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000294 /// \param MutexExp The original mutex expression within an attribute
295 /// \param DeclExp An expression involving the Decl on which the attribute
296 /// occurs.
297 /// \param D The declaration to which the lock/unlock attribute is attached.
298 /// Caller must check isValid() after construction.
299 MutexID(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
300 buildMutexIDFromExp(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000301 }
302
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000303 /// Return true if this is a valid decl sequence.
304 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000305 bool isValid() const {
306 return !DeclSeq.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000307 }
308
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +0000309 /// Issue a warning about an invalid lock expression
310 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
311 Expr *DeclExp, const NamedDecl* D) {
312 SourceLocation Loc;
313 if (DeclExp)
314 Loc = DeclExp->getExprLoc();
315
316 // FIXME: add a note about the attribute location in MutexExp or D
317 if (Loc.isValid())
318 Handler.handleInvalidLockExp(Loc);
319 }
320
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000321 bool operator==(const MutexID &other) const {
322 return DeclSeq == other.DeclSeq;
323 }
324
325 bool operator!=(const MutexID &other) const {
326 return !(*this == other);
327 }
328
329 // SmallVector overloads Operator< to do lexicographic ordering. Note that
330 // we use pointer equality (and <) to compare NamedDecls. This means the order
331 // of MutexIDs in a lockset is nondeterministic. In order to output
332 // diagnostics in a deterministic ordering, we must order all diagnostics to
333 // output by SourceLocation when iterating through this lockset.
334 bool operator<(const MutexID &other) const {
335 return DeclSeq < other.DeclSeq;
336 }
337
338 /// \brief Returns the name of the first Decl in the list for a given MutexID;
339 /// e.g. the lock expression foo.bar() has name "bar".
340 /// The caret will point unambiguously to the lock expression, so using this
341 /// name in diagnostics is a way to get simple, and consistent, mutex names.
342 /// We do not want to output the entire expression text for security reasons.
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000343 std::string getName() const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000344 assert(isValid());
DeLesley Hutchins4bda3ec2012-02-16 17:03:24 +0000345 if (!DeclSeq.front())
346 return "this"; // Use 0 to represent 'this'.
DeLesley Hutchins0d95dfc2012-03-02 23:36:05 +0000347 return DeclSeq.front()->getNameAsString();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000348 }
349
350 void Profile(llvm::FoldingSetNodeID &ID) const {
351 for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
352 E = DeclSeq.end(); I != E; ++I) {
353 ID.AddPointer(*I);
354 }
355 }
356};
357
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000358
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000359/// \brief A short list of MutexIDs
360class MutexIDList : public SmallVector<MutexID, 3> {
361public:
362 /// \brief Return true if the list contains the specified MutexID
363 /// Performs a linear search, because these lists are almost always very small.
364 bool contains(const MutexID& M) {
365 for (iterator I=begin(),E=end(); I != E; ++I)
366 if ((*I) == M) return true;
367 return false;
368 }
369
370 /// \brief Push M onto list, bud discard duplicates
371 void push_back_nodup(const MutexID& M) {
372 if (!contains(M)) push_back(M);
373 }
374};
375
376
377
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000378/// \brief This is a helper class that stores info about the most recent
379/// accquire of a Lock.
380///
381/// The main body of the analysis maps MutexIDs to LockDatas.
382struct LockData {
383 SourceLocation AcquireLoc;
384
385 /// \brief LKind stores whether a lock is held shared or exclusively.
386 /// Note that this analysis does not currently support either re-entrant
387 /// locking or lock "upgrading" and "downgrading" between exclusive and
388 /// shared.
389 ///
390 /// FIXME: add support for re-entrant locking and lock up/downgrading
391 LockKind LKind;
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000392 bool Managed; // for ScopedLockable objects
393 MutexID UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000394
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000395 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
396 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
397 UnderlyingMutex(Decl::EmptyShell())
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +0000398 {}
399
400 LockData(SourceLocation AcquireLoc, LockKind LKind, const MutexID &Mu)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +0000401 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
402 UnderlyingMutex(Mu)
403 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000404
405 bool operator==(const LockData &other) const {
406 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
407 }
408
409 bool operator!=(const LockData &other) const {
410 return !(*this == other);
411 }
412
413 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000414 ID.AddInteger(AcquireLoc.getRawEncoding());
415 ID.AddInteger(LKind);
416 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000417};
418
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000419
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000420/// A Lockset maps each MutexID (defined above) to information about how it has
421/// been locked.
422typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000423typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000424
425class LocalVariableMap;
426
Richard Smith2e515622012-02-03 04:45:26 +0000427/// A side (entry or exit) of a CFG node.
428enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000429
430/// CFGBlockInfo is a struct which contains all the information that is
431/// maintained for each block in the CFG. See LocalVariableMap for more
432/// information about the contexts.
433struct CFGBlockInfo {
434 Lockset EntrySet; // Lockset held at entry to block
435 Lockset ExitSet; // Lockset held at exit from block
436 LocalVarContext EntryContext; // Context held at entry to block
437 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith2e515622012-02-03 04:45:26 +0000438 SourceLocation EntryLoc; // Location of first statement in block
439 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000440 unsigned EntryIndex; // Used to replay contexts later
441
Richard Smith2e515622012-02-03 04:45:26 +0000442 const Lockset &getSet(CFGBlockSide Side) const {
443 return Side == CBS_Entry ? EntrySet : ExitSet;
444 }
445 SourceLocation getLocation(CFGBlockSide Side) const {
446 return Side == CBS_Entry ? EntryLoc : ExitLoc;
447 }
448
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000449private:
450 CFGBlockInfo(Lockset EmptySet, LocalVarContext EmptyCtx)
451 : EntrySet(EmptySet), ExitSet(EmptySet),
452 EntryContext(EmptyCtx), ExitContext(EmptyCtx)
453 { }
454
455public:
456 static CFGBlockInfo getEmptyBlockInfo(Lockset::Factory &F,
457 LocalVariableMap &M);
458};
459
460
461
462// A LocalVariableMap maintains a map from local variables to their currently
463// valid definitions. It provides SSA-like functionality when traversing the
464// CFG. Like SSA, each definition or assignment to a variable is assigned a
465// unique name (an integer), which acts as the SSA name for that definition.
466// The total set of names is shared among all CFG basic blocks.
467// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
468// with their SSA-names. Instead, we compute a Context for each point in the
469// code, which maps local variables to the appropriate SSA-name. This map
470// changes with each assignment.
471//
472// The map is computed in a single pass over the CFG. Subsequent analyses can
473// then query the map to find the appropriate Context for a statement, and use
474// that Context to look up the definitions of variables.
475class LocalVariableMap {
476public:
477 typedef LocalVarContext Context;
478
479 /// A VarDefinition consists of an expression, representing the value of the
480 /// variable, along with the context in which that expression should be
481 /// interpreted. A reference VarDefinition does not itself contain this
482 /// information, but instead contains a pointer to a previous VarDefinition.
483 struct VarDefinition {
484 public:
485 friend class LocalVariableMap;
486
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000487 const NamedDecl *Dec; // The original declaration for this variable.
488 const Expr *Exp; // The expression for this variable, OR
489 unsigned Ref; // Reference to another VarDefinition
490 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000491
492 bool isReference() { return !Exp; }
493
494 private:
495 // Create ordinary variable definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000496 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000497 : Dec(D), Exp(E), Ref(0), Ctx(C)
498 { }
499
500 // Create reference to previous definition
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000501 VarDefinition(const NamedDecl *D, unsigned R, Context C)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000502 : Dec(D), Exp(0), Ref(R), Ctx(C)
503 { }
504 };
505
506private:
507 Context::Factory ContextFactory;
508 std::vector<VarDefinition> VarDefinitions;
509 std::vector<unsigned> CtxIndices;
510 std::vector<std::pair<Stmt*, Context> > SavedContexts;
511
512public:
513 LocalVariableMap() {
514 // index 0 is a placeholder for undefined variables (aka phi-nodes).
515 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
516 }
517
518 /// Look up a definition, within the given context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000519 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000520 const unsigned *i = Ctx.lookup(D);
521 if (!i)
522 return 0;
523 assert(*i < VarDefinitions.size());
524 return &VarDefinitions[*i];
525 }
526
527 /// Look up the definition for D within the given context. Returns
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000528 /// NULL if the expression is not statically known. If successful, also
529 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000530 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000531 const unsigned *P = Ctx.lookup(D);
532 if (!P)
533 return 0;
534
535 unsigned i = *P;
536 while (i > 0) {
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000537 if (VarDefinitions[i].Exp) {
538 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000539 return VarDefinitions[i].Exp;
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +0000540 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000541 i = VarDefinitions[i].Ref;
542 }
543 return 0;
544 }
545
546 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
547
548 /// Return the next context after processing S. This function is used by
549 /// clients of the class to get the appropriate context when traversing the
550 /// CFG. It must be called for every assignment or DeclStmt.
551 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
552 if (SavedContexts[CtxIndex+1].first == S) {
553 CtxIndex++;
554 Context Result = SavedContexts[CtxIndex].second;
555 return Result;
556 }
557 return C;
558 }
559
560 void dumpVarDefinitionName(unsigned i) {
561 if (i == 0) {
562 llvm::errs() << "Undefined";
563 return;
564 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000565 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000566 if (!Dec) {
567 llvm::errs() << "<<NULL>>";
568 return;
569 }
570 Dec->printName(llvm::errs());
571 llvm::errs() << "." << i << " " << ((void*) Dec);
572 }
573
574 /// Dumps an ASCII representation of the variable map to llvm::errs()
575 void dump() {
576 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000577 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000578 unsigned Ref = VarDefinitions[i].Ref;
579
580 dumpVarDefinitionName(i);
581 llvm::errs() << " = ";
582 if (Exp) Exp->dump();
583 else {
584 dumpVarDefinitionName(Ref);
585 llvm::errs() << "\n";
586 }
587 }
588 }
589
590 /// Dumps an ASCII representation of a Context to llvm::errs()
591 void dumpContext(Context C) {
592 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000593 const NamedDecl *D = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000594 D->printName(llvm::errs());
595 const unsigned *i = C.lookup(D);
596 llvm::errs() << " -> ";
597 dumpVarDefinitionName(*i);
598 llvm::errs() << "\n";
599 }
600 }
601
602 /// Builds the variable map.
603 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
604 std::vector<CFGBlockInfo> &BlockInfo);
605
606protected:
607 // Get the current context index
608 unsigned getContextIndex() { return SavedContexts.size()-1; }
609
610 // Save the current context for later replay
611 void saveContext(Stmt *S, Context C) {
612 SavedContexts.push_back(std::make_pair(S,C));
613 }
614
615 // Adds a new definition to the given context, and returns a new context.
616 // This method should be called when declaring a new variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000617 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000618 assert(!Ctx.contains(D));
619 unsigned newID = VarDefinitions.size();
620 Context NewCtx = ContextFactory.add(Ctx, D, newID);
621 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
622 return NewCtx;
623 }
624
625 // Add a new reference to an existing definition.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000626 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000627 unsigned newID = VarDefinitions.size();
628 Context NewCtx = ContextFactory.add(Ctx, D, newID);
629 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
630 return NewCtx;
631 }
632
633 // Updates a definition only if that definition is already in the map.
634 // This method should be called when assigning to an existing variable.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000635 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000636 if (Ctx.contains(D)) {
637 unsigned newID = VarDefinitions.size();
638 Context NewCtx = ContextFactory.remove(Ctx, D);
639 NewCtx = ContextFactory.add(NewCtx, D, newID);
640 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
641 return NewCtx;
642 }
643 return Ctx;
644 }
645
646 // Removes a definition from the context, but keeps the variable name
647 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000648 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000649 Context NewCtx = Ctx;
650 if (NewCtx.contains(D)) {
651 NewCtx = ContextFactory.remove(NewCtx, D);
652 NewCtx = ContextFactory.add(NewCtx, D, 0);
653 }
654 return NewCtx;
655 }
656
657 // Remove a definition entirely frmo the context.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000658 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000659 Context NewCtx = Ctx;
660 if (NewCtx.contains(D)) {
661 NewCtx = ContextFactory.remove(NewCtx, D);
662 }
663 return NewCtx;
664 }
665
666 Context intersectContexts(Context C1, Context C2);
667 Context createReferenceContext(Context C);
668 void intersectBackEdge(Context C1, Context C2);
669
670 friend class VarMapBuilder;
671};
672
673
674// This has to be defined after LocalVariableMap.
675CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(Lockset::Factory &F,
676 LocalVariableMap &M) {
677 return CFGBlockInfo(F.getEmptyMap(), M.getEmptyContext());
678}
679
680
681/// Visitor which builds a LocalVariableMap
682class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
683public:
684 LocalVariableMap* VMap;
685 LocalVariableMap::Context Ctx;
686
687 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
688 : VMap(VM), Ctx(C) {}
689
690 void VisitDeclStmt(DeclStmt *S);
691 void VisitBinaryOperator(BinaryOperator *BO);
692};
693
694
695// Add new local variables to the variable map
696void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
697 bool modifiedCtx = false;
698 DeclGroupRef DGrp = S->getDeclGroup();
699 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
700 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
701 Expr *E = VD->getInit();
702
703 // Add local variables with trivial type to the variable map
704 QualType T = VD->getType();
705 if (T.isTrivialType(VD->getASTContext())) {
706 Ctx = VMap->addDefinition(VD, E, Ctx);
707 modifiedCtx = true;
708 }
709 }
710 }
711 if (modifiedCtx)
712 VMap->saveContext(S, Ctx);
713}
714
715// Update local variable definitions in variable map
716void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
717 if (!BO->isAssignmentOp())
718 return;
719
720 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
721
722 // Update the variable map and current context.
723 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
724 ValueDecl *VDec = DRE->getDecl();
725 if (Ctx.lookup(VDec)) {
726 if (BO->getOpcode() == BO_Assign)
727 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
728 else
729 // FIXME -- handle compound assignment operators
730 Ctx = VMap->clearDefinition(VDec, Ctx);
731 VMap->saveContext(BO, Ctx);
732 }
733 }
734}
735
736
737// Computes the intersection of two contexts. The intersection is the
738// set of variables which have the same definition in both contexts;
739// variables with different definitions are discarded.
740LocalVariableMap::Context
741LocalVariableMap::intersectContexts(Context C1, Context C2) {
742 Context Result = C1;
743 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000744 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000745 unsigned i1 = I.getData();
746 const unsigned *i2 = C2.lookup(Dec);
747 if (!i2) // variable doesn't exist on second path
748 Result = removeDefinition(Dec, Result);
749 else if (*i2 != i1) // variable exists, but has different definition
750 Result = clearDefinition(Dec, Result);
751 }
752 return Result;
753}
754
755// For every variable in C, create a new variable that refers to the
756// definition in C. Return a new context that contains these new variables.
757// (We use this for a naive implementation of SSA on loop back-edges.)
758LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
759 Context Result = getEmptyContext();
760 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000761 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000762 unsigned i = I.getData();
763 Result = addReference(Dec, i, Result);
764 }
765 return Result;
766}
767
768// This routine also takes the intersection of C1 and C2, but it does so by
769// altering the VarDefinitions. C1 must be the result of an earlier call to
770// createReferenceContext.
771void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
772 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000773 const NamedDecl *Dec = I.getKey();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000774 unsigned i1 = I.getData();
775 VarDefinition *VDef = &VarDefinitions[i1];
776 assert(VDef->isReference());
777
778 const unsigned *i2 = C2.lookup(Dec);
779 if (!i2 || (*i2 != i1))
780 VDef->Ref = 0; // Mark this variable as undefined
781 }
782}
783
784
785// Traverse the CFG in topological order, so all predecessors of a block
786// (excluding back-edges) are visited before the block itself. At
787// each point in the code, we calculate a Context, which holds the set of
788// variable definitions which are visible at that point in execution.
789// Visible variables are mapped to their definitions using an array that
790// contains all definitions.
791//
792// At join points in the CFG, the set is computed as the intersection of
793// the incoming sets along each edge, E.g.
794//
795// { Context | VarDefinitions }
796// int x = 0; { x -> x1 | x1 = 0 }
797// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
798// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
799// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
800// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
801//
802// This is essentially a simpler and more naive version of the standard SSA
803// algorithm. Those definitions that remain in the intersection are from blocks
804// that strictly dominate the current block. We do not bother to insert proper
805// phi nodes, because they are not used in our analysis; instead, wherever
806// a phi node would be required, we simply remove that definition from the
807// context (E.g. x above).
808//
809// The initial traversal does not capture back-edges, so those need to be
810// handled on a separate pass. Whenever the first pass encounters an
811// incoming back edge, it duplicates the context, creating new definitions
812// that refer back to the originals. (These correspond to places where SSA
813// might have to insert a phi node.) On the second pass, these definitions are
814// set to NULL if the the variable has changed on the back-edge (i.e. a phi
815// node was actually required.) E.g.
816//
817// { Context | VarDefinitions }
818// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
819// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
820// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
821// ... { y -> y1 | x3 = 2, x2 = 1, ... }
822//
823void LocalVariableMap::traverseCFG(CFG *CFGraph,
824 PostOrderCFGView *SortedGraph,
825 std::vector<CFGBlockInfo> &BlockInfo) {
826 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
827
828 CtxIndices.resize(CFGraph->getNumBlockIDs());
829
830 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
831 E = SortedGraph->end(); I!= E; ++I) {
832 const CFGBlock *CurrBlock = *I;
833 int CurrBlockID = CurrBlock->getBlockID();
834 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
835
836 VisitedBlocks.insert(CurrBlock);
837
838 // Calculate the entry context for the current block
839 bool HasBackEdges = false;
840 bool CtxInit = true;
841 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
842 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
843 // if *PI -> CurrBlock is a back edge, so skip it
844 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
845 HasBackEdges = true;
846 continue;
847 }
848
849 int PrevBlockID = (*PI)->getBlockID();
850 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
851
852 if (CtxInit) {
853 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
854 CtxInit = false;
855 }
856 else {
857 CurrBlockInfo->EntryContext =
858 intersectContexts(CurrBlockInfo->EntryContext,
859 PrevBlockInfo->ExitContext);
860 }
861 }
862
863 // Duplicate the context if we have back-edges, so we can call
864 // intersectBackEdges later.
865 if (HasBackEdges)
866 CurrBlockInfo->EntryContext =
867 createReferenceContext(CurrBlockInfo->EntryContext);
868
869 // Create a starting context index for the current block
870 saveContext(0, CurrBlockInfo->EntryContext);
871 CurrBlockInfo->EntryIndex = getContextIndex();
872
873 // Visit all the statements in the basic block.
874 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
875 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
876 BE = CurrBlock->end(); BI != BE; ++BI) {
877 switch (BI->getKind()) {
878 case CFGElement::Statement: {
879 const CFGStmt *CS = cast<CFGStmt>(&*BI);
880 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
881 break;
882 }
883 default:
884 break;
885 }
886 }
887 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
888
889 // Mark variables on back edges as "unknown" if they've been changed.
890 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
891 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
892 // if CurrBlock -> *SI is *not* a back edge
893 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
894 continue;
895
896 CFGBlock *FirstLoopBlock = *SI;
897 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
898 Context LoopEnd = CurrBlockInfo->ExitContext;
899 intersectBackEdge(LoopBegin, LoopEnd);
900 }
901 }
902
903 // Put an extra entry at the end of the indexed context array
904 unsigned exitID = CFGraph->getExit().getBlockID();
905 saveContext(0, BlockInfo[exitID].ExitContext);
906}
907
Richard Smith2e515622012-02-03 04:45:26 +0000908/// Find the appropriate source locations to use when producing diagnostics for
909/// each block in the CFG.
910static void findBlockLocations(CFG *CFGraph,
911 PostOrderCFGView *SortedGraph,
912 std::vector<CFGBlockInfo> &BlockInfo) {
913 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
914 E = SortedGraph->end(); I!= E; ++I) {
915 const CFGBlock *CurrBlock = *I;
916 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
917
918 // Find the source location of the last statement in the block, if the
919 // block is not empty.
920 if (const Stmt *S = CurrBlock->getTerminator()) {
921 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
922 } else {
923 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
924 BE = CurrBlock->rend(); BI != BE; ++BI) {
925 // FIXME: Handle other CFGElement kinds.
926 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
927 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
928 break;
929 }
930 }
931 }
932
933 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
934 // This block contains at least one statement. Find the source location
935 // of the first statement in the block.
936 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
937 BE = CurrBlock->end(); BI != BE; ++BI) {
938 // FIXME: Handle other CFGElement kinds.
939 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
940 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
941 break;
942 }
943 }
944 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
945 CurrBlock != &CFGraph->getExit()) {
946 // The block is empty, and has a single predecessor. Use its exit
947 // location.
948 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
949 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
950 }
951 }
952}
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000953
954/// \brief Class which implements the core thread safety analysis routines.
955class ThreadSafetyAnalyzer {
956 friend class BuildLockset;
957
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000958 ThreadSafetyHandler &Handler;
959 Lockset::Factory LocksetFactory;
960 LocalVariableMap LocalVarMap;
961 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000962
963public:
964 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
965
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000966 Lockset addLock(const Lockset &LSet, const MutexID &Mutex,
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000967 const LockData &LDat);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000968 Lockset removeLock(const Lockset &LSet, const MutexID &Mutex,
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000969 SourceLocation UnlockLoc, bool FullyRemove=false);
970
971 template <typename AttrType>
972 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
973 const NamedDecl *D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000974
975 template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +0000976 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
977 const NamedDecl *D,
978 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
979 Expr *BrE, bool Neg);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000980
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000981 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
982 bool &Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +0000983
DeLesley Hutchins0da44142012-06-22 17:07:28 +0000984 Lockset getEdgeLockset(const Lockset &ExitSet,
985 const CFGBlock* PredBlock,
986 const CFGBlock *CurrBlock);
987
988 Lockset intersectAndWarn(const Lockset &LSet1, const Lockset &LSet2,
DeLesley Hutchins879a4332012-07-02 22:16:54 +0000989 SourceLocation JoinLoc,
990 LockErrorKind LEK1, LockErrorKind LEK2);
991
992 Lockset intersectAndWarn(const Lockset &LSet1, const Lockset &LSet2,
993 SourceLocation JoinLoc, LockErrorKind LEK1) {
994 return intersectAndWarn(LSet1, LSet2, JoinLoc, LEK1, LEK1);
995 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000996
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +0000997 void runAnalysis(AnalysisDeclContext &AC);
998};
999
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001000
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001001/// \brief Add a new lock to the lockset, warning if the lock is already there.
1002/// \param Mutex -- the Mutex expression for the lock
1003/// \param LDat -- the LockData for the lock
1004Lockset ThreadSafetyAnalyzer::addLock(const Lockset &LSet,
1005 const MutexID &Mutex,
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001006 const LockData &LDat) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001007 // FIXME: deal with acquired before/after annotations.
1008 // FIXME: Don't always warn when we have support for reentrant locks.
1009 if (LSet.lookup(Mutex)) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001010 Handler.handleDoubleLock(Mutex.getName(), LDat.AcquireLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001011 return LSet;
1012 } else {
1013 return LocksetFactory.add(LSet, Mutex, LDat);
1014 }
1015}
1016
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001017
1018/// \brief Remove a lock from the lockset, warning if the lock is not there.
1019/// \param LockExp The lock expression corresponding to the lock to be removed
1020/// \param UnlockLoc The source location of the unlock (only used in error msg)
1021Lockset ThreadSafetyAnalyzer::removeLock(const Lockset &LSet,
1022 const MutexID &Mutex,
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001023 SourceLocation UnlockLoc,
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001024 bool FullyRemove) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001025 const LockData *LDat = LSet.lookup(Mutex);
1026 if (!LDat) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001027 Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001028 return LSet;
1029 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001030 if (LDat->UnderlyingMutex.isValid()) {
1031 // This is scoped lockable object, which manages the real mutex.
1032 if (FullyRemove) {
1033 // We're destroying the managing object.
1034 // Remove the underlying mutex if it exists; but don't warn.
1035 Lockset Result = LSet;
1036 if (LSet.contains(LDat->UnderlyingMutex))
1037 Result = LocksetFactory.remove(Result, LDat->UnderlyingMutex);
1038 return LocksetFactory.remove(Result, Mutex);
1039 } else {
1040 // We're releasing the underlying mutex, but not destroying the
1041 // managing object. Warn on dual release.
1042 if (!LSet.contains(LDat->UnderlyingMutex)) {
1043 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.getName(),
1044 UnlockLoc);
1045 return LSet;
1046 }
1047 return LocksetFactory.remove(LSet, LDat->UnderlyingMutex);
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001048 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001049 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001050 return LocksetFactory.remove(LSet, Mutex);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001051}
1052
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001053
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001054/// \brief Extract the list of mutexIDs from the attribute on an expression,
1055/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001056template <typename AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001057void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1058 Expr *Exp, const NamedDecl *D) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001059 typedef typename AttrType::args_iterator iterator_type;
1060
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001061 if (Attr->args_size() == 0) {
1062 // The mutex held is the "this" object.
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001063 MutexID Mu(0, Exp, D);
1064 if (!Mu.isValid())
1065 MutexID::warnInvalidLock(Handler, 0, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001066 else
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001067 Mtxs.push_back_nodup(Mu);
1068 return;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001069 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001070
1071 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
1072 MutexID Mu(*I, Exp, D);
1073 if (!Mu.isValid())
1074 MutexID::warnInvalidLock(Handler, *I, Exp, D);
1075 else
1076 Mtxs.push_back_nodup(Mu);
1077 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001078}
1079
1080
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001081/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1082/// trylock applies to the given edge, then push them onto Mtxs, discarding
1083/// any duplicates.
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001084template <class AttrType>
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001085void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1086 Expr *Exp, const NamedDecl *D,
1087 const CFGBlock *PredBlock,
1088 const CFGBlock *CurrBlock,
1089 Expr *BrE, bool Neg) {
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001090 // Find out which branch has the lock
1091 bool branch = 0;
1092 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1093 branch = BLE->getValue();
1094 }
1095 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1096 branch = ILE->getValue().getBoolValue();
1097 }
1098 int branchnum = branch ? 0 : 1;
1099 if (Neg) branchnum = !branchnum;
1100
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001101 // If we've taken the trylock branch, then add the lock
1102 int i = 0;
1103 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1104 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1105 if (*SI == CurrBlock && i == branchnum) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001106 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001107 }
1108 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001109}
1110
1111
DeLesley Hutchins13106112012-07-10 21:47:55 +00001112bool getStaticBooleanValue(Expr* E, bool& TCond) {
1113 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1114 TCond = false;
1115 return true;
1116 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1117 TCond = BLE->getValue();
1118 return true;
1119 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1120 TCond = ILE->getValue().getBoolValue();
1121 return true;
1122 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1123 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1124 }
1125 return false;
1126}
1127
1128
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001129// If Cond can be traced back to a function call, return the call expression.
1130// The negate variable should be called with false, and will be set to true
1131// if the function call is negated, e.g. if (!mu.tryLock(...))
1132const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1133 LocalVarContext C,
1134 bool &Negate) {
1135 if (!Cond)
1136 return 0;
1137
1138 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1139 return CallExp;
1140 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001141 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1142 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1143 }
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001144 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1145 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1146 }
1147 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1148 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1149 return getTrylockCallExpr(E, C, Negate);
1150 }
1151 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1152 if (UOP->getOpcode() == UO_LNot) {
1153 Negate = !Negate;
1154 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1155 }
DeLesley Hutchins13106112012-07-10 21:47:55 +00001156 return 0;
1157 }
1158 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1159 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1160 if (BOP->getOpcode() == BO_NE)
1161 Negate = !Negate;
1162
1163 bool TCond = false;
1164 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1165 if (!TCond) Negate = !Negate;
1166 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1167 }
1168 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1169 if (!TCond) Negate = !Negate;
1170 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1171 }
1172 return 0;
1173 }
1174 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001175 }
1176 // FIXME -- handle && and || as well.
DeLesley Hutchins13106112012-07-10 21:47:55 +00001177 return 0;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001178}
1179
1180
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001181/// \brief Find the lockset that holds on the edge between PredBlock
1182/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1183/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1184Lockset ThreadSafetyAnalyzer::getEdgeLockset(const Lockset &ExitSet,
1185 const CFGBlock *PredBlock,
1186 const CFGBlock *CurrBlock) {
1187 if (!PredBlock->getTerminatorCondition())
1188 return ExitSet;
1189
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001190 bool Negate = false;
1191 const Stmt *Cond = PredBlock->getTerminatorCondition();
1192 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1193 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1194
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001195 CallExpr *Exp =
1196 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001197 if (!Exp)
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001198 return ExitSet;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001199
1200 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1201 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001202 return ExitSet;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001203
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001204
1205 MutexIDList ExclusiveLocksToAdd;
1206 MutexIDList SharedLocksToAdd;
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001207
1208 // If the condition is a call to a Trylock function, then grab the attributes
1209 AttrVec &ArgAttrs = FunDecl->getAttrs();
1210 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1211 Attr *Attr = ArgAttrs[i];
1212 switch (Attr->getKind()) {
1213 case attr::ExclusiveTrylockFunction: {
1214 ExclusiveTrylockFunctionAttr *A =
1215 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001216 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1217 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001218 break;
1219 }
1220 case attr::SharedTrylockFunction: {
1221 SharedTrylockFunctionAttr *A =
1222 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001223 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1224 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001225 break;
1226 }
1227 default:
1228 break;
1229 }
1230 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001231
1232 // Add and remove locks.
1233 Lockset Result = ExitSet;
1234 SourceLocation Loc = Exp->getExprLoc();
1235 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1236 Result = addLock(Result, ExclusiveLocksToAdd[i],
1237 LockData(Loc, LK_Exclusive));
1238 }
1239 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1240 Result = addLock(Result, SharedLocksToAdd[i],
1241 LockData(Loc, LK_Shared));
1242 }
1243
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001244 return Result;
1245}
1246
1247
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001248/// \brief We use this class to visit different types of expressions in
1249/// CFGBlocks, and build up the lockset.
1250/// An expression may cause us to add or remove locks from the lockset, or else
1251/// output error messages related to missing locks.
1252/// FIXME: In future, we may be able to not inherit from a visitor.
1253class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001254 friend class ThreadSafetyAnalyzer;
1255
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001256 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001257 Lockset LSet;
1258 LocalVariableMap::Context LVarCtx;
1259 unsigned CtxIndex;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001260
1261 // Helper functions
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001262 const ValueDecl *getValueDecl(Expr *Exp);
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001263
1264 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1265 Expr *MutexExp, ProtectedOperationKind POK);
1266
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001267 void checkAccess(Expr *Exp, AccessKind AK);
1268 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001269 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001270
1271 /// \brief Returns true if the lockset contains a lock, regardless of whether
1272 /// the lock is held exclusively or shared.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001273 bool locksetContains(const MutexID &Lock) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001274 return LSet.lookup(Lock);
1275 }
1276
1277 /// \brief Returns true if the lockset contains a lock with the passed in
1278 /// locktype.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001279 bool locksetContains(const MutexID &Lock, LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001280 const LockData *LockHeld = LSet.lookup(Lock);
1281 return (LockHeld && KindRequested == LockHeld->LKind);
1282 }
1283
1284 /// \brief Returns true if the lockset contains a lock with at least the
1285 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1286 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1287 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001288 bool locksetContainsAtLeast(const MutexID &Lock,
1289 LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001290 switch (KindRequested) {
1291 case LK_Shared:
1292 return locksetContains(Lock);
1293 case LK_Exclusive:
1294 return locksetContains(Lock, KindRequested);
1295 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001296 llvm_unreachable("Unknown LockKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001297 }
1298
1299public:
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001300 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001301 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001302 Analyzer(Anlzr),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001303 LSet(Info.EntrySet),
1304 LVarCtx(Info.EntryContext),
1305 CtxIndex(Info.EntryIndex)
1306 {}
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001307
1308 void VisitUnaryOperator(UnaryOperator *UO);
1309 void VisitBinaryOperator(BinaryOperator *BO);
1310 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001311 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001312 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001313 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001314};
1315
DeLesley Hutchinsf1ac6372011-10-21 18:10:14 +00001316
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001317/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1318const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1319 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1320 return DR->getDecl();
1321
1322 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1323 return ME->getMemberDecl();
1324
1325 return 0;
1326}
1327
1328/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001329/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001330void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1331 AccessKind AK, Expr *MutexExp,
1332 ProtectedOperationKind POK) {
1333 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001334
1335 MutexID Mutex(MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001336 if (!Mutex.isValid())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001337 MutexID::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001338 else if (!locksetContainsAtLeast(Mutex, LK))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001339 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.getName(), LK,
1340 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001341}
1342
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001343/// \brief This method identifies variable dereferences and checks pt_guarded_by
1344/// and pt_guarded_var annotations. Note that we only check these annotations
1345/// at the time a pointer is dereferenced.
1346/// FIXME: We need to check for other types of pointer dereferences
1347/// (e.g. [], ->) and deal with them here.
1348/// \param Exp An expression that has been read or written.
1349void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1350 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1351 if (!UO || UO->getOpcode() != clang::UO_Deref)
1352 return;
1353 Exp = UO->getSubExpr()->IgnoreParenCasts();
1354
1355 const ValueDecl *D = getValueDecl(Exp);
1356 if(!D || !D->hasAttrs())
1357 return;
1358
1359 if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001360 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1361 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001362
1363 const AttrVec &ArgAttrs = D->getAttrs();
1364 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1365 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1366 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1367}
1368
1369/// \brief Checks guarded_by and guarded_var attributes.
1370/// Whenever we identify an access (read or write) of a DeclRefExpr or
1371/// MemberExpr, we need to check whether there are any guarded_by or
1372/// guarded_var attributes, and make sure we hold the appropriate mutexes.
1373void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1374 const ValueDecl *D = getValueDecl(Exp);
1375 if(!D || !D->hasAttrs())
1376 return;
1377
1378 if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001379 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1380 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001381
1382 const AttrVec &ArgAttrs = D->getAttrs();
1383 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1384 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1385 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1386}
1387
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001388/// \brief Process a function call, method call, constructor call,
1389/// or destructor call. This involves looking at the attributes on the
1390/// corresponding function/method/constructor/destructor, issuing warnings,
1391/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001392///
1393/// FIXME: For classes annotated with one of the guarded annotations, we need
1394/// to treat const method calls as reads and non-const method calls as writes,
1395/// and check that the appropriate locks are held. Non-const method calls with
1396/// the same signature as const method calls can be also treated as reads.
1397///
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001398void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1399 const AttrVec &ArgAttrs = D->getAttrs();
1400 MutexIDList ExclusiveLocksToAdd;
1401 MutexIDList SharedLocksToAdd;
1402 MutexIDList LocksToRemove;
1403
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001404 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001405 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1406 switch (At->getKind()) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001407 // When we encounter an exclusive lock function, we need to add the lock
1408 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001409 case attr::ExclusiveLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001410 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1411 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001412 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001413 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001414
1415 // When we encounter a shared lock function, we need to add the lock
1416 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001417 case attr::SharedLockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001418 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1419 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001420 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001421 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001422
1423 // When we encounter an unlock function, we need to remove unlocked
1424 // mutexes from the lockset, and flag a warning if they are not there.
1425 case attr::UnlockFunction: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001426 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1427 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001428 break;
1429 }
1430
1431 case attr::ExclusiveLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001432 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001433
1434 for (ExclusiveLocksRequiredAttr::args_iterator
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001435 I = A->args_begin(), E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001436 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1437 break;
1438 }
1439
1440 case attr::SharedLocksRequired: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001441 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001442
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001443 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1444 E = A->args_end(); I != E; ++I)
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001445 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1446 break;
1447 }
1448
1449 case attr::LocksExcluded: {
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001450 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1451 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1452 E = A->args_end(); I != E; ++I) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001453 MutexID Mutex(*I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001454 if (!Mutex.isValid())
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001455 MutexID::warnInvalidLock(Analyzer->Handler, *I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +00001456 else if (locksetContains(Mutex))
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001457 Analyzer->Handler.handleFunExcludesLock(D->getName(),
1458 Mutex.getName(),
1459 Exp->getExprLoc());
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001460 }
1461 break;
1462 }
1463
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001464 // Ignore other (non thread-safety) attributes
1465 default:
1466 break;
1467 }
1468 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001469
1470 // Figure out if we're calling the constructor of scoped lockable class
1471 bool isScopedVar = false;
1472 if (VD) {
1473 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1474 const CXXRecordDecl* PD = CD->getParent();
1475 if (PD && PD->getAttr<ScopedLockableAttr>())
1476 isScopedVar = true;
1477 }
1478 }
1479
1480 // Add locks.
1481 SourceLocation Loc = Exp->getExprLoc();
1482 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1483 LSet = Analyzer->addLock(LSet, ExclusiveLocksToAdd[i],
1484 LockData(Loc, LK_Exclusive, isScopedVar));
1485 }
1486 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1487 LSet = Analyzer->addLock(LSet, SharedLocksToAdd[i],
1488 LockData(Loc, LK_Shared, isScopedVar));
1489 }
1490
1491 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1492 // FIXME -- this doesn't work if we acquire multiple locks.
1493 if (isScopedVar) {
1494 SourceLocation MLoc = VD->getLocation();
1495 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
1496 MutexID SMutex(&DRE, 0, 0);
1497
1498 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1499 LSet = Analyzer->addLock(LSet, SMutex, LockData(MLoc, LK_Exclusive,
1500 ExclusiveLocksToAdd[i]));
1501 }
1502 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1503 LSet = Analyzer->addLock(LSet, SMutex, LockData(MLoc, LK_Shared,
1504 SharedLocksToAdd[i]));
1505 }
1506 }
1507
1508 // Remove locks.
1509 // FIXME -- should only fully remove if the attribute refers to 'this'.
1510 bool Dtor = isa<CXXDestructorDecl>(D);
1511 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
1512 LSet = Analyzer->removeLock(LSet, LocksToRemove[i], Loc, Dtor);
1513 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001514}
1515
DeLesley Hutchinsb4fa4182012-01-06 19:16:50 +00001516
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001517/// \brief For unary operations which read and write a variable, we need to
1518/// check whether we hold any required mutexes. Reads are checked in
1519/// VisitCastExpr.
1520void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1521 switch (UO->getOpcode()) {
1522 case clang::UO_PostDec:
1523 case clang::UO_PostInc:
1524 case clang::UO_PreDec:
1525 case clang::UO_PreInc: {
1526 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1527 checkAccess(SubExp, AK_Written);
1528 checkDereference(SubExp, AK_Written);
1529 break;
1530 }
1531 default:
1532 break;
1533 }
1534}
1535
1536/// For binary operations which assign to a variable (writes), we need to check
1537/// whether we hold any required mutexes.
1538/// FIXME: Deal with non-primitive types.
1539void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1540 if (!BO->isAssignmentOp())
1541 return;
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001542
1543 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001544 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001545
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001546 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1547 checkAccess(LHSExp, AK_Written);
1548 checkDereference(LHSExp, AK_Written);
1549}
1550
1551/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1552/// need to ensure we hold any required mutexes.
1553/// FIXME: Deal with non-primitive types.
1554void BuildLockset::VisitCastExpr(CastExpr *CE) {
1555 if (CE->getCastKind() != CK_LValueToRValue)
1556 return;
1557 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
1558 checkAccess(SubExp, AK_Read);
1559 checkDereference(SubExp, AK_Read);
1560}
1561
1562
DeLesley Hutchinsdf497822011-12-29 00:56:48 +00001563void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001564 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1565 if(!D || !D->hasAttrs())
1566 return;
1567 handleCall(Exp, D);
1568}
1569
1570void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001571 // FIXME -- only handles constructors in DeclStmt below.
1572}
1573
1574void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001575 // adjust the context
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001576 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001577
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001578 DeclGroupRef DGrp = S->getDeclGroup();
1579 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1580 Decl *D = *I;
1581 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1582 Expr *E = VD->getInit();
DeLesley Hutchins9d6e7f32012-07-03 18:25:56 +00001583 // handle constructors that involve temporaries
1584 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1585 E = EWC->getSubExpr();
1586
DeLesley Hutchins1fa3c062011-12-08 20:23:06 +00001587 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1588 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1589 if (!CtorD || !CtorD->hasAttrs())
1590 return;
1591 handleCall(CE, CtorD, VD);
1592 }
1593 }
1594 }
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +00001595}
1596
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001597
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001598
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001599/// \brief Compute the intersection of two locksets and issue warnings for any
1600/// locks in the symmetric difference.
1601///
1602/// This function is used at a merge point in the CFG when comparing the lockset
1603/// of each branch being merged. For example, given the following sequence:
1604/// A; if () then B; else C; D; we need to check that the lockset after B and C
1605/// are the same. In the event of a difference, we use the intersection of these
1606/// two locksets at the start of D.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001607///
1608/// \param LSet1 The first lockset.
1609/// \param LSet2 The second lockset.
1610/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001611/// \param LEK1 The error message to report if a mutex is missing from LSet1
1612/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001613Lockset ThreadSafetyAnalyzer::intersectAndWarn(const Lockset &LSet1,
1614 const Lockset &LSet2,
1615 SourceLocation JoinLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001616 LockErrorKind LEK1,
1617 LockErrorKind LEK2) {
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +00001618 Lockset Intersection = LSet1;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001619
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001620 for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
1621 const MutexID &LSet2Mutex = I.getKey();
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001622 const LockData &LDat2 = I.getData();
1623 if (const LockData *LDat1 = LSet1.lookup(LSet2Mutex)) {
1624 if (LDat1->LKind != LDat2.LKind) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001625 Handler.handleExclusiveAndShared(LSet2Mutex.getName(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001626 LDat2.AcquireLoc,
1627 LDat1->AcquireLoc);
1628 if (LDat1->LKind != LK_Exclusive)
1629 Intersection = LocksetFactory.add(Intersection, LSet2Mutex, LDat2);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001630 }
1631 } else {
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001632 if (LDat2.UnderlyingMutex.isValid()) {
1633 if (LSet2.lookup(LDat2.UnderlyingMutex)) {
1634 // If this is a scoped lock that manages another mutex, and if the
1635 // underlying mutex is still held, then warn about the underlying
1636 // mutex.
1637 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.getName(),
1638 LDat2.AcquireLoc,
1639 JoinLoc, LEK1);
1640 }
1641 }
1642 else if (!LDat2.Managed)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001643 Handler.handleMutexHeldEndOfScope(LSet2Mutex.getName(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001644 LDat2.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001645 JoinLoc, LEK1);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001646 }
1647 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001648
1649 for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
1650 if (!LSet2.contains(I.getKey())) {
1651 const MutexID &Mutex = I.getKey();
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001652 const LockData &LDat1 = I.getData();
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001653
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001654 if (LDat1.UnderlyingMutex.isValid()) {
1655 if (LSet1.lookup(LDat1.UnderlyingMutex)) {
1656 // If this is a scoped lock that manages another mutex, and if the
1657 // underlying mutex is still held, then warn about the underlying
1658 // mutex.
1659 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.getName(),
1660 LDat1.AcquireLoc,
1661 JoinLoc, LEK1);
1662 }
1663 }
1664 else if (!LDat1.Managed)
DeLesley Hutchinsc99a5d82012-06-28 22:42:48 +00001665 Handler.handleMutexHeldEndOfScope(Mutex.getName(),
DeLesley Hutchinsbbe33412012-07-02 22:26:29 +00001666 LDat1.AcquireLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001667 JoinLoc, LEK2);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001668 Intersection = LocksetFactory.remove(Intersection, Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001669 }
1670 }
1671 return Intersection;
1672}
1673
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001674
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001675
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001676/// \brief Check a function's CFG for thread-safety violations.
1677///
1678/// We traverse the blocks in the CFG, compute the set of mutexes that are held
1679/// at the end of each block, and issue warnings for thread safety violations.
1680/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00001681void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001682 CFG *CFGraph = AC.getCFG();
1683 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001684 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
1685
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001686 // AC.dumpCFG(true);
1687
DeLesley Hutchins9f80a972011-10-17 21:33:35 +00001688 if (!D)
1689 return; // Ignore anonymous functions for now.
1690 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
1691 return;
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001692 // FIXME: Do something a bit more intelligent inside constructor and
1693 // destructor code. Constructors and destructors must assume unique access
1694 // to 'this', so checks on member variable access is disabled, but we should
1695 // still enable checks on other objects.
1696 if (isa<CXXConstructorDecl>(D))
1697 return; // Don't check inside constructors.
1698 if (isa<CXXDestructorDecl>(D))
1699 return; // Don't check inside destructors.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001700
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001701 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001702 CFGBlockInfo::getEmptyBlockInfo(LocksetFactory, LocalVarMap));
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001703
1704 // We need to explore the CFG via a "topological" ordering.
1705 // That way, we will be guaranteed to have information about required
1706 // predecessor locksets when exploring a new block.
Ted Kremenek439ed162011-10-22 02:14:27 +00001707 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
1708 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001709
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001710 // Compute SSA names for local variables
1711 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
1712
Richard Smith2e515622012-02-03 04:45:26 +00001713 // Fill in source locations for all CFGBlocks.
1714 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
1715
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001716 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001717 // to initial lockset. Also turn off checking for lock and unlock functions.
1718 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek439ed162011-10-22 02:14:27 +00001719 if (!SortedGraph->empty() && D->hasAttrs()) {
1720 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001721 Lockset &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001722 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001723
1724 MutexIDList ExclusiveLocksToAdd;
1725 MutexIDList SharedLocksToAdd;
1726
1727 SourceLocation Loc = D->getLocation();
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001728 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001729 Attr *Attr = ArgAttrs[i];
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001730 Loc = Attr->getLocation();
1731 if (ExclusiveLocksRequiredAttr *A
1732 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
1733 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
1734 } else if (SharedLocksRequiredAttr *A
1735 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
1736 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
DeLesley Hutchins2f13bec2012-02-16 17:13:43 +00001737 } else if (isa<UnlockFunctionAttr>(Attr)) {
1738 // Don't try to check unlock functions for now
1739 return;
1740 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
1741 // Don't try to check lock functions for now
1742 return;
1743 } else if (isa<SharedLockFunctionAttr>(Attr)) {
1744 // Don't try to check lock functions for now
1745 return;
DeLesley Hutchins76f0a6e2012-07-02 21:59:24 +00001746 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
1747 // Don't try to check trylock functions for now
1748 return;
1749 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
1750 // Don't try to check trylock functions for now
1751 return;
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001752 }
1753 }
DeLesley Hutchins5381c052012-07-05 21:16:29 +00001754
1755 // FIXME -- Loc can be wrong here.
1756 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1757 InitialLockset = addLock(InitialLockset, ExclusiveLocksToAdd[i],
1758 LockData(Loc, LK_Exclusive));
1759 }
1760 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1761 InitialLockset = addLock(InitialLockset, SharedLocksToAdd[i],
1762 LockData(Loc, LK_Shared));
1763 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +00001764 }
1765
Ted Kremenek439ed162011-10-22 02:14:27 +00001766 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1767 E = SortedGraph->end(); I!= E; ++I) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001768 const CFGBlock *CurrBlock = *I;
1769 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001770 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001771
1772 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001773 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001774
1775 // Iterate through the predecessor blocks and warn if the lockset for all
1776 // predecessors is not the same. We take the entry lockset of the current
1777 // block to be the intersection of all previous locksets.
1778 // FIXME: By keeping the intersection, we may output more errors in future
1779 // for a lock which is not in the intersection, but was in the union. We
1780 // may want to also keep the union in future. As an example, let's say
1781 // the intersection contains Mutex L, and the union contains L and M.
1782 // Later we unlock M. At this point, we would output an error because we
1783 // never locked M; although the real error is probably that we forgot to
1784 // lock M on all code paths. Conversely, let's say that later we lock M.
1785 // In this case, we should compare against the intersection instead of the
1786 // union because the real error is probably that we forgot to unlock M on
1787 // all code paths.
1788 bool LocksetInitialized = false;
Richard Smithaacde712012-02-03 03:30:07 +00001789 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001790 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1791 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1792
1793 // if *PI -> CurrBlock is a back edge
1794 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
1795 continue;
1796
DeLesley Hutchins2a35be82012-03-02 22:02:58 +00001797 // Ignore edges from blocks that can't return.
1798 if ((*PI)->hasNoReturnElement())
1799 continue;
1800
Richard Smithaacde712012-02-03 03:30:07 +00001801 // If the previous block ended in a 'continue' or 'break' statement, then
1802 // a difference in locksets is probably due to a bug in that block, rather
1803 // than in some other predecessor. In that case, keep the other
1804 // predecessor's lockset.
1805 if (const Stmt *Terminator = (*PI)->getTerminator()) {
1806 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
1807 SpecialBlocks.push_back(*PI);
1808 continue;
1809 }
1810 }
1811
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001812 int PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001813 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001814 Lockset PrevLockset =
1815 getEdgeLockset(PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001816
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001817 if (!LocksetInitialized) {
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001818 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001819 LocksetInitialized = true;
1820 } else {
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001821 CurrBlockInfo->EntrySet =
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001822 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
1823 CurrBlockInfo->EntryLoc,
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001824 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001825 }
1826 }
1827
Richard Smithaacde712012-02-03 03:30:07 +00001828 // Process continue and break blocks. Assume that the lockset for the
1829 // resulting block is unaffected by any discrepancies in them.
1830 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
1831 SpecialI < SpecialN; ++SpecialI) {
1832 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
1833 int PrevBlockID = PrevBlock->getBlockID();
1834 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1835
1836 if (!LocksetInitialized) {
1837 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
1838 LocksetInitialized = true;
1839 } else {
1840 // Determine whether this edge is a loop terminator for diagnostic
1841 // purposes. FIXME: A 'break' statement might be a loop terminator, but
1842 // it might also be part of a switch. Also, a subsequent destructor
1843 // might add to the lockset, in which case the real issue might be a
1844 // double lock on the other path.
1845 const Stmt *Terminator = PrevBlock->getTerminator();
1846 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
1847
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001848 Lockset PrevLockset =
1849 getEdgeLockset(PrevBlockInfo->ExitSet, PrevBlock, CurrBlock);
1850
Richard Smithaacde712012-02-03 03:30:07 +00001851 // Do not update EntrySet.
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001852 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
1853 PrevBlockInfo->ExitLoc,
Richard Smithaacde712012-02-03 03:30:07 +00001854 IsLoop ? LEK_LockedSomeLoopIterations
1855 : LEK_LockedSomePredecessors);
1856 }
1857 }
1858
DeLesley Hutchins54c350a2012-04-19 16:48:43 +00001859 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
1860
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001861 // Visit all the statements in the basic block.
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001862 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1863 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00001864 switch (BI->getKind()) {
1865 case CFGElement::Statement: {
1866 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1867 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1868 break;
1869 }
1870 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
1871 case CFGElement::AutomaticObjectDtor: {
1872 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
1873 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
1874 AD->getDestructorDecl(AC.getASTContext()));
1875 if (!DD->hasAttrs())
1876 break;
1877
1878 // Create a dummy expression,
1879 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001880 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
DeLesley Hutchins6db51f72011-10-21 20:51:27 +00001881 AD->getTriggerStmt()->getLocEnd());
1882 LocksetBuilder.handleCall(&DRE, DD);
1883 break;
1884 }
1885 default:
1886 break;
1887 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001888 }
DeLesley Hutchinsb37d2b52012-01-06 18:36:09 +00001889 CurrBlockInfo->ExitSet = LocksetBuilder.LSet;
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001890
1891 // For every back edge from CurrBlock (the end of the loop) to another block
1892 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
1893 // the one held at the beginning of FirstLoopBlock. We can look up the
1894 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
1895 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1896 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1897
1898 // if CurrBlock -> *SI is *not* a back edge
1899 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1900 continue;
1901
1902 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001903 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
1904 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
1905 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
1906 PreLoop->EntryLoc,
Richard Smith2e515622012-02-03 04:45:26 +00001907 LEK_LockedSomeLoopIterations);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001908 }
1909 }
1910
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001911 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
1912 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +00001913
1914 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchins0da44142012-06-22 17:07:28 +00001915 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
1916 Final->ExitLoc,
DeLesley Hutchins879a4332012-07-02 22:16:54 +00001917 LEK_LockedAtEndOfFunction,
1918 LEK_NotLockedAtEndOfFunction);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001919}
1920
1921} // end anonymous namespace
1922
1923
1924namespace clang {
1925namespace thread_safety {
1926
1927/// \brief Check a function's CFG for thread-safety violations.
1928///
1929/// We traverse the blocks in the CFG, compute the set of mutexes that are held
1930/// at the end of each block, and issue warnings for thread safety violations.
1931/// Each block in the CFG is traversed exactly once.
Ted Kremenek1d26f482011-10-24 01:32:45 +00001932void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001933 ThreadSafetyHandler &Handler) {
1934 ThreadSafetyAnalyzer Analyzer(Handler);
1935 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001936}
1937
1938/// \brief Helper function that returns a LockKind required for the given level
1939/// of access.
1940LockKind getLockKindFromAccessKind(AccessKind AK) {
1941 switch (AK) {
1942 case AK_Read :
1943 return LK_Shared;
1944 case AK_Written :
1945 return LK_Exclusive;
1946 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00001947 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001948}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +00001949
Caitlin Sadowski402aa062011-09-09 16:11:56 +00001950}} // end namespace clang::thread_safety