1 //===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // A intra-procedural analysis for thread safety (e.g. deadlocks and race
11 // conditions), based off of an annotation system.
13 // See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
16 //===----------------------------------------------------------------------===//
18 #include "clang/Analysis/Analyses/ThreadSafety.h"
19 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
20 #include "clang/Analysis/AnalysisContext.h"
21 #include "clang/Analysis/CFG.h"
22 #include "clang/Analysis/CFGStmtMap.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/SourceLocation.h"
29 #include "clang/Basic/OperatorKinds.h"
30 #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"
36 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
42 using namespace thread_safety;
44 // Key method definition
45 ThreadSafetyHandler::~ThreadSafetyHandler() {}
49 /// SExpr implements a simple expression language that is used to store,
50 /// compare, and pretty-print C++ expressions. Unlike a clang Expr, a SExpr
51 /// does not capture surface syntax, and it does not distinguish between
52 /// C++ concepts, like pointers and references, that have no real semantic
53 /// differences. This simplicity allows SExprs to be meaningfully compared,
56 /// (*this).foo = this->foo
59 /// Thread-safety analysis works by comparing lock expressions. Within the
60 /// body of a function, an expression such as "x->foo->bar.mu" will resolve to
61 /// a particular mutex object at run-time. Subsequent occurrences of the same
62 /// expression (where "same" means syntactic equality) will refer to the same
63 /// run-time object if three conditions hold:
64 /// (1) Local variables in the expression, such as "x" have not changed.
65 /// (2) Values on the heap that affect the expression have not changed.
66 /// (3) The expression involves only pure function calls.
68 /// The current implementation assumes, but does not verify, that multiple uses
69 /// of the same lock expression satisfies these criteria.
74 EOP_Wildcard, //< Matches anything.
75 EOP_This, //< This keyword.
76 EOP_NVar, //< Named variable.
77 EOP_LVar, //< Local variable.
78 EOP_Dot, //< Field access
79 EOP_Call, //< Function call
80 EOP_MCall, //< Method call
81 EOP_Index, //< Array index
82 EOP_Unary, //< Unary operation
83 EOP_Binary, //< Binary operation
84 EOP_Unknown //< Catchall for everything else
90 unsigned char Op; //< Opcode of the root node
91 unsigned char Flags; //< Additional opcode-specific data
92 unsigned short Sz; //< Number of child nodes
93 const void* Data; //< Additional opcode-specific data
96 SExprNode(ExprOp O, unsigned F, const void* D)
97 : Op(static_cast<unsigned char>(O)),
98 Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
101 unsigned size() const { return Sz; }
102 void setSize(unsigned S) { Sz = S; }
104 ExprOp kind() const { return static_cast<ExprOp>(Op); }
106 const NamedDecl* getNamedDecl() const {
107 assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
108 return reinterpret_cast<const NamedDecl*>(Data);
111 const NamedDecl* getFunctionDecl() const {
112 assert(Op == EOP_Call || Op == EOP_MCall);
113 return reinterpret_cast<const NamedDecl*>(Data);
116 bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
117 void setArrow(bool A) { Flags = A ? 1 : 0; }
119 unsigned arity() const {
121 case EOP_Nop: return 0;
122 case EOP_Wildcard: return 0;
123 case EOP_NVar: return 0;
124 case EOP_LVar: return 0;
125 case EOP_This: return 0;
126 case EOP_Dot: return 1;
127 case EOP_Call: return Flags+1; // First arg is function.
128 case EOP_MCall: return Flags+1; // First arg is implicit obj.
129 case EOP_Index: return 2;
130 case EOP_Unary: return 1;
131 case EOP_Binary: return 2;
132 case EOP_Unknown: return Flags;
137 bool operator==(const SExprNode& Other) const {
138 // Ignore flags and size -- they don't matter.
139 return (Op == Other.Op &&
143 bool operator!=(const SExprNode& Other) const {
144 return !(*this == Other);
147 bool matches(const SExprNode& Other) const {
148 return (*this == Other) ||
149 (Op == EOP_Wildcard) ||
150 (Other.Op == EOP_Wildcard);
155 /// \brief Encapsulates the lexical context of a function call. The lexical
156 /// context includes the arguments to the call, including the implicit object
157 /// argument. When an attribute containing a mutex expression is attached to
158 /// a method, the expression may refer to formal parameters of the method.
159 /// Actual arguments must be substituted for formal parameters to derive
160 /// the appropriate mutex expression in the lexical context where the function
161 /// is called. PrevCtx holds the context in which the arguments themselves
162 /// should be evaluated; multiple calling contexts can be chained together
163 /// by the lock_returned attribute.
164 struct CallingContext {
165 const NamedDecl* AttrDecl; // The decl to which the attribute is attached.
166 Expr* SelfArg; // Implicit object argument -- e.g. 'this'
167 bool SelfArrow; // is Self referred to with -> or .?
168 unsigned NumArgs; // Number of funArgs
169 Expr** FunArgs; // Function arguments
170 CallingContext* PrevCtx; // The previous context; or 0 if none.
172 CallingContext(const NamedDecl *D = 0, Expr *S = 0,
173 unsigned N = 0, Expr **A = 0, CallingContext *P = 0)
174 : AttrDecl(D), SelfArg(S), SelfArrow(false),
175 NumArgs(N), FunArgs(A), PrevCtx(P)
179 typedef SmallVector<SExprNode, 4> NodeVector;
182 // A SExpr is a list of SExprNodes in prefix order. The Size field allows
183 // the list to be traversed as a tree.
188 NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
189 return NodeVec.size()-1;
192 unsigned makeWildcard() {
193 NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
194 return NodeVec.size()-1;
197 unsigned makeNamedVar(const NamedDecl *D) {
198 NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
199 return NodeVec.size()-1;
202 unsigned makeLocalVar(const NamedDecl *D) {
203 NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
204 return NodeVec.size()-1;
207 unsigned makeThis() {
208 NodeVec.push_back(SExprNode(EOP_This, 0, 0));
209 return NodeVec.size()-1;
212 unsigned makeDot(const NamedDecl *D, bool Arrow) {
213 NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
214 return NodeVec.size()-1;
217 unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
218 NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
219 return NodeVec.size()-1;
222 unsigned makeMCall(unsigned NumArgs, const NamedDecl *D) {
223 NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, D));
224 return NodeVec.size()-1;
227 unsigned makeIndex() {
228 NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
229 return NodeVec.size()-1;
232 unsigned makeUnary() {
233 NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
234 return NodeVec.size()-1;
237 unsigned makeBinary() {
238 NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
239 return NodeVec.size()-1;
242 unsigned makeUnknown(unsigned Arity) {
243 NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
244 return NodeVec.size()-1;
247 /// Build an SExpr from the given C++ expression.
248 /// Recursive function that terminates on DeclRefExpr.
249 /// Note: this function merely creates a SExpr; it does not check to
250 /// ensure that the original expression is a valid mutex expression.
252 /// NDeref returns the number of Derefence and AddressOf operations
253 /// preceeding the Expr; this is used to decide whether to pretty-print
254 /// SExprs with . or ->.
255 unsigned buildSExpr(Expr *Exp, CallingContext* CallCtx, int* NDeref = 0) {
259 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
260 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
261 ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
264 cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
265 unsigned i = PV->getFunctionScopeIndex();
267 if (CallCtx && CallCtx->FunArgs &&
268 FD == CallCtx->AttrDecl->getCanonicalDecl()) {
269 // Substitute call arguments for references to function parameters
270 assert(i < CallCtx->NumArgs);
271 return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
273 // Map the param back to the param of the original function declaration.
274 makeNamedVar(FD->getParamDecl(i));
277 // Not a function parameter -- just store the reference.
280 } else if (isa<CXXThisExpr>(Exp)) {
281 // Substitute parent for 'this'
282 if (CallCtx && CallCtx->SelfArg) {
283 if (!CallCtx->SelfArrow && NDeref)
284 // 'this' is a pointer, but self is not, so need to take address.
286 return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
292 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
293 NamedDecl *ND = ME->getMemberDecl();
294 int ImplicitDeref = ME->isArrow() ? 1 : 0;
295 unsigned Root = makeDot(ND, false);
296 unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
297 NodeVec[Root].setArrow(ImplicitDeref > 0);
298 NodeVec[Root].setSize(Sz + 1);
300 } else if (CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
301 // When calling a function with a lock_returned attribute, replace
302 // the function call with the expression in lock_returned.
303 if (LockReturnedAttr* At =
304 CMCE->getMethodDecl()->getAttr<LockReturnedAttr>()) {
305 CallingContext LRCallCtx(CMCE->getMethodDecl());
306 LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
307 LRCallCtx.SelfArrow =
308 dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
309 LRCallCtx.NumArgs = CMCE->getNumArgs();
310 LRCallCtx.FunArgs = CMCE->getArgs();
311 LRCallCtx.PrevCtx = CallCtx;
312 return buildSExpr(At->getArg(), &LRCallCtx);
314 // Hack to treat smart pointers and iterators as pointers;
315 // ignore any method named get().
316 if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
317 CMCE->getNumArgs() == 0) {
318 if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
320 return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
322 unsigned NumCallArgs = CMCE->getNumArgs();
324 makeMCall(NumCallArgs, CMCE->getMethodDecl()->getCanonicalDecl());
325 unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
326 Expr** CallArgs = CMCE->getArgs();
327 for (unsigned i = 0; i < NumCallArgs; ++i) {
328 Sz += buildSExpr(CallArgs[i], CallCtx);
330 NodeVec[Root].setSize(Sz + 1);
332 } else if (CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
333 if (LockReturnedAttr* At =
334 CE->getDirectCallee()->getAttr<LockReturnedAttr>()) {
335 CallingContext LRCallCtx(CE->getDirectCallee());
336 LRCallCtx.NumArgs = CE->getNumArgs();
337 LRCallCtx.FunArgs = CE->getArgs();
338 LRCallCtx.PrevCtx = CallCtx;
339 return buildSExpr(At->getArg(), &LRCallCtx);
341 // Treat smart pointers and iterators as pointers;
342 // ignore the * and -> operators.
343 if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
344 OverloadedOperatorKind k = OE->getOperator();
346 if (NDeref) ++(*NDeref);
347 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
349 else if (k == OO_Arrow) {
350 return buildSExpr(OE->getArg(0), CallCtx, NDeref);
353 unsigned NumCallArgs = CE->getNumArgs();
354 unsigned Root = makeCall(NumCallArgs, 0);
355 unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
356 Expr** CallArgs = CE->getArgs();
357 for (unsigned i = 0; i < NumCallArgs; ++i) {
358 Sz += buildSExpr(CallArgs[i], CallCtx);
360 NodeVec[Root].setSize(Sz+1);
362 } else if (BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
363 unsigned Root = makeBinary();
364 unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
365 Sz += buildSExpr(BOE->getRHS(), CallCtx);
366 NodeVec[Root].setSize(Sz);
368 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
369 // Ignore & and * operators -- they're no-ops.
370 // However, we try to figure out whether the expression is a pointer,
371 // so we can use . and -> appropriately in error messages.
372 if (UOE->getOpcode() == UO_Deref) {
373 if (NDeref) ++(*NDeref);
374 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
376 if (UOE->getOpcode() == UO_AddrOf) {
377 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
378 if (DRE->getDecl()->isCXXInstanceMember()) {
379 // This is a pointer-to-member expression, e.g. &MyClass::mu_.
380 // We interpret this syntax specially, as a wildcard.
381 unsigned Root = makeDot(DRE->getDecl(), false);
383 NodeVec[Root].setSize(2);
387 if (NDeref) --(*NDeref);
388 return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
390 unsigned Root = makeUnary();
391 unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
392 NodeVec[Root].setSize(Sz);
394 } else if (ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Exp)) {
395 unsigned Root = makeIndex();
396 unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
397 Sz += buildSExpr(ASE->getIdx(), CallCtx);
398 NodeVec[Root].setSize(Sz);
400 } else if (AbstractConditionalOperator *CE =
401 dyn_cast<AbstractConditionalOperator>(Exp)) {
402 unsigned Root = makeUnknown(3);
403 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
404 Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
405 Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
406 NodeVec[Root].setSize(Sz);
408 } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
409 unsigned Root = makeUnknown(3);
410 unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
411 Sz += buildSExpr(CE->getLHS(), CallCtx);
412 Sz += buildSExpr(CE->getRHS(), CallCtx);
413 NodeVec[Root].setSize(Sz);
415 } else if (CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
416 return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
417 } else if (ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
418 return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
419 } else if (ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
420 return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
421 } else if (CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
422 return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
423 } else if (isa<CharacterLiteral>(Exp) ||
424 isa<CXXNullPtrLiteralExpr>(Exp) ||
425 isa<GNUNullExpr>(Exp) ||
426 isa<CXXBoolLiteralExpr>(Exp) ||
427 isa<FloatingLiteral>(Exp) ||
428 isa<ImaginaryLiteral>(Exp) ||
429 isa<IntegerLiteral>(Exp) ||
430 isa<StringLiteral>(Exp) ||
431 isa<ObjCStringLiteral>(Exp)) {
433 return 1; // FIXME: Ignore literals for now
436 return 1; // Ignore. FIXME: mark as invalid expression?
440 /// \brief Construct a SExpr from an expression.
441 /// \param MutexExp The original mutex expression within an attribute
442 /// \param DeclExp An expression involving the Decl on which the attribute
444 /// \param D The declaration to which the lock/unlock attribute is attached.
445 void buildSExprFromExpr(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
446 CallingContext CallCtx(D);
448 // If we are processing a raw attribute expression, with no substitutions.
450 buildSExpr(MutexExp, 0);
454 // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
455 // for formal parameters when we call buildMutexID later.
456 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
457 CallCtx.SelfArg = ME->getBase();
458 CallCtx.SelfArrow = ME->isArrow();
459 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
460 CallCtx.SelfArg = CE->getImplicitObjectArgument();
461 CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
462 CallCtx.NumArgs = CE->getNumArgs();
463 CallCtx.FunArgs = CE->getArgs();
464 } else if (CallExpr *CE = dyn_cast<CallExpr>(DeclExp)) {
465 CallCtx.NumArgs = CE->getNumArgs();
466 CallCtx.FunArgs = CE->getArgs();
467 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
468 CallCtx.SelfArg = 0; // FIXME -- get the parent from DeclStmt
469 CallCtx.NumArgs = CE->getNumArgs();
470 CallCtx.FunArgs = CE->getArgs();
471 } else if (D && isa<CXXDestructorDecl>(D)) {
472 // There's no such thing as a "destructor call" in the AST.
473 CallCtx.SelfArg = DeclExp;
476 // If the attribute has no arguments, then assume the argument is "this".
478 buildSExpr(CallCtx.SelfArg, 0);
482 // For most attributes.
483 buildSExpr(MutexExp, &CallCtx);
486 /// \brief Get index of next sibling of node i.
487 unsigned getNextSibling(unsigned i) const {
488 return i + NodeVec[i].size();
492 explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
494 /// \param MutexExp The original mutex expression within an attribute
495 /// \param DeclExp An expression involving the Decl on which the attribute
497 /// \param D The declaration to which the lock/unlock attribute is attached.
498 /// Caller must check isValid() after construction.
499 SExpr(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
500 buildSExprFromExpr(MutexExp, DeclExp, D);
503 /// Return true if this is a valid decl sequence.
504 /// Caller must call this by hand after construction to handle errors.
505 bool isValid() const {
506 return !NodeVec.empty();
509 /// Issue a warning about an invalid lock expression
510 static void warnInvalidLock(ThreadSafetyHandler &Handler, Expr* MutexExp,
511 Expr *DeclExp, const NamedDecl* D) {
514 Loc = DeclExp->getExprLoc();
516 // FIXME: add a note about the attribute location in MutexExp or D
518 Handler.handleInvalidLockExp(Loc);
521 bool operator==(const SExpr &other) const {
522 return NodeVec == other.NodeVec;
525 bool operator!=(const SExpr &other) const {
526 return !(*this == other);
529 bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
530 if (NodeVec[i].matches(Other.NodeVec[j])) {
531 unsigned n = NodeVec[i].arity();
533 unsigned ci = i+1; // first child of i
534 unsigned cj = j+1; // first child of j
535 for (unsigned k = 0; k < n;
536 ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
537 Result = Result && matches(Other, ci, cj);
544 /// \brief Pretty print a lock expression for use in error messages.
545 std::string toString(unsigned i = 0) const {
547 if (i >= NodeVec.size())
550 const SExprNode* N = &NodeVec[i];
560 return N->getNamedDecl()->getNameAsString();
563 if (NodeVec[i+1].kind() == EOP_Wildcard) {
565 S += N->getNamedDecl()->getQualifiedNameAsString();
568 std::string FieldName = N->getNamedDecl()->getNameAsString();
569 if (NodeVec[i+1].kind() == EOP_This)
572 std::string S = toString(i+1);
574 return S + "->" + FieldName;
576 return S + "." + FieldName;
579 std::string S = toString(i+1) + "(";
580 unsigned NumArgs = N->arity()-1;
581 unsigned ci = getNextSibling(i+1);
582 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
584 if (k+1 < NumArgs) S += ",";
591 if (NodeVec[i+1].kind() != EOP_This)
592 S = toString(i+1) + ".";
593 if (const NamedDecl *D = N->getFunctionDecl())
594 S += D->getNameAsString() + "(";
597 unsigned NumArgs = N->arity()-1;
598 unsigned ci = getNextSibling(i+1);
599 for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
601 if (k+1 < NumArgs) S += ",";
607 std::string S1 = toString(i+1);
608 std::string S2 = toString(i+1 + NodeVec[i+1].size());
609 return S1 + "[" + S2 + "]";
612 std::string S = toString(i+1);
616 std::string S1 = toString(i+1);
617 std::string S2 = toString(i+1 + NodeVec[i+1].size());
618 return "(" + S1 + "#" + S2 + ")";
621 unsigned NumChildren = N->arity();
622 if (NumChildren == 0)
626 for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
628 if (j+1 < NumChildren) S += "#";
640 /// \brief A short list of SExprs
641 class MutexIDList : public SmallVector<SExpr, 3> {
643 /// \brief Return true if the list contains the specified SExpr
644 /// Performs a linear search, because these lists are almost always very small.
645 bool contains(const SExpr& M) {
646 for (iterator I=begin(),E=end(); I != E; ++I)
647 if ((*I) == M) return true;
651 /// \brief Push M onto list, bud discard duplicates
652 void push_back_nodup(const SExpr& M) {
653 if (!contains(M)) push_back(M);
659 /// \brief This is a helper class that stores info about the most recent
660 /// accquire of a Lock.
662 /// The main body of the analysis maps MutexIDs to LockDatas.
664 SourceLocation AcquireLoc;
666 /// \brief LKind stores whether a lock is held shared or exclusively.
667 /// Note that this analysis does not currently support either re-entrant
668 /// locking or lock "upgrading" and "downgrading" between exclusive and
671 /// FIXME: add support for re-entrant locking and lock up/downgrading
673 bool Managed; // for ScopedLockable objects
674 SExpr UnderlyingMutex; // for ScopedLockable objects
676 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
677 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
678 UnderlyingMutex(Decl::EmptyShell())
681 LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
682 : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
686 bool operator==(const LockData &other) const {
687 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
690 bool operator!=(const LockData &other) const {
691 return !(*this == other);
694 void Profile(llvm::FoldingSetNodeID &ID) const {
695 ID.AddInteger(AcquireLoc.getRawEncoding());
696 ID.AddInteger(LKind);
701 /// \brief A FactEntry stores a single fact that is known at a particular point
702 /// in the program execution. Currently, this is information regarding a lock
703 /// that is held at that point.
708 FactEntry(const SExpr& M, const LockData& L)
714 typedef unsigned short FactID;
716 /// \brief FactManager manages the memory for all facts that are created during
717 /// the analysis of a single routine.
720 std::vector<FactEntry> Facts;
723 FactID newLock(const SExpr& M, const LockData& L) {
724 Facts.push_back(FactEntry(M,L));
725 return static_cast<unsigned short>(Facts.size() - 1);
728 const FactEntry& operator[](FactID F) const { return Facts[F]; }
729 FactEntry& operator[](FactID F) { return Facts[F]; }
733 /// \brief A FactSet is the set of facts that are known to be true at a
734 /// particular program point. FactSets must be small, because they are
735 /// frequently copied, and are thus implemented as a set of indices into a
736 /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
737 /// locks, so we can get away with doing a linear search for lookup. Note
738 /// that a hashtable or map is inappropriate in this case, because lookups
739 /// may involve partial pattern matches, rather than exact matches.
742 typedef SmallVector<FactID, 4> FactVec;
747 typedef FactVec::iterator iterator;
748 typedef FactVec::const_iterator const_iterator;
750 iterator begin() { return FactIDs.begin(); }
751 const_iterator begin() const { return FactIDs.begin(); }
753 iterator end() { return FactIDs.end(); }
754 const_iterator end() const { return FactIDs.end(); }
756 bool isEmpty() const { return FactIDs.size() == 0; }
758 FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
759 FactID F = FM.newLock(M, L);
760 FactIDs.push_back(F);
764 bool removeLock(FactManager& FM, const SExpr& M) {
765 unsigned n = FactIDs.size();
769 for (unsigned i = 0; i < n-1; ++i) {
770 if (FM[FactIDs[i]].MutID.matches(M)) {
771 FactIDs[i] = FactIDs[n-1];
776 if (FM[FactIDs[n-1]].MutID.matches(M)) {
783 LockData* findLock(FactManager& FM, const SExpr& M) const {
784 for (const_iterator I=begin(), E=end(); I != E; ++I) {
785 if (FM[*I].MutID.matches(M)) return &FM[*I].LDat;
793 /// A Lockset maps each SExpr (defined above) to information about how it has
795 typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
796 typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
798 class LocalVariableMap;
800 /// A side (entry or exit) of a CFG node.
801 enum CFGBlockSide { CBS_Entry, CBS_Exit };
803 /// CFGBlockInfo is a struct which contains all the information that is
804 /// maintained for each block in the CFG. See LocalVariableMap for more
805 /// information about the contexts.
806 struct CFGBlockInfo {
807 FactSet EntrySet; // Lockset held at entry to block
808 FactSet ExitSet; // Lockset held at exit from block
809 LocalVarContext EntryContext; // Context held at entry to block
810 LocalVarContext ExitContext; // Context held at exit from block
811 SourceLocation EntryLoc; // Location of first statement in block
812 SourceLocation ExitLoc; // Location of last statement in block.
813 unsigned EntryIndex; // Used to replay contexts later
815 const FactSet &getSet(CFGBlockSide Side) const {
816 return Side == CBS_Entry ? EntrySet : ExitSet;
818 SourceLocation getLocation(CFGBlockSide Side) const {
819 return Side == CBS_Entry ? EntryLoc : ExitLoc;
823 CFGBlockInfo(LocalVarContext EmptyCtx)
824 : EntryContext(EmptyCtx), ExitContext(EmptyCtx)
828 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
833 // A LocalVariableMap maintains a map from local variables to their currently
834 // valid definitions. It provides SSA-like functionality when traversing the
835 // CFG. Like SSA, each definition or assignment to a variable is assigned a
836 // unique name (an integer), which acts as the SSA name for that definition.
837 // The total set of names is shared among all CFG basic blocks.
838 // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
839 // with their SSA-names. Instead, we compute a Context for each point in the
840 // code, which maps local variables to the appropriate SSA-name. This map
841 // changes with each assignment.
843 // The map is computed in a single pass over the CFG. Subsequent analyses can
844 // then query the map to find the appropriate Context for a statement, and use
845 // that Context to look up the definitions of variables.
846 class LocalVariableMap {
848 typedef LocalVarContext Context;
850 /// A VarDefinition consists of an expression, representing the value of the
851 /// variable, along with the context in which that expression should be
852 /// interpreted. A reference VarDefinition does not itself contain this
853 /// information, but instead contains a pointer to a previous VarDefinition.
854 struct VarDefinition {
856 friend class LocalVariableMap;
858 const NamedDecl *Dec; // The original declaration for this variable.
859 const Expr *Exp; // The expression for this variable, OR
860 unsigned Ref; // Reference to another VarDefinition
861 Context Ctx; // The map with which Exp should be interpreted.
863 bool isReference() { return !Exp; }
866 // Create ordinary variable definition
867 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
868 : Dec(D), Exp(E), Ref(0), Ctx(C)
871 // Create reference to previous definition
872 VarDefinition(const NamedDecl *D, unsigned R, Context C)
873 : Dec(D), Exp(0), Ref(R), Ctx(C)
878 Context::Factory ContextFactory;
879 std::vector<VarDefinition> VarDefinitions;
880 std::vector<unsigned> CtxIndices;
881 std::vector<std::pair<Stmt*, Context> > SavedContexts;
885 // index 0 is a placeholder for undefined variables (aka phi-nodes).
886 VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
889 /// Look up a definition, within the given context.
890 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
891 const unsigned *i = Ctx.lookup(D);
894 assert(*i < VarDefinitions.size());
895 return &VarDefinitions[*i];
898 /// Look up the definition for D within the given context. Returns
899 /// NULL if the expression is not statically known. If successful, also
900 /// modifies Ctx to hold the context of the return Expr.
901 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
902 const unsigned *P = Ctx.lookup(D);
908 if (VarDefinitions[i].Exp) {
909 Ctx = VarDefinitions[i].Ctx;
910 return VarDefinitions[i].Exp;
912 i = VarDefinitions[i].Ref;
917 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
919 /// Return the next context after processing S. This function is used by
920 /// clients of the class to get the appropriate context when traversing the
921 /// CFG. It must be called for every assignment or DeclStmt.
922 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
923 if (SavedContexts[CtxIndex+1].first == S) {
925 Context Result = SavedContexts[CtxIndex].second;
931 void dumpVarDefinitionName(unsigned i) {
933 llvm::errs() << "Undefined";
936 const NamedDecl *Dec = VarDefinitions[i].Dec;
938 llvm::errs() << "<<NULL>>";
941 Dec->printName(llvm::errs());
942 llvm::errs() << "." << i << " " << ((void*) Dec);
945 /// Dumps an ASCII representation of the variable map to llvm::errs()
947 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
948 const Expr *Exp = VarDefinitions[i].Exp;
949 unsigned Ref = VarDefinitions[i].Ref;
951 dumpVarDefinitionName(i);
952 llvm::errs() << " = ";
953 if (Exp) Exp->dump();
955 dumpVarDefinitionName(Ref);
956 llvm::errs() << "\n";
961 /// Dumps an ASCII representation of a Context to llvm::errs()
962 void dumpContext(Context C) {
963 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
964 const NamedDecl *D = I.getKey();
965 D->printName(llvm::errs());
966 const unsigned *i = C.lookup(D);
967 llvm::errs() << " -> ";
968 dumpVarDefinitionName(*i);
969 llvm::errs() << "\n";
973 /// Builds the variable map.
974 void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
975 std::vector<CFGBlockInfo> &BlockInfo);
978 // Get the current context index
979 unsigned getContextIndex() { return SavedContexts.size()-1; }
981 // Save the current context for later replay
982 void saveContext(Stmt *S, Context C) {
983 SavedContexts.push_back(std::make_pair(S,C));
986 // Adds a new definition to the given context, and returns a new context.
987 // This method should be called when declaring a new variable.
988 Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
989 assert(!Ctx.contains(D));
990 unsigned newID = VarDefinitions.size();
991 Context NewCtx = ContextFactory.add(Ctx, D, newID);
992 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
996 // Add a new reference to an existing definition.
997 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
998 unsigned newID = VarDefinitions.size();
999 Context NewCtx = ContextFactory.add(Ctx, D, newID);
1000 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1004 // Updates a definition only if that definition is already in the map.
1005 // This method should be called when assigning to an existing variable.
1006 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
1007 if (Ctx.contains(D)) {
1008 unsigned newID = VarDefinitions.size();
1009 Context NewCtx = ContextFactory.remove(Ctx, D);
1010 NewCtx = ContextFactory.add(NewCtx, D, newID);
1011 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1017 // Removes a definition from the context, but keeps the variable name
1018 // as a valid variable. The index 0 is a placeholder for cleared definitions.
1019 Context clearDefinition(const NamedDecl *D, Context Ctx) {
1020 Context NewCtx = Ctx;
1021 if (NewCtx.contains(D)) {
1022 NewCtx = ContextFactory.remove(NewCtx, D);
1023 NewCtx = ContextFactory.add(NewCtx, D, 0);
1028 // Remove a definition entirely frmo the context.
1029 Context removeDefinition(const NamedDecl *D, Context Ctx) {
1030 Context NewCtx = Ctx;
1031 if (NewCtx.contains(D)) {
1032 NewCtx = ContextFactory.remove(NewCtx, D);
1037 Context intersectContexts(Context C1, Context C2);
1038 Context createReferenceContext(Context C);
1039 void intersectBackEdge(Context C1, Context C2);
1041 friend class VarMapBuilder;
1045 // This has to be defined after LocalVariableMap.
1046 CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1047 return CFGBlockInfo(M.getEmptyContext());
1051 /// Visitor which builds a LocalVariableMap
1052 class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1054 LocalVariableMap* VMap;
1055 LocalVariableMap::Context Ctx;
1057 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1058 : VMap(VM), Ctx(C) {}
1060 void VisitDeclStmt(DeclStmt *S);
1061 void VisitBinaryOperator(BinaryOperator *BO);
1065 // Add new local variables to the variable map
1066 void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1067 bool modifiedCtx = false;
1068 DeclGroupRef DGrp = S->getDeclGroup();
1069 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1070 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1071 Expr *E = VD->getInit();
1073 // Add local variables with trivial type to the variable map
1074 QualType T = VD->getType();
1075 if (T.isTrivialType(VD->getASTContext())) {
1076 Ctx = VMap->addDefinition(VD, E, Ctx);
1082 VMap->saveContext(S, Ctx);
1085 // Update local variable definitions in variable map
1086 void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1087 if (!BO->isAssignmentOp())
1090 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1092 // Update the variable map and current context.
1093 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1094 ValueDecl *VDec = DRE->getDecl();
1095 if (Ctx.lookup(VDec)) {
1096 if (BO->getOpcode() == BO_Assign)
1097 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1099 // FIXME -- handle compound assignment operators
1100 Ctx = VMap->clearDefinition(VDec, Ctx);
1101 VMap->saveContext(BO, Ctx);
1107 // Computes the intersection of two contexts. The intersection is the
1108 // set of variables which have the same definition in both contexts;
1109 // variables with different definitions are discarded.
1110 LocalVariableMap::Context
1111 LocalVariableMap::intersectContexts(Context C1, Context C2) {
1112 Context Result = C1;
1113 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
1114 const NamedDecl *Dec = I.getKey();
1115 unsigned i1 = I.getData();
1116 const unsigned *i2 = C2.lookup(Dec);
1117 if (!i2) // variable doesn't exist on second path
1118 Result = removeDefinition(Dec, Result);
1119 else if (*i2 != i1) // variable exists, but has different definition
1120 Result = clearDefinition(Dec, Result);
1125 // For every variable in C, create a new variable that refers to the
1126 // definition in C. Return a new context that contains these new variables.
1127 // (We use this for a naive implementation of SSA on loop back-edges.)
1128 LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1129 Context Result = getEmptyContext();
1130 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
1131 const NamedDecl *Dec = I.getKey();
1132 unsigned i = I.getData();
1133 Result = addReference(Dec, i, Result);
1138 // This routine also takes the intersection of C1 and C2, but it does so by
1139 // altering the VarDefinitions. C1 must be the result of an earlier call to
1140 // createReferenceContext.
1141 void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1142 for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
1143 const NamedDecl *Dec = I.getKey();
1144 unsigned i1 = I.getData();
1145 VarDefinition *VDef = &VarDefinitions[i1];
1146 assert(VDef->isReference());
1148 const unsigned *i2 = C2.lookup(Dec);
1149 if (!i2 || (*i2 != i1))
1150 VDef->Ref = 0; // Mark this variable as undefined
1155 // Traverse the CFG in topological order, so all predecessors of a block
1156 // (excluding back-edges) are visited before the block itself. At
1157 // each point in the code, we calculate a Context, which holds the set of
1158 // variable definitions which are visible at that point in execution.
1159 // Visible variables are mapped to their definitions using an array that
1160 // contains all definitions.
1162 // At join points in the CFG, the set is computed as the intersection of
1163 // the incoming sets along each edge, E.g.
1165 // { Context | VarDefinitions }
1166 // int x = 0; { x -> x1 | x1 = 0 }
1167 // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1168 // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
1169 // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
1170 // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
1172 // This is essentially a simpler and more naive version of the standard SSA
1173 // algorithm. Those definitions that remain in the intersection are from blocks
1174 // that strictly dominate the current block. We do not bother to insert proper
1175 // phi nodes, because they are not used in our analysis; instead, wherever
1176 // a phi node would be required, we simply remove that definition from the
1177 // context (E.g. x above).
1179 // The initial traversal does not capture back-edges, so those need to be
1180 // handled on a separate pass. Whenever the first pass encounters an
1181 // incoming back edge, it duplicates the context, creating new definitions
1182 // that refer back to the originals. (These correspond to places where SSA
1183 // might have to insert a phi node.) On the second pass, these definitions are
1184 // set to NULL if the variable has changed on the back-edge (i.e. a phi
1185 // node was actually required.) E.g.
1187 // { Context | VarDefinitions }
1188 // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
1189 // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
1190 // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
1191 // ... { y -> y1 | x3 = 2, x2 = 1, ... }
1193 void LocalVariableMap::traverseCFG(CFG *CFGraph,
1194 PostOrderCFGView *SortedGraph,
1195 std::vector<CFGBlockInfo> &BlockInfo) {
1196 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1198 CtxIndices.resize(CFGraph->getNumBlockIDs());
1200 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1201 E = SortedGraph->end(); I!= E; ++I) {
1202 const CFGBlock *CurrBlock = *I;
1203 int CurrBlockID = CurrBlock->getBlockID();
1204 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1206 VisitedBlocks.insert(CurrBlock);
1208 // Calculate the entry context for the current block
1209 bool HasBackEdges = false;
1210 bool CtxInit = true;
1211 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1212 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1213 // if *PI -> CurrBlock is a back edge, so skip it
1214 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1215 HasBackEdges = true;
1219 int PrevBlockID = (*PI)->getBlockID();
1220 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1223 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1227 CurrBlockInfo->EntryContext =
1228 intersectContexts(CurrBlockInfo->EntryContext,
1229 PrevBlockInfo->ExitContext);
1233 // Duplicate the context if we have back-edges, so we can call
1234 // intersectBackEdges later.
1236 CurrBlockInfo->EntryContext =
1237 createReferenceContext(CurrBlockInfo->EntryContext);
1239 // Create a starting context index for the current block
1240 saveContext(0, CurrBlockInfo->EntryContext);
1241 CurrBlockInfo->EntryIndex = getContextIndex();
1243 // Visit all the statements in the basic block.
1244 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1245 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1246 BE = CurrBlock->end(); BI != BE; ++BI) {
1247 switch (BI->getKind()) {
1248 case CFGElement::Statement: {
1249 const CFGStmt *CS = cast<CFGStmt>(&*BI);
1250 VMapBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
1257 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1259 // Mark variables on back edges as "unknown" if they've been changed.
1260 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1261 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
1262 // if CurrBlock -> *SI is *not* a back edge
1263 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1266 CFGBlock *FirstLoopBlock = *SI;
1267 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1268 Context LoopEnd = CurrBlockInfo->ExitContext;
1269 intersectBackEdge(LoopBegin, LoopEnd);
1273 // Put an extra entry at the end of the indexed context array
1274 unsigned exitID = CFGraph->getExit().getBlockID();
1275 saveContext(0, BlockInfo[exitID].ExitContext);
1278 /// Find the appropriate source locations to use when producing diagnostics for
1279 /// each block in the CFG.
1280 static void findBlockLocations(CFG *CFGraph,
1281 PostOrderCFGView *SortedGraph,
1282 std::vector<CFGBlockInfo> &BlockInfo) {
1283 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1284 E = SortedGraph->end(); I!= E; ++I) {
1285 const CFGBlock *CurrBlock = *I;
1286 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1288 // Find the source location of the last statement in the block, if the
1289 // block is not empty.
1290 if (const Stmt *S = CurrBlock->getTerminator()) {
1291 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1293 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1294 BE = CurrBlock->rend(); BI != BE; ++BI) {
1295 // FIXME: Handle other CFGElement kinds.
1296 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1297 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1303 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1304 // This block contains at least one statement. Find the source location
1305 // of the first statement in the block.
1306 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1307 BE = CurrBlock->end(); BI != BE; ++BI) {
1308 // FIXME: Handle other CFGElement kinds.
1309 if (const CFGStmt *CS = dyn_cast<CFGStmt>(&*BI)) {
1310 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1314 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1315 CurrBlock != &CFGraph->getExit()) {
1316 // The block is empty, and has a single predecessor. Use its exit
1318 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1319 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1324 /// \brief Class which implements the core thread safety analysis routines.
1325 class ThreadSafetyAnalyzer {
1326 friend class BuildLockset;
1328 ThreadSafetyHandler &Handler;
1329 LocalVariableMap LocalVarMap;
1330 FactManager FactMan;
1331 std::vector<CFGBlockInfo> BlockInfo;
1334 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1336 void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1337 void removeLock(FactSet &FSet, const SExpr &Mutex,
1338 SourceLocation UnlockLoc, bool FullyRemove=false);
1340 template <typename AttrType>
1341 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1342 const NamedDecl *D);
1344 template <class AttrType>
1345 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1347 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1348 Expr *BrE, bool Neg);
1350 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1353 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1354 const CFGBlock* PredBlock,
1355 const CFGBlock *CurrBlock);
1357 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1358 SourceLocation JoinLoc,
1359 LockErrorKind LEK1, LockErrorKind LEK2,
1362 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1363 SourceLocation JoinLoc, LockErrorKind LEK1,
1365 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
1368 void runAnalysis(AnalysisDeclContext &AC);
1372 /// \brief Add a new lock to the lockset, warning if the lock is already there.
1373 /// \param Mutex -- the Mutex expression for the lock
1374 /// \param LDat -- the LockData for the lock
1375 void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
1376 const LockData &LDat) {
1377 // FIXME: deal with acquired before/after annotations.
1378 // FIXME: Don't always warn when we have support for reentrant locks.
1379 if (FSet.findLock(FactMan, Mutex)) {
1380 Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
1382 FSet.addLock(FactMan, Mutex, LDat);
1387 /// \brief Remove a lock from the lockset, warning if the lock is not there.
1388 /// \param LockExp The lock expression corresponding to the lock to be removed
1389 /// \param UnlockLoc The source location of the unlock (only used in error msg)
1390 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
1392 SourceLocation UnlockLoc,
1394 const LockData *LDat = FSet.findLock(FactMan, Mutex);
1396 Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
1400 if (LDat->UnderlyingMutex.isValid()) {
1401 // This is scoped lockable object, which manages the real mutex.
1403 // We're destroying the managing object.
1404 // Remove the underlying mutex if it exists; but don't warn.
1405 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1406 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1408 // We're releasing the underlying mutex, but not destroying the
1409 // managing object. Warn on dual release.
1410 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
1411 Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
1414 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1418 FSet.removeLock(FactMan, Mutex);
1422 /// \brief Extract the list of mutexIDs from the attribute on an expression,
1423 /// and push them onto Mtxs, discarding any duplicates.
1424 template <typename AttrType>
1425 void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1426 Expr *Exp, const NamedDecl *D) {
1427 typedef typename AttrType::args_iterator iterator_type;
1429 if (Attr->args_size() == 0) {
1430 // The mutex held is the "this" object.
1431 SExpr Mu(0, Exp, D);
1433 SExpr::warnInvalidLock(Handler, 0, Exp, D);
1435 Mtxs.push_back_nodup(Mu);
1439 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
1440 SExpr Mu(*I, Exp, D);
1442 SExpr::warnInvalidLock(Handler, *I, Exp, D);
1444 Mtxs.push_back_nodup(Mu);
1449 /// \brief Extract the list of mutexIDs from a trylock attribute. If the
1450 /// trylock applies to the given edge, then push them onto Mtxs, discarding
1452 template <class AttrType>
1453 void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1454 Expr *Exp, const NamedDecl *D,
1455 const CFGBlock *PredBlock,
1456 const CFGBlock *CurrBlock,
1457 Expr *BrE, bool Neg) {
1458 // Find out which branch has the lock
1460 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1461 branch = BLE->getValue();
1463 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1464 branch = ILE->getValue().getBoolValue();
1466 int branchnum = branch ? 0 : 1;
1467 if (Neg) branchnum = !branchnum;
1469 // If we've taken the trylock branch, then add the lock
1471 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1472 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1473 if (*SI == CurrBlock && i == branchnum) {
1474 getMutexIDs(Mtxs, Attr, Exp, D);
1480 bool getStaticBooleanValue(Expr* E, bool& TCond) {
1481 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1484 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1485 TCond = BLE->getValue();
1487 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1488 TCond = ILE->getValue().getBoolValue();
1490 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1491 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1497 // If Cond can be traced back to a function call, return the call expression.
1498 // The negate variable should be called with false, and will be set to true
1499 // if the function call is negated, e.g. if (!mu.tryLock(...))
1500 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1506 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1509 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1510 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1512 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1513 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1515 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1516 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1517 return getTrylockCallExpr(E, C, Negate);
1519 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1520 if (UOP->getOpcode() == UO_LNot) {
1522 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1526 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1527 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1528 if (BOP->getOpcode() == BO_NE)
1532 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1533 if (!TCond) Negate = !Negate;
1534 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1536 else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1537 if (!TCond) Negate = !Negate;
1538 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1544 // FIXME -- handle && and || as well.
1549 /// \brief Find the lockset that holds on the edge between PredBlock
1550 /// and CurrBlock. The edge set is the exit set of PredBlock (passed
1551 /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1552 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1553 const FactSet &ExitSet,
1554 const CFGBlock *PredBlock,
1555 const CFGBlock *CurrBlock) {
1558 if (!PredBlock->getTerminatorCondition())
1561 bool Negate = false;
1562 const Stmt *Cond = PredBlock->getTerminatorCondition();
1563 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1564 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1567 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
1571 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1572 if(!FunDecl || !FunDecl->hasAttrs())
1576 MutexIDList ExclusiveLocksToAdd;
1577 MutexIDList SharedLocksToAdd;
1579 // If the condition is a call to a Trylock function, then grab the attributes
1580 AttrVec &ArgAttrs = FunDecl->getAttrs();
1581 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1582 Attr *Attr = ArgAttrs[i];
1583 switch (Attr->getKind()) {
1584 case attr::ExclusiveTrylockFunction: {
1585 ExclusiveTrylockFunctionAttr *A =
1586 cast<ExclusiveTrylockFunctionAttr>(Attr);
1587 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1588 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1591 case attr::SharedTrylockFunction: {
1592 SharedTrylockFunctionAttr *A =
1593 cast<SharedTrylockFunctionAttr>(Attr);
1594 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1595 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1603 // Add and remove locks.
1604 SourceLocation Loc = Exp->getExprLoc();
1605 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1606 addLock(Result, ExclusiveLocksToAdd[i],
1607 LockData(Loc, LK_Exclusive));
1609 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1610 addLock(Result, SharedLocksToAdd[i],
1611 LockData(Loc, LK_Shared));
1616 /// \brief We use this class to visit different types of expressions in
1617 /// CFGBlocks, and build up the lockset.
1618 /// An expression may cause us to add or remove locks from the lockset, or else
1619 /// output error messages related to missing locks.
1620 /// FIXME: In future, we may be able to not inherit from a visitor.
1621 class BuildLockset : public StmtVisitor<BuildLockset> {
1622 friend class ThreadSafetyAnalyzer;
1624 ThreadSafetyAnalyzer *Analyzer;
1626 LocalVariableMap::Context LVarCtx;
1630 const ValueDecl *getValueDecl(Expr *Exp);
1632 void warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp, AccessKind AK,
1633 Expr *MutexExp, ProtectedOperationKind POK);
1635 void checkAccess(Expr *Exp, AccessKind AK);
1636 void checkDereference(Expr *Exp, AccessKind AK);
1637 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
1639 /// \brief Returns true if the lockset contains a lock, regardless of whether
1640 /// the lock is held exclusively or shared.
1641 bool locksetContains(const SExpr &Mu) const {
1642 return FSet.findLock(Analyzer->FactMan, Mu);
1645 /// \brief Returns true if the lockset contains a lock with the passed in
1647 bool locksetContains(const SExpr &Mu, LockKind KindRequested) const {
1648 const LockData *LockHeld = FSet.findLock(Analyzer->FactMan, Mu);
1649 return (LockHeld && KindRequested == LockHeld->LKind);
1652 /// \brief Returns true if the lockset contains a lock with at least the
1653 /// passed in locktype. So for example, if we pass in LK_Shared, this function
1654 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
1655 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
1656 bool locksetContainsAtLeast(const SExpr &Lock,
1657 LockKind KindRequested) const {
1658 switch (KindRequested) {
1660 return locksetContains(Lock);
1662 return locksetContains(Lock, KindRequested);
1664 llvm_unreachable("Unknown LockKind");
1668 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1669 : StmtVisitor<BuildLockset>(),
1671 FSet(Info.EntrySet),
1672 LVarCtx(Info.EntryContext),
1673 CtxIndex(Info.EntryIndex)
1676 void VisitUnaryOperator(UnaryOperator *UO);
1677 void VisitBinaryOperator(BinaryOperator *BO);
1678 void VisitCastExpr(CastExpr *CE);
1679 void VisitCallExpr(CallExpr *Exp);
1680 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
1681 void VisitDeclStmt(DeclStmt *S);
1685 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1686 const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
1687 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1688 return DR->getDecl();
1690 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1691 return ME->getMemberDecl();
1696 /// \brief Warn if the LSet does not contain a lock sufficient to protect access
1697 /// of at least the passed in AccessKind.
1698 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
1699 AccessKind AK, Expr *MutexExp,
1700 ProtectedOperationKind POK) {
1701 LockKind LK = getLockKindFromAccessKind(AK);
1703 SExpr Mutex(MutexExp, Exp, D);
1704 if (!Mutex.isValid())
1705 SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1706 else if (!locksetContainsAtLeast(Mutex, LK))
1707 Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1711 /// \brief This method identifies variable dereferences and checks pt_guarded_by
1712 /// and pt_guarded_var annotations. Note that we only check these annotations
1713 /// at the time a pointer is dereferenced.
1714 /// FIXME: We need to check for other types of pointer dereferences
1715 /// (e.g. [], ->) and deal with them here.
1716 /// \param Exp An expression that has been read or written.
1717 void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
1718 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
1719 if (!UO || UO->getOpcode() != clang::UO_Deref)
1721 Exp = UO->getSubExpr()->IgnoreParenCasts();
1723 const ValueDecl *D = getValueDecl(Exp);
1724 if(!D || !D->hasAttrs())
1727 if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
1728 Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1731 const AttrVec &ArgAttrs = D->getAttrs();
1732 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1733 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1734 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
1737 /// \brief Checks guarded_by and guarded_var attributes.
1738 /// Whenever we identify an access (read or write) of a DeclRefExpr or
1739 /// MemberExpr, we need to check whether there are any guarded_by or
1740 /// guarded_var attributes, and make sure we hold the appropriate mutexes.
1741 void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
1742 const ValueDecl *D = getValueDecl(Exp);
1743 if(!D || !D->hasAttrs())
1746 if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
1747 Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1750 const AttrVec &ArgAttrs = D->getAttrs();
1751 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1752 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1753 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1756 /// \brief Process a function call, method call, constructor call,
1757 /// or destructor call. This involves looking at the attributes on the
1758 /// corresponding function/method/constructor/destructor, issuing warnings,
1759 /// and updating the locksets accordingly.
1761 /// FIXME: For classes annotated with one of the guarded annotations, we need
1762 /// to treat const method calls as reads and non-const method calls as writes,
1763 /// and check that the appropriate locks are held. Non-const method calls with
1764 /// the same signature as const method calls can be also treated as reads.
1766 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1767 const AttrVec &ArgAttrs = D->getAttrs();
1768 MutexIDList ExclusiveLocksToAdd;
1769 MutexIDList SharedLocksToAdd;
1770 MutexIDList LocksToRemove;
1772 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
1773 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1774 switch (At->getKind()) {
1775 // When we encounter an exclusive lock function, we need to add the lock
1776 // to our lockset with kind exclusive.
1777 case attr::ExclusiveLockFunction: {
1778 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1779 Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D);
1783 // When we encounter a shared lock function, we need to add the lock
1784 // to our lockset with kind shared.
1785 case attr::SharedLockFunction: {
1786 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1787 Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D);
1791 // When we encounter an unlock function, we need to remove unlocked
1792 // mutexes from the lockset, and flag a warning if they are not there.
1793 case attr::UnlockFunction: {
1794 UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1795 Analyzer->getMutexIDs(LocksToRemove, A, Exp, D);
1799 case attr::ExclusiveLocksRequired: {
1800 ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
1802 for (ExclusiveLocksRequiredAttr::args_iterator
1803 I = A->args_begin(), E = A->args_end(); I != E; ++I)
1804 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1808 case attr::SharedLocksRequired: {
1809 SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
1811 for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1812 E = A->args_end(); I != E; ++I)
1813 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1817 case attr::LocksExcluded: {
1818 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1819 for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1820 E = A->args_end(); I != E; ++I) {
1821 SExpr Mutex(*I, Exp, D);
1822 if (!Mutex.isValid())
1823 SExpr::warnInvalidLock(Analyzer->Handler, *I, Exp, D);
1824 else if (locksetContains(Mutex))
1825 Analyzer->Handler.handleFunExcludesLock(D->getName(),
1832 // Ignore other (non thread-safety) attributes
1838 // Figure out if we're calling the constructor of scoped lockable class
1839 bool isScopedVar = false;
1841 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1842 const CXXRecordDecl* PD = CD->getParent();
1843 if (PD && PD->getAttr<ScopedLockableAttr>())
1849 SourceLocation Loc = Exp->getExprLoc();
1850 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1851 Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1852 LockData(Loc, LK_Exclusive, isScopedVar));
1854 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1855 Analyzer->addLock(FSet, SharedLocksToAdd[i],
1856 LockData(Loc, LK_Shared, isScopedVar));
1859 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1860 // FIXME -- this doesn't work if we acquire multiple locks.
1862 SourceLocation MLoc = VD->getLocation();
1863 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
1864 SExpr SMutex(&DRE, 0, 0);
1866 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1867 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
1868 ExclusiveLocksToAdd[i]));
1870 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1871 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
1872 SharedLocksToAdd[i]));
1877 // FIXME -- should only fully remove if the attribute refers to 'this'.
1878 bool Dtor = isa<CXXDestructorDecl>(D);
1879 for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
1880 Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
1885 /// \brief For unary operations which read and write a variable, we need to
1886 /// check whether we hold any required mutexes. Reads are checked in
1888 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1889 switch (UO->getOpcode()) {
1890 case clang::UO_PostDec:
1891 case clang::UO_PostInc:
1892 case clang::UO_PreDec:
1893 case clang::UO_PreInc: {
1894 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
1895 checkAccess(SubExp, AK_Written);
1896 checkDereference(SubExp, AK_Written);
1904 /// For binary operations which assign to a variable (writes), we need to check
1905 /// whether we hold any required mutexes.
1906 /// FIXME: Deal with non-primitive types.
1907 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1908 if (!BO->isAssignmentOp())
1911 // adjust the context
1912 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1914 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1915 checkAccess(LHSExp, AK_Written);
1916 checkDereference(LHSExp, AK_Written);
1919 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1920 /// need to ensure we hold any required mutexes.
1921 /// FIXME: Deal with non-primitive types.
1922 void BuildLockset::VisitCastExpr(CastExpr *CE) {
1923 if (CE->getCastKind() != CK_LValueToRValue)
1925 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
1926 checkAccess(SubExp, AK_Read);
1927 checkDereference(SubExp, AK_Read);
1931 void BuildLockset::VisitCallExpr(CallExpr *Exp) {
1932 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1933 if(!D || !D->hasAttrs())
1938 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
1939 // FIXME -- only handles constructors in DeclStmt below.
1942 void BuildLockset::VisitDeclStmt(DeclStmt *S) {
1943 // adjust the context
1944 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
1946 DeclGroupRef DGrp = S->getDeclGroup();
1947 for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1949 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1950 Expr *E = VD->getInit();
1951 // handle constructors that involve temporaries
1952 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1953 E = EWC->getSubExpr();
1955 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1956 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1957 if (!CtorD || !CtorD->hasAttrs())
1959 handleCall(CE, CtorD, VD);
1967 /// \brief Compute the intersection of two locksets and issue warnings for any
1968 /// locks in the symmetric difference.
1970 /// This function is used at a merge point in the CFG when comparing the lockset
1971 /// of each branch being merged. For example, given the following sequence:
1972 /// A; if () then B; else C; D; we need to check that the lockset after B and C
1973 /// are the same. In the event of a difference, we use the intersection of these
1974 /// two locksets at the start of D.
1976 /// \param LSet1 The first lockset.
1977 /// \param LSet2 The second lockset.
1978 /// \param JoinLoc The location of the join point for error reporting
1979 /// \param LEK1 The error message to report if a mutex is missing from LSet1
1980 /// \param LEK2 The error message to report if a mutex is missing from Lset2
1981 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
1982 const FactSet &FSet2,
1983 SourceLocation JoinLoc,
1987 FactSet FSet1Orig = FSet1;
1989 for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
1991 const SExpr &FSet2Mutex = FactMan[*I].MutID;
1992 const LockData &LDat2 = FactMan[*I].LDat;
1994 if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
1995 if (LDat1->LKind != LDat2.LKind) {
1996 Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
1999 if (Modify && LDat1->LKind != LK_Exclusive) {
2000 FSet1.removeLock(FactMan, FSet2Mutex);
2001 FSet1.addLock(FactMan, FSet2Mutex, LDat2);
2005 if (LDat2.UnderlyingMutex.isValid()) {
2006 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
2007 // If this is a scoped lock that manages another mutex, and if the
2008 // underlying mutex is still held, then warn about the underlying
2010 Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
2015 else if (!LDat2.Managed)
2016 Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
2022 for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
2024 const SExpr &FSet1Mutex = FactMan[*I].MutID;
2025 const LockData &LDat1 = FactMan[*I].LDat;
2027 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
2028 if (LDat1.UnderlyingMutex.isValid()) {
2029 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
2030 // If this is a scoped lock that manages another mutex, and if the
2031 // underlying mutex is still held, then warn about the underlying
2033 Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
2038 else if (!LDat1.Managed)
2039 Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
2043 FSet1.removeLock(FactMan, FSet1Mutex);
2050 /// \brief Check a function's CFG for thread-safety violations.
2052 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2053 /// at the end of each block, and issue warnings for thread safety violations.
2054 /// Each block in the CFG is traversed exactly once.
2055 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2056 CFG *CFGraph = AC.getCFG();
2057 if (!CFGraph) return;
2058 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2060 // AC.dumpCFG(true);
2063 return; // Ignore anonymous functions for now.
2064 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2066 // FIXME: Do something a bit more intelligent inside constructor and
2067 // destructor code. Constructors and destructors must assume unique access
2068 // to 'this', so checks on member variable access is disabled, but we should
2069 // still enable checks on other objects.
2070 if (isa<CXXConstructorDecl>(D))
2071 return; // Don't check inside constructors.
2072 if (isa<CXXDestructorDecl>(D))
2073 return; // Don't check inside destructors.
2075 BlockInfo.resize(CFGraph->getNumBlockIDs(),
2076 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2078 // We need to explore the CFG via a "topological" ordering.
2079 // That way, we will be guaranteed to have information about required
2080 // predecessor locksets when exploring a new block.
2081 PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2082 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2084 // Compute SSA names for local variables
2085 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2087 // Fill in source locations for all CFGBlocks.
2088 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2090 // Add locks from exclusive_locks_required and shared_locks_required
2091 // to initial lockset. Also turn off checking for lock and unlock functions.
2092 // FIXME: is there a more intelligent way to check lock/unlock functions?
2093 if (!SortedGraph->empty() && D->hasAttrs()) {
2094 const CFGBlock *FirstBlock = *SortedGraph->begin();
2095 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2096 const AttrVec &ArgAttrs = D->getAttrs();
2098 MutexIDList ExclusiveLocksToAdd;
2099 MutexIDList SharedLocksToAdd;
2101 SourceLocation Loc = D->getLocation();
2102 for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
2103 Attr *Attr = ArgAttrs[i];
2104 Loc = Attr->getLocation();
2105 if (ExclusiveLocksRequiredAttr *A
2106 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2107 getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2108 } else if (SharedLocksRequiredAttr *A
2109 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2110 getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
2111 } else if (isa<UnlockFunctionAttr>(Attr)) {
2112 // Don't try to check unlock functions for now
2114 } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
2115 // Don't try to check lock functions for now
2117 } else if (isa<SharedLockFunctionAttr>(Attr)) {
2118 // Don't try to check lock functions for now
2120 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2121 // Don't try to check trylock functions for now
2123 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2124 // Don't try to check trylock functions for now
2129 // FIXME -- Loc can be wrong here.
2130 for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
2131 addLock(InitialLockset, ExclusiveLocksToAdd[i],
2132 LockData(Loc, LK_Exclusive));
2134 for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
2135 addLock(InitialLockset, SharedLocksToAdd[i],
2136 LockData(Loc, LK_Shared));
2140 for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2141 E = SortedGraph->end(); I!= E; ++I) {
2142 const CFGBlock *CurrBlock = *I;
2143 int CurrBlockID = CurrBlock->getBlockID();
2144 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2146 // Use the default initial lockset in case there are no predecessors.
2147 VisitedBlocks.insert(CurrBlock);
2149 // Iterate through the predecessor blocks and warn if the lockset for all
2150 // predecessors is not the same. We take the entry lockset of the current
2151 // block to be the intersection of all previous locksets.
2152 // FIXME: By keeping the intersection, we may output more errors in future
2153 // for a lock which is not in the intersection, but was in the union. We
2154 // may want to also keep the union in future. As an example, let's say
2155 // the intersection contains Mutex L, and the union contains L and M.
2156 // Later we unlock M. At this point, we would output an error because we
2157 // never locked M; although the real error is probably that we forgot to
2158 // lock M on all code paths. Conversely, let's say that later we lock M.
2159 // In this case, we should compare against the intersection instead of the
2160 // union because the real error is probably that we forgot to unlock M on
2162 bool LocksetInitialized = false;
2163 llvm::SmallVector<CFGBlock*, 8> SpecialBlocks;
2164 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2165 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2167 // if *PI -> CurrBlock is a back edge
2168 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2171 // Ignore edges from blocks that can't return.
2172 if ((*PI)->hasNoReturnElement())
2175 // If the previous block ended in a 'continue' or 'break' statement, then
2176 // a difference in locksets is probably due to a bug in that block, rather
2177 // than in some other predecessor. In that case, keep the other
2178 // predecessor's lockset.
2179 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2180 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2181 SpecialBlocks.push_back(*PI);
2186 int PrevBlockID = (*PI)->getBlockID();
2187 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2188 FactSet PrevLockset;
2189 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2191 if (!LocksetInitialized) {
2192 CurrBlockInfo->EntrySet = PrevLockset;
2193 LocksetInitialized = true;
2195 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2196 CurrBlockInfo->EntryLoc,
2197 LEK_LockedSomePredecessors);
2201 // Process continue and break blocks. Assume that the lockset for the
2202 // resulting block is unaffected by any discrepancies in them.
2203 for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2204 SpecialI < SpecialN; ++SpecialI) {
2205 CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2206 int PrevBlockID = PrevBlock->getBlockID();
2207 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2209 if (!LocksetInitialized) {
2210 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2211 LocksetInitialized = true;
2213 // Determine whether this edge is a loop terminator for diagnostic
2214 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2215 // it might also be part of a switch. Also, a subsequent destructor
2216 // might add to the lockset, in which case the real issue might be a
2217 // double lock on the other path.
2218 const Stmt *Terminator = PrevBlock->getTerminator();
2219 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2221 FactSet PrevLockset;
2222 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2223 PrevBlock, CurrBlock);
2225 // Do not update EntrySet.
2226 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2227 PrevBlockInfo->ExitLoc,
2228 IsLoop ? LEK_LockedSomeLoopIterations
2229 : LEK_LockedSomePredecessors,
2234 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2236 // Visit all the statements in the basic block.
2237 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2238 BE = CurrBlock->end(); BI != BE; ++BI) {
2239 switch (BI->getKind()) {
2240 case CFGElement::Statement: {
2241 const CFGStmt *CS = cast<CFGStmt>(&*BI);
2242 LocksetBuilder.Visit(const_cast<Stmt*>(CS->getStmt()));
2245 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2246 case CFGElement::AutomaticObjectDtor: {
2247 const CFGAutomaticObjDtor *AD = cast<CFGAutomaticObjDtor>(&*BI);
2248 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl*>(
2249 AD->getDestructorDecl(AC.getASTContext()));
2250 if (!DD->hasAttrs())
2253 // Create a dummy expression,
2254 VarDecl *VD = const_cast<VarDecl*>(AD->getVarDecl());
2255 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
2256 AD->getTriggerStmt()->getLocEnd());
2257 LocksetBuilder.handleCall(&DRE, DD);
2264 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2266 // For every back edge from CurrBlock (the end of the loop) to another block
2267 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2268 // the one held at the beginning of FirstLoopBlock. We can look up the
2269 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2270 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2271 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2273 // if CurrBlock -> *SI is *not* a back edge
2274 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2277 CFGBlock *FirstLoopBlock = *SI;
2278 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2279 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2280 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2282 LEK_LockedSomeLoopIterations,
2287 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2288 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
2290 // FIXME: Should we call this function for all blocks which exit the function?
2291 intersectAndWarn(Initial->EntrySet, Final->ExitSet,
2293 LEK_LockedAtEndOfFunction,
2294 LEK_NotLockedAtEndOfFunction,
2298 } // end anonymous namespace
2302 namespace thread_safety {
2304 /// \brief Check a function's CFG for thread-safety violations.
2306 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2307 /// at the end of each block, and issue warnings for thread safety violations.
2308 /// Each block in the CFG is traversed exactly once.
2309 void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2310 ThreadSafetyHandler &Handler) {
2311 ThreadSafetyAnalyzer Analyzer(Handler);
2312 Analyzer.runAnalysis(AC);
2315 /// \brief Helper function that returns a LockKind required for the given level
2317 LockKind getLockKindFromAccessKind(AccessKind AK) {
2322 return LK_Exclusive;
2324 llvm_unreachable("Unknown AccessKind");
2327 }} // end namespace clang::thread_safety