ThreadSafety.cpp revision 5696884053b4a60dbed01ea8c7e6cd8dcf9b5de9
1//===- 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//
13// See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
14// information.
15//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/Analysis/Analyses/PostOrderCFGView.h"
25#include "clang/Analysis/AnalysisContext.h"
26#include "clang/Analysis/CFG.h"
27#include "clang/Analysis/CFGStmtMap.h"
28#include "clang/Basic/OperatorKinds.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/SourceManager.h"
31#include "llvm/ADT/BitVector.h"
32#include "llvm/ADT/FoldingSet.h"
33#include "llvm/ADT/ImmutableMap.h"
34#include "llvm/ADT/PostOrderIterator.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/Support/raw_ostream.h"
38#include <algorithm>
39#include <utility>
40#include <vector>
41
42using namespace clang;
43using namespace thread_safety;
44
45// Key method definition
46ThreadSafetyHandler::~ThreadSafetyHandler() {}
47
48namespace {
49
50/// SExpr implements a simple expression language that is used to store,
51/// compare, and pretty-print C++ expressions.  Unlike a clang Expr, a SExpr
52/// does not capture surface syntax, and it does not distinguish between
53/// C++ concepts, like pointers and references, that have no real semantic
54/// differences.  This simplicity allows SExprs to be meaningfully compared,
55/// e.g.
56///        (x)          =  x
57///        (*this).foo  =  this->foo
58///        *&a          =  a
59///
60/// Thread-safety analysis works by comparing lock expressions.  Within the
61/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
62/// a particular mutex object at run-time.  Subsequent occurrences of the same
63/// expression (where "same" means syntactic equality) will refer to the same
64/// run-time object if three conditions hold:
65/// (1) Local variables in the expression, such as "x" have not changed.
66/// (2) Values on the heap that affect the expression have not changed.
67/// (3) The expression involves only pure function calls.
68///
69/// The current implementation assumes, but does not verify, that multiple uses
70/// of the same lock expression satisfies these criteria.
71class SExpr {
72private:
73  enum ExprOp {
74    EOP_Nop,       ///< No-op
75    EOP_Wildcard,  ///< Matches anything.
76    EOP_Universal, ///< Universal lock.
77    EOP_This,      ///< This keyword.
78    EOP_NVar,      ///< Named variable.
79    EOP_LVar,      ///< Local variable.
80    EOP_Dot,       ///< Field access
81    EOP_Call,      ///< Function call
82    EOP_MCall,     ///< Method call
83    EOP_Index,     ///< Array index
84    EOP_Unary,     ///< Unary operation
85    EOP_Binary,    ///< Binary operation
86    EOP_Unknown    ///< Catchall for everything else
87  };
88
89
90  class SExprNode {
91   private:
92    unsigned char  Op;     ///< Opcode of the root node
93    unsigned char  Flags;  ///< Additional opcode-specific data
94    unsigned short Sz;     ///< Number of child nodes
95    const void*    Data;   ///< Additional opcode-specific data
96
97   public:
98    SExprNode(ExprOp O, unsigned F, const void* D)
99      : Op(static_cast<unsigned char>(O)),
100        Flags(static_cast<unsigned char>(F)), Sz(1), Data(D)
101    { }
102
103    unsigned size() const        { return Sz; }
104    void     setSize(unsigned S) { Sz = S;    }
105
106    ExprOp   kind() const { return static_cast<ExprOp>(Op); }
107
108    const NamedDecl* getNamedDecl() const {
109      assert(Op == EOP_NVar || Op == EOP_LVar || Op == EOP_Dot);
110      return reinterpret_cast<const NamedDecl*>(Data);
111    }
112
113    const NamedDecl* getFunctionDecl() const {
114      assert(Op == EOP_Call || Op == EOP_MCall);
115      return reinterpret_cast<const NamedDecl*>(Data);
116    }
117
118    bool isArrow() const { return Op == EOP_Dot && Flags == 1; }
119    void setArrow(bool A) { Flags = A ? 1 : 0; }
120
121    unsigned arity() const {
122      switch (Op) {
123        case EOP_Nop:       return 0;
124        case EOP_Wildcard:  return 0;
125        case EOP_Universal: return 0;
126        case EOP_NVar:      return 0;
127        case EOP_LVar:      return 0;
128        case EOP_This:      return 0;
129        case EOP_Dot:       return 1;
130        case EOP_Call:      return Flags+1;  // First arg is function.
131        case EOP_MCall:     return Flags+1;  // First arg is implicit obj.
132        case EOP_Index:     return 2;
133        case EOP_Unary:     return 1;
134        case EOP_Binary:    return 2;
135        case EOP_Unknown:   return Flags;
136      }
137      return 0;
138    }
139
140    bool operator==(const SExprNode& Other) const {
141      // Ignore flags and size -- they don't matter.
142      return (Op == Other.Op &&
143              Data == Other.Data);
144    }
145
146    bool operator!=(const SExprNode& Other) const {
147      return !(*this == Other);
148    }
149
150    bool matches(const SExprNode& Other) const {
151      return (*this == Other) ||
152             (Op == EOP_Wildcard) ||
153             (Other.Op == EOP_Wildcard);
154    }
155  };
156
157
158  /// \brief Encapsulates the lexical context of a function call.  The lexical
159  /// context includes the arguments to the call, including the implicit object
160  /// argument.  When an attribute containing a mutex expression is attached to
161  /// a method, the expression may refer to formal parameters of the method.
162  /// Actual arguments must be substituted for formal parameters to derive
163  /// the appropriate mutex expression in the lexical context where the function
164  /// is called.  PrevCtx holds the context in which the arguments themselves
165  /// should be evaluated; multiple calling contexts can be chained together
166  /// by the lock_returned attribute.
167  struct CallingContext {
168    const NamedDecl*   AttrDecl;   // The decl to which the attribute is attached.
169    const Expr*        SelfArg;    // Implicit object argument -- e.g. 'this'
170    bool               SelfArrow;  // is Self referred to with -> or .?
171    unsigned           NumArgs;    // Number of funArgs
172    const Expr* const* FunArgs;    // Function arguments
173    CallingContext*    PrevCtx;    // The previous context; or 0 if none.
174
175    CallingContext(const NamedDecl *D = 0, const Expr *S = 0,
176                   unsigned N = 0, const Expr* const *A = 0,
177                   CallingContext *P = 0)
178      : AttrDecl(D), SelfArg(S), SelfArrow(false),
179        NumArgs(N), FunArgs(A), PrevCtx(P)
180    { }
181  };
182
183  typedef SmallVector<SExprNode, 4> NodeVector;
184
185private:
186  // A SExpr is a list of SExprNodes in prefix order.  The Size field allows
187  // the list to be traversed as a tree.
188  NodeVector NodeVec;
189
190private:
191  unsigned makeNop() {
192    NodeVec.push_back(SExprNode(EOP_Nop, 0, 0));
193    return NodeVec.size()-1;
194  }
195
196  unsigned makeWildcard() {
197    NodeVec.push_back(SExprNode(EOP_Wildcard, 0, 0));
198    return NodeVec.size()-1;
199  }
200
201  unsigned makeUniversal() {
202    NodeVec.push_back(SExprNode(EOP_Universal, 0, 0));
203    return NodeVec.size()-1;
204  }
205
206  unsigned makeNamedVar(const NamedDecl *D) {
207    NodeVec.push_back(SExprNode(EOP_NVar, 0, D));
208    return NodeVec.size()-1;
209  }
210
211  unsigned makeLocalVar(const NamedDecl *D) {
212    NodeVec.push_back(SExprNode(EOP_LVar, 0, D));
213    return NodeVec.size()-1;
214  }
215
216  unsigned makeThis() {
217    NodeVec.push_back(SExprNode(EOP_This, 0, 0));
218    return NodeVec.size()-1;
219  }
220
221  unsigned makeDot(const NamedDecl *D, bool Arrow) {
222    NodeVec.push_back(SExprNode(EOP_Dot, Arrow ? 1 : 0, D));
223    return NodeVec.size()-1;
224  }
225
226  unsigned makeCall(unsigned NumArgs, const NamedDecl *D) {
227    NodeVec.push_back(SExprNode(EOP_Call, NumArgs, D));
228    return NodeVec.size()-1;
229  }
230
231  // Grab the very first declaration of virtual method D
232  const CXXMethodDecl* getFirstVirtualDecl(const CXXMethodDecl *D) {
233    while (true) {
234      D = D->getCanonicalDecl();
235      CXXMethodDecl::method_iterator I = D->begin_overridden_methods(),
236                                     E = D->end_overridden_methods();
237      if (I == E)
238        return D;  // Method does not override anything
239      D = *I;      // FIXME: this does not work with multiple inheritance.
240    }
241    return 0;
242  }
243
244  unsigned makeMCall(unsigned NumArgs, const CXXMethodDecl *D) {
245    NodeVec.push_back(SExprNode(EOP_MCall, NumArgs, getFirstVirtualDecl(D)));
246    return NodeVec.size()-1;
247  }
248
249  unsigned makeIndex() {
250    NodeVec.push_back(SExprNode(EOP_Index, 0, 0));
251    return NodeVec.size()-1;
252  }
253
254  unsigned makeUnary() {
255    NodeVec.push_back(SExprNode(EOP_Unary, 0, 0));
256    return NodeVec.size()-1;
257  }
258
259  unsigned makeBinary() {
260    NodeVec.push_back(SExprNode(EOP_Binary, 0, 0));
261    return NodeVec.size()-1;
262  }
263
264  unsigned makeUnknown(unsigned Arity) {
265    NodeVec.push_back(SExprNode(EOP_Unknown, Arity, 0));
266    return NodeVec.size()-1;
267  }
268
269  /// Build an SExpr from the given C++ expression.
270  /// Recursive function that terminates on DeclRefExpr.
271  /// Note: this function merely creates a SExpr; it does not check to
272  /// ensure that the original expression is a valid mutex expression.
273  ///
274  /// NDeref returns the number of Derefence and AddressOf operations
275  /// preceeding the Expr; this is used to decide whether to pretty-print
276  /// SExprs with . or ->.
277  unsigned buildSExpr(const Expr *Exp, CallingContext* CallCtx,
278                      int* NDeref = 0) {
279    if (!Exp)
280      return 0;
281
282    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
283      const NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
284      const ParmVarDecl *PV = dyn_cast_or_null<ParmVarDecl>(ND);
285      if (PV) {
286        const FunctionDecl *FD =
287          cast<FunctionDecl>(PV->getDeclContext())->getCanonicalDecl();
288        unsigned i = PV->getFunctionScopeIndex();
289
290        if (CallCtx && CallCtx->FunArgs &&
291            FD == CallCtx->AttrDecl->getCanonicalDecl()) {
292          // Substitute call arguments for references to function parameters
293          assert(i < CallCtx->NumArgs);
294          return buildSExpr(CallCtx->FunArgs[i], CallCtx->PrevCtx, NDeref);
295        }
296        // Map the param back to the param of the original function declaration.
297        makeNamedVar(FD->getParamDecl(i));
298        return 1;
299      }
300      // Not a function parameter -- just store the reference.
301      makeNamedVar(ND);
302      return 1;
303    } else if (isa<CXXThisExpr>(Exp)) {
304      // Substitute parent for 'this'
305      if (CallCtx && CallCtx->SelfArg) {
306        if (!CallCtx->SelfArrow && NDeref)
307          // 'this' is a pointer, but self is not, so need to take address.
308          --(*NDeref);
309        return buildSExpr(CallCtx->SelfArg, CallCtx->PrevCtx, NDeref);
310      }
311      else {
312        makeThis();
313        return 1;
314      }
315    } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
316      const NamedDecl *ND = ME->getMemberDecl();
317      int ImplicitDeref = ME->isArrow() ? 1 : 0;
318      unsigned Root = makeDot(ND, false);
319      unsigned Sz = buildSExpr(ME->getBase(), CallCtx, &ImplicitDeref);
320      NodeVec[Root].setArrow(ImplicitDeref > 0);
321      NodeVec[Root].setSize(Sz + 1);
322      return Sz + 1;
323    } else if (const CXXMemberCallExpr *CMCE = dyn_cast<CXXMemberCallExpr>(Exp)) {
324      // When calling a function with a lock_returned attribute, replace
325      // the function call with the expression in lock_returned.
326      const CXXMethodDecl* MD =
327        cast<CXXMethodDecl>(CMCE->getMethodDecl()->getMostRecentDecl());
328      if (LockReturnedAttr* At = MD->getAttr<LockReturnedAttr>()) {
329        CallingContext LRCallCtx(CMCE->getMethodDecl());
330        LRCallCtx.SelfArg = CMCE->getImplicitObjectArgument();
331        LRCallCtx.SelfArrow =
332          dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow();
333        LRCallCtx.NumArgs = CMCE->getNumArgs();
334        LRCallCtx.FunArgs = CMCE->getArgs();
335        LRCallCtx.PrevCtx = CallCtx;
336        return buildSExpr(At->getArg(), &LRCallCtx);
337      }
338      // Hack to treat smart pointers and iterators as pointers;
339      // ignore any method named get().
340      if (CMCE->getMethodDecl()->getNameAsString() == "get" &&
341          CMCE->getNumArgs() == 0) {
342        if (NDeref && dyn_cast<MemberExpr>(CMCE->getCallee())->isArrow())
343          ++(*NDeref);
344        return buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx, NDeref);
345      }
346      unsigned NumCallArgs = CMCE->getNumArgs();
347      unsigned Root = makeMCall(NumCallArgs, CMCE->getMethodDecl());
348      unsigned Sz = buildSExpr(CMCE->getImplicitObjectArgument(), CallCtx);
349      const Expr* const* CallArgs = CMCE->getArgs();
350      for (unsigned i = 0; i < NumCallArgs; ++i) {
351        Sz += buildSExpr(CallArgs[i], CallCtx);
352      }
353      NodeVec[Root].setSize(Sz + 1);
354      return Sz + 1;
355    } else if (const CallExpr *CE = dyn_cast<CallExpr>(Exp)) {
356      const FunctionDecl* FD =
357        cast<FunctionDecl>(CE->getDirectCallee()->getMostRecentDecl());
358      if (LockReturnedAttr* At = FD->getAttr<LockReturnedAttr>()) {
359        CallingContext LRCallCtx(CE->getDirectCallee());
360        LRCallCtx.NumArgs = CE->getNumArgs();
361        LRCallCtx.FunArgs = CE->getArgs();
362        LRCallCtx.PrevCtx = CallCtx;
363        return buildSExpr(At->getArg(), &LRCallCtx);
364      }
365      // Treat smart pointers and iterators as pointers;
366      // ignore the * and -> operators.
367      if (const CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(CE)) {
368        OverloadedOperatorKind k = OE->getOperator();
369        if (k == OO_Star) {
370          if (NDeref) ++(*NDeref);
371          return buildSExpr(OE->getArg(0), CallCtx, NDeref);
372        }
373        else if (k == OO_Arrow) {
374          return buildSExpr(OE->getArg(0), CallCtx, NDeref);
375        }
376      }
377      unsigned NumCallArgs = CE->getNumArgs();
378      unsigned Root = makeCall(NumCallArgs, 0);
379      unsigned Sz = buildSExpr(CE->getCallee(), CallCtx);
380      const Expr* const* CallArgs = CE->getArgs();
381      for (unsigned i = 0; i < NumCallArgs; ++i) {
382        Sz += buildSExpr(CallArgs[i], CallCtx);
383      }
384      NodeVec[Root].setSize(Sz+1);
385      return Sz+1;
386    } else if (const BinaryOperator *BOE = dyn_cast<BinaryOperator>(Exp)) {
387      unsigned Root = makeBinary();
388      unsigned Sz = buildSExpr(BOE->getLHS(), CallCtx);
389      Sz += buildSExpr(BOE->getRHS(), CallCtx);
390      NodeVec[Root].setSize(Sz);
391      return Sz;
392    } else if (const UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp)) {
393      // Ignore & and * operators -- they're no-ops.
394      // However, we try to figure out whether the expression is a pointer,
395      // so we can use . and -> appropriately in error messages.
396      if (UOE->getOpcode() == UO_Deref) {
397        if (NDeref) ++(*NDeref);
398        return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
399      }
400      if (UOE->getOpcode() == UO_AddrOf) {
401        if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(UOE->getSubExpr())) {
402          if (DRE->getDecl()->isCXXInstanceMember()) {
403            // This is a pointer-to-member expression, e.g. &MyClass::mu_.
404            // We interpret this syntax specially, as a wildcard.
405            unsigned Root = makeDot(DRE->getDecl(), false);
406            makeWildcard();
407            NodeVec[Root].setSize(2);
408            return 2;
409          }
410        }
411        if (NDeref) --(*NDeref);
412        return buildSExpr(UOE->getSubExpr(), CallCtx, NDeref);
413      }
414      unsigned Root = makeUnary();
415      unsigned Sz = buildSExpr(UOE->getSubExpr(), CallCtx);
416      NodeVec[Root].setSize(Sz);
417      return Sz;
418    } else if (const ArraySubscriptExpr *ASE =
419               dyn_cast<ArraySubscriptExpr>(Exp)) {
420      unsigned Root = makeIndex();
421      unsigned Sz = buildSExpr(ASE->getBase(), CallCtx);
422      Sz += buildSExpr(ASE->getIdx(), CallCtx);
423      NodeVec[Root].setSize(Sz);
424      return Sz;
425    } else if (const AbstractConditionalOperator *CE =
426               dyn_cast<AbstractConditionalOperator>(Exp)) {
427      unsigned Root = makeUnknown(3);
428      unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
429      Sz += buildSExpr(CE->getTrueExpr(), CallCtx);
430      Sz += buildSExpr(CE->getFalseExpr(), CallCtx);
431      NodeVec[Root].setSize(Sz);
432      return Sz;
433    } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(Exp)) {
434      unsigned Root = makeUnknown(3);
435      unsigned Sz = buildSExpr(CE->getCond(), CallCtx);
436      Sz += buildSExpr(CE->getLHS(), CallCtx);
437      Sz += buildSExpr(CE->getRHS(), CallCtx);
438      NodeVec[Root].setSize(Sz);
439      return Sz;
440    } else if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
441      return buildSExpr(CE->getSubExpr(), CallCtx, NDeref);
442    } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
443      return buildSExpr(PE->getSubExpr(), CallCtx, NDeref);
444    } else if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(Exp)) {
445      return buildSExpr(EWC->getSubExpr(), CallCtx, NDeref);
446    } else if (const CXXBindTemporaryExpr *E = dyn_cast<CXXBindTemporaryExpr>(Exp)) {
447      return buildSExpr(E->getSubExpr(), CallCtx, NDeref);
448    } else if (isa<CharacterLiteral>(Exp) ||
449               isa<CXXNullPtrLiteralExpr>(Exp) ||
450               isa<GNUNullExpr>(Exp) ||
451               isa<CXXBoolLiteralExpr>(Exp) ||
452               isa<FloatingLiteral>(Exp) ||
453               isa<ImaginaryLiteral>(Exp) ||
454               isa<IntegerLiteral>(Exp) ||
455               isa<StringLiteral>(Exp) ||
456               isa<ObjCStringLiteral>(Exp)) {
457      makeNop();
458      return 1;  // FIXME: Ignore literals for now
459    } else {
460      makeNop();
461      return 1;  // Ignore.  FIXME: mark as invalid expression?
462    }
463  }
464
465  /// \brief Construct a SExpr from an expression.
466  /// \param MutexExp The original mutex expression within an attribute
467  /// \param DeclExp An expression involving the Decl on which the attribute
468  ///        occurs.
469  /// \param D  The declaration to which the lock/unlock attribute is attached.
470  void buildSExprFromExpr(const Expr *MutexExp, const Expr *DeclExp,
471                          const NamedDecl *D, VarDecl *SelfDecl = 0) {
472    CallingContext CallCtx(D);
473
474    if (MutexExp) {
475      if (const StringLiteral* SLit = dyn_cast<StringLiteral>(MutexExp)) {
476        if (SLit->getString() == StringRef("*"))
477          // The "*" expr is a universal lock, which essentially turns off
478          // checks until it is removed from the lockset.
479          makeUniversal();
480        else
481          // Ignore other string literals for now.
482          makeNop();
483        return;
484      }
485    }
486
487    // If we are processing a raw attribute expression, with no substitutions.
488    if (DeclExp == 0) {
489      buildSExpr(MutexExp, 0);
490      return;
491    }
492
493    // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
494    // for formal parameters when we call buildMutexID later.
495    if (const MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
496      CallCtx.SelfArg   = ME->getBase();
497      CallCtx.SelfArrow = ME->isArrow();
498    } else if (const CXXMemberCallExpr *CE =
499               dyn_cast<CXXMemberCallExpr>(DeclExp)) {
500      CallCtx.SelfArg   = CE->getImplicitObjectArgument();
501      CallCtx.SelfArrow = dyn_cast<MemberExpr>(CE->getCallee())->isArrow();
502      CallCtx.NumArgs   = CE->getNumArgs();
503      CallCtx.FunArgs   = CE->getArgs();
504    } else if (const CallExpr *CE =
505               dyn_cast<CallExpr>(DeclExp)) {
506      CallCtx.NumArgs = CE->getNumArgs();
507      CallCtx.FunArgs = CE->getArgs();
508    } else if (const CXXConstructExpr *CE =
509               dyn_cast<CXXConstructExpr>(DeclExp)) {
510      CallCtx.SelfArg = 0;  // Will be set below
511      CallCtx.NumArgs = CE->getNumArgs();
512      CallCtx.FunArgs = CE->getArgs();
513    } else if (D && isa<CXXDestructorDecl>(D)) {
514      // There's no such thing as a "destructor call" in the AST.
515      CallCtx.SelfArg = DeclExp;
516    }
517
518    // Hack to handle constructors, where self cannot be recovered from
519    // the expression.
520    if (SelfDecl && !CallCtx.SelfArg) {
521      DeclRefExpr SelfDRE(SelfDecl, false, SelfDecl->getType(), VK_LValue,
522                          SelfDecl->getLocation());
523      CallCtx.SelfArg = &SelfDRE;
524
525      // If the attribute has no arguments, then assume the argument is "this".
526      if (MutexExp == 0)
527        buildSExpr(CallCtx.SelfArg, 0);
528      else  // For most attributes.
529        buildSExpr(MutexExp, &CallCtx);
530      return;
531    }
532
533    // If the attribute has no arguments, then assume the argument is "this".
534    if (MutexExp == 0)
535      buildSExpr(CallCtx.SelfArg, 0);
536    else  // For most attributes.
537      buildSExpr(MutexExp, &CallCtx);
538  }
539
540  /// \brief Get index of next sibling of node i.
541  unsigned getNextSibling(unsigned i) const {
542    return i + NodeVec[i].size();
543  }
544
545public:
546  explicit SExpr(clang::Decl::EmptyShell e) { NodeVec.clear(); }
547
548  /// \param MutexExp The original mutex expression within an attribute
549  /// \param DeclExp An expression involving the Decl on which the attribute
550  ///        occurs.
551  /// \param D  The declaration to which the lock/unlock attribute is attached.
552  /// Caller must check isValid() after construction.
553  SExpr(const Expr* MutexExp, const Expr *DeclExp, const NamedDecl* D,
554        VarDecl *SelfDecl=0) {
555    buildSExprFromExpr(MutexExp, DeclExp, D, SelfDecl);
556  }
557
558  /// Return true if this is a valid decl sequence.
559  /// Caller must call this by hand after construction to handle errors.
560  bool isValid() const {
561    return !NodeVec.empty();
562  }
563
564  bool shouldIgnore() const {
565    // Nop is a mutex that we have decided to deliberately ignore.
566    assert(NodeVec.size() > 0 && "Invalid Mutex");
567    return NodeVec[0].kind() == EOP_Nop;
568  }
569
570  bool isUniversal() const {
571    assert(NodeVec.size() > 0 && "Invalid Mutex");
572    return NodeVec[0].kind() == EOP_Universal;
573  }
574
575  /// Issue a warning about an invalid lock expression
576  static void warnInvalidLock(ThreadSafetyHandler &Handler,
577                              const Expr *MutexExp,
578                              const Expr *DeclExp, const NamedDecl* D) {
579    SourceLocation Loc;
580    if (DeclExp)
581      Loc = DeclExp->getExprLoc();
582
583    // FIXME: add a note about the attribute location in MutexExp or D
584    if (Loc.isValid())
585      Handler.handleInvalidLockExp(Loc);
586  }
587
588  bool operator==(const SExpr &other) const {
589    return NodeVec == other.NodeVec;
590  }
591
592  bool operator!=(const SExpr &other) const {
593    return !(*this == other);
594  }
595
596  bool matches(const SExpr &Other, unsigned i = 0, unsigned j = 0) const {
597    if (NodeVec[i].matches(Other.NodeVec[j])) {
598      unsigned ni = NodeVec[i].arity();
599      unsigned nj = Other.NodeVec[j].arity();
600      unsigned n = (ni < nj) ? ni : nj;
601      bool Result = true;
602      unsigned ci = i+1;  // first child of i
603      unsigned cj = j+1;  // first child of j
604      for (unsigned k = 0; k < n;
605           ++k, ci=getNextSibling(ci), cj = Other.getNextSibling(cj)) {
606        Result = Result && matches(Other, ci, cj);
607      }
608      return Result;
609    }
610    return false;
611  }
612
613  // A partial match between a.mu and b.mu returns true a and b have the same
614  // type (and thus mu refers to the same mutex declaration), regardless of
615  // whether a and b are different objects or not.
616  bool partiallyMatches(const SExpr &Other) const {
617    if (NodeVec[0].kind() == EOP_Dot)
618      return NodeVec[0].matches(Other.NodeVec[0]);
619    return false;
620  }
621
622  /// \brief Pretty print a lock expression for use in error messages.
623  std::string toString(unsigned i = 0) const {
624    assert(isValid());
625    if (i >= NodeVec.size())
626      return "";
627
628    const SExprNode* N = &NodeVec[i];
629    switch (N->kind()) {
630      case EOP_Nop:
631        return "_";
632      case EOP_Wildcard:
633        return "(?)";
634      case EOP_Universal:
635        return "*";
636      case EOP_This:
637        return "this";
638      case EOP_NVar:
639      case EOP_LVar: {
640        return N->getNamedDecl()->getNameAsString();
641      }
642      case EOP_Dot: {
643        if (NodeVec[i+1].kind() == EOP_Wildcard) {
644          std::string S = "&";
645          S += N->getNamedDecl()->getQualifiedNameAsString();
646          return S;
647        }
648        std::string FieldName = N->getNamedDecl()->getNameAsString();
649        if (NodeVec[i+1].kind() == EOP_This)
650          return FieldName;
651
652        std::string S = toString(i+1);
653        if (N->isArrow())
654          return S + "->" + FieldName;
655        else
656          return S + "." + FieldName;
657      }
658      case EOP_Call: {
659        std::string S = toString(i+1) + "(";
660        unsigned NumArgs = N->arity()-1;
661        unsigned ci = getNextSibling(i+1);
662        for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
663          S += toString(ci);
664          if (k+1 < NumArgs) S += ",";
665        }
666        S += ")";
667        return S;
668      }
669      case EOP_MCall: {
670        std::string S = "";
671        if (NodeVec[i+1].kind() != EOP_This)
672          S = toString(i+1) + ".";
673        if (const NamedDecl *D = N->getFunctionDecl())
674          S += D->getNameAsString() + "(";
675        else
676          S += "#(";
677        unsigned NumArgs = N->arity()-1;
678        unsigned ci = getNextSibling(i+1);
679        for (unsigned k=0; k<NumArgs; ++k, ci = getNextSibling(ci)) {
680          S += toString(ci);
681          if (k+1 < NumArgs) S += ",";
682        }
683        S += ")";
684        return S;
685      }
686      case EOP_Index: {
687        std::string S1 = toString(i+1);
688        std::string S2 = toString(i+1 + NodeVec[i+1].size());
689        return S1 + "[" + S2 + "]";
690      }
691      case EOP_Unary: {
692        std::string S = toString(i+1);
693        return "#" + S;
694      }
695      case EOP_Binary: {
696        std::string S1 = toString(i+1);
697        std::string S2 = toString(i+1 + NodeVec[i+1].size());
698        return "(" + S1 + "#" + S2 + ")";
699      }
700      case EOP_Unknown: {
701        unsigned NumChildren = N->arity();
702        if (NumChildren == 0)
703          return "(...)";
704        std::string S = "(";
705        unsigned ci = i+1;
706        for (unsigned j = 0; j < NumChildren; ++j, ci = getNextSibling(ci)) {
707          S += toString(ci);
708          if (j+1 < NumChildren) S += "#";
709        }
710        S += ")";
711        return S;
712      }
713    }
714    return "";
715  }
716};
717
718
719
720/// \brief A short list of SExprs
721class MutexIDList : public SmallVector<SExpr, 3> {
722public:
723  /// \brief Return true if the list contains the specified SExpr
724  /// Performs a linear search, because these lists are almost always very small.
725  bool contains(const SExpr& M) {
726    for (iterator I=begin(),E=end(); I != E; ++I)
727      if ((*I) == M) return true;
728    return false;
729  }
730
731  /// \brief Push M onto list, bud discard duplicates
732  void push_back_nodup(const SExpr& M) {
733    if (!contains(M)) push_back(M);
734  }
735};
736
737
738
739/// \brief This is a helper class that stores info about the most recent
740/// accquire of a Lock.
741///
742/// The main body of the analysis maps MutexIDs to LockDatas.
743struct LockData {
744  SourceLocation AcquireLoc;
745
746  /// \brief LKind stores whether a lock is held shared or exclusively.
747  /// Note that this analysis does not currently support either re-entrant
748  /// locking or lock "upgrading" and "downgrading" between exclusive and
749  /// shared.
750  ///
751  /// FIXME: add support for re-entrant locking and lock up/downgrading
752  LockKind LKind;
753  bool     Managed;            // for ScopedLockable objects
754  SExpr    UnderlyingMutex;    // for ScopedLockable objects
755
756  LockData(SourceLocation AcquireLoc, LockKind LKind, bool M = false)
757    : AcquireLoc(AcquireLoc), LKind(LKind), Managed(M),
758      UnderlyingMutex(Decl::EmptyShell())
759  {}
760
761  LockData(SourceLocation AcquireLoc, LockKind LKind, const SExpr &Mu)
762    : AcquireLoc(AcquireLoc), LKind(LKind), Managed(false),
763      UnderlyingMutex(Mu)
764  {}
765
766  bool operator==(const LockData &other) const {
767    return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
768  }
769
770  bool operator!=(const LockData &other) const {
771    return !(*this == other);
772  }
773
774  void Profile(llvm::FoldingSetNodeID &ID) const {
775    ID.AddInteger(AcquireLoc.getRawEncoding());
776    ID.AddInteger(LKind);
777  }
778
779  bool isAtLeast(LockKind LK) {
780    return (LK == LK_Shared) || (LKind == LK_Exclusive);
781  }
782};
783
784
785/// \brief A FactEntry stores a single fact that is known at a particular point
786/// in the program execution.  Currently, this is information regarding a lock
787/// that is held at that point.
788struct FactEntry {
789  SExpr    MutID;
790  LockData LDat;
791
792  FactEntry(const SExpr& M, const LockData& L)
793    : MutID(M), LDat(L)
794  { }
795};
796
797
798typedef unsigned short FactID;
799
800/// \brief FactManager manages the memory for all facts that are created during
801/// the analysis of a single routine.
802class FactManager {
803private:
804  std::vector<FactEntry> Facts;
805
806public:
807  FactID newLock(const SExpr& M, const LockData& L) {
808    Facts.push_back(FactEntry(M,L));
809    return static_cast<unsigned short>(Facts.size() - 1);
810  }
811
812  const FactEntry& operator[](FactID F) const { return Facts[F]; }
813  FactEntry&       operator[](FactID F)       { return Facts[F]; }
814};
815
816
817/// \brief A FactSet is the set of facts that are known to be true at a
818/// particular program point.  FactSets must be small, because they are
819/// frequently copied, and are thus implemented as a set of indices into a
820/// table maintained by a FactManager.  A typical FactSet only holds 1 or 2
821/// locks, so we can get away with doing a linear search for lookup.  Note
822/// that a hashtable or map is inappropriate in this case, because lookups
823/// may involve partial pattern matches, rather than exact matches.
824class FactSet {
825private:
826  typedef SmallVector<FactID, 4> FactVec;
827
828  FactVec FactIDs;
829
830public:
831  typedef FactVec::iterator       iterator;
832  typedef FactVec::const_iterator const_iterator;
833
834  iterator       begin()       { return FactIDs.begin(); }
835  const_iterator begin() const { return FactIDs.begin(); }
836
837  iterator       end()       { return FactIDs.end(); }
838  const_iterator end() const { return FactIDs.end(); }
839
840  bool isEmpty() const { return FactIDs.size() == 0; }
841
842  FactID addLock(FactManager& FM, const SExpr& M, const LockData& L) {
843    FactID F = FM.newLock(M, L);
844    FactIDs.push_back(F);
845    return F;
846  }
847
848  bool removeLock(FactManager& FM, const SExpr& M) {
849    unsigned n = FactIDs.size();
850    if (n == 0)
851      return false;
852
853    for (unsigned i = 0; i < n-1; ++i) {
854      if (FM[FactIDs[i]].MutID.matches(M)) {
855        FactIDs[i] = FactIDs[n-1];
856        FactIDs.pop_back();
857        return true;
858      }
859    }
860    if (FM[FactIDs[n-1]].MutID.matches(M)) {
861      FactIDs.pop_back();
862      return true;
863    }
864    return false;
865  }
866
867  LockData* findLock(FactManager &FM, const SExpr &M) const {
868    for (const_iterator I = begin(), E = end(); I != E; ++I) {
869      const SExpr &Exp = FM[*I].MutID;
870      if (Exp.matches(M))
871        return &FM[*I].LDat;
872    }
873    return 0;
874  }
875
876  LockData* findLockUniv(FactManager &FM, const SExpr &M) const {
877    for (const_iterator I = begin(), E = end(); I != E; ++I) {
878      const SExpr &Exp = FM[*I].MutID;
879      if (Exp.matches(M) || Exp.isUniversal())
880        return &FM[*I].LDat;
881    }
882    return 0;
883  }
884
885  FactEntry* findPartialMatch(FactManager &FM, const SExpr &M) const {
886    for (const_iterator I=begin(), E=end(); I != E; ++I) {
887      const SExpr& Exp = FM[*I].MutID;
888      if (Exp.partiallyMatches(M)) return &FM[*I];
889    }
890    return 0;
891  }
892};
893
894
895
896/// A Lockset maps each SExpr (defined above) to information about how it has
897/// been locked.
898typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
899typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
900
901class LocalVariableMap;
902
903/// A side (entry or exit) of a CFG node.
904enum CFGBlockSide { CBS_Entry, CBS_Exit };
905
906/// CFGBlockInfo is a struct which contains all the information that is
907/// maintained for each block in the CFG.  See LocalVariableMap for more
908/// information about the contexts.
909struct CFGBlockInfo {
910  FactSet EntrySet;             // Lockset held at entry to block
911  FactSet ExitSet;              // Lockset held at exit from block
912  LocalVarContext EntryContext; // Context held at entry to block
913  LocalVarContext ExitContext;  // Context held at exit from block
914  SourceLocation EntryLoc;      // Location of first statement in block
915  SourceLocation ExitLoc;       // Location of last statement in block.
916  unsigned EntryIndex;          // Used to replay contexts later
917  bool Reachable;               // Is this block reachable?
918
919  const FactSet &getSet(CFGBlockSide Side) const {
920    return Side == CBS_Entry ? EntrySet : ExitSet;
921  }
922  SourceLocation getLocation(CFGBlockSide Side) const {
923    return Side == CBS_Entry ? EntryLoc : ExitLoc;
924  }
925
926private:
927  CFGBlockInfo(LocalVarContext EmptyCtx)
928    : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
929  { }
930
931public:
932  static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
933};
934
935
936
937// A LocalVariableMap maintains a map from local variables to their currently
938// valid definitions.  It provides SSA-like functionality when traversing the
939// CFG.  Like SSA, each definition or assignment to a variable is assigned a
940// unique name (an integer), which acts as the SSA name for that definition.
941// The total set of names is shared among all CFG basic blocks.
942// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
943// with their SSA-names.  Instead, we compute a Context for each point in the
944// code, which maps local variables to the appropriate SSA-name.  This map
945// changes with each assignment.
946//
947// The map is computed in a single pass over the CFG.  Subsequent analyses can
948// then query the map to find the appropriate Context for a statement, and use
949// that Context to look up the definitions of variables.
950class LocalVariableMap {
951public:
952  typedef LocalVarContext Context;
953
954  /// A VarDefinition consists of an expression, representing the value of the
955  /// variable, along with the context in which that expression should be
956  /// interpreted.  A reference VarDefinition does not itself contain this
957  /// information, but instead contains a pointer to a previous VarDefinition.
958  struct VarDefinition {
959  public:
960    friend class LocalVariableMap;
961
962    const NamedDecl *Dec;  // The original declaration for this variable.
963    const Expr *Exp;       // The expression for this variable, OR
964    unsigned Ref;          // Reference to another VarDefinition
965    Context Ctx;           // The map with which Exp should be interpreted.
966
967    bool isReference() { return !Exp; }
968
969  private:
970    // Create ordinary variable definition
971    VarDefinition(const NamedDecl *D, const Expr *E, Context C)
972      : Dec(D), Exp(E), Ref(0), Ctx(C)
973    { }
974
975    // Create reference to previous definition
976    VarDefinition(const NamedDecl *D, unsigned R, Context C)
977      : Dec(D), Exp(0), Ref(R), Ctx(C)
978    { }
979  };
980
981private:
982  Context::Factory ContextFactory;
983  std::vector<VarDefinition> VarDefinitions;
984  std::vector<unsigned> CtxIndices;
985  std::vector<std::pair<Stmt*, Context> > SavedContexts;
986
987public:
988  LocalVariableMap() {
989    // index 0 is a placeholder for undefined variables (aka phi-nodes).
990    VarDefinitions.push_back(VarDefinition(0, 0u, getEmptyContext()));
991  }
992
993  /// Look up a definition, within the given context.
994  const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
995    const unsigned *i = Ctx.lookup(D);
996    if (!i)
997      return 0;
998    assert(*i < VarDefinitions.size());
999    return &VarDefinitions[*i];
1000  }
1001
1002  /// Look up the definition for D within the given context.  Returns
1003  /// NULL if the expression is not statically known.  If successful, also
1004  /// modifies Ctx to hold the context of the return Expr.
1005  const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
1006    const unsigned *P = Ctx.lookup(D);
1007    if (!P)
1008      return 0;
1009
1010    unsigned i = *P;
1011    while (i > 0) {
1012      if (VarDefinitions[i].Exp) {
1013        Ctx = VarDefinitions[i].Ctx;
1014        return VarDefinitions[i].Exp;
1015      }
1016      i = VarDefinitions[i].Ref;
1017    }
1018    return 0;
1019  }
1020
1021  Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
1022
1023  /// Return the next context after processing S.  This function is used by
1024  /// clients of the class to get the appropriate context when traversing the
1025  /// CFG.  It must be called for every assignment or DeclStmt.
1026  Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
1027    if (SavedContexts[CtxIndex+1].first == S) {
1028      CtxIndex++;
1029      Context Result = SavedContexts[CtxIndex].second;
1030      return Result;
1031    }
1032    return C;
1033  }
1034
1035  void dumpVarDefinitionName(unsigned i) {
1036    if (i == 0) {
1037      llvm::errs() << "Undefined";
1038      return;
1039    }
1040    const NamedDecl *Dec = VarDefinitions[i].Dec;
1041    if (!Dec) {
1042      llvm::errs() << "<<NULL>>";
1043      return;
1044    }
1045    Dec->printName(llvm::errs());
1046    llvm::errs() << "." << i << " " << ((const void*) Dec);
1047  }
1048
1049  /// Dumps an ASCII representation of the variable map to llvm::errs()
1050  void dump() {
1051    for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
1052      const Expr *Exp = VarDefinitions[i].Exp;
1053      unsigned Ref = VarDefinitions[i].Ref;
1054
1055      dumpVarDefinitionName(i);
1056      llvm::errs() << " = ";
1057      if (Exp) Exp->dump();
1058      else {
1059        dumpVarDefinitionName(Ref);
1060        llvm::errs() << "\n";
1061      }
1062    }
1063  }
1064
1065  /// Dumps an ASCII representation of a Context to llvm::errs()
1066  void dumpContext(Context C) {
1067    for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
1068      const NamedDecl *D = I.getKey();
1069      D->printName(llvm::errs());
1070      const unsigned *i = C.lookup(D);
1071      llvm::errs() << " -> ";
1072      dumpVarDefinitionName(*i);
1073      llvm::errs() << "\n";
1074    }
1075  }
1076
1077  /// Builds the variable map.
1078  void traverseCFG(CFG *CFGraph, PostOrderCFGView *SortedGraph,
1079                     std::vector<CFGBlockInfo> &BlockInfo);
1080
1081protected:
1082  // Get the current context index
1083  unsigned getContextIndex() { return SavedContexts.size()-1; }
1084
1085  // Save the current context for later replay
1086  void saveContext(Stmt *S, Context C) {
1087    SavedContexts.push_back(std::make_pair(S,C));
1088  }
1089
1090  // Adds a new definition to the given context, and returns a new context.
1091  // This method should be called when declaring a new variable.
1092  Context addDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
1093    assert(!Ctx.contains(D));
1094    unsigned newID = VarDefinitions.size();
1095    Context NewCtx = ContextFactory.add(Ctx, D, newID);
1096    VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1097    return NewCtx;
1098  }
1099
1100  // Add a new reference to an existing definition.
1101  Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
1102    unsigned newID = VarDefinitions.size();
1103    Context NewCtx = ContextFactory.add(Ctx, D, newID);
1104    VarDefinitions.push_back(VarDefinition(D, i, Ctx));
1105    return NewCtx;
1106  }
1107
1108  // Updates a definition only if that definition is already in the map.
1109  // This method should be called when assigning to an existing variable.
1110  Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
1111    if (Ctx.contains(D)) {
1112      unsigned newID = VarDefinitions.size();
1113      Context NewCtx = ContextFactory.remove(Ctx, D);
1114      NewCtx = ContextFactory.add(NewCtx, D, newID);
1115      VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
1116      return NewCtx;
1117    }
1118    return Ctx;
1119  }
1120
1121  // Removes a definition from the context, but keeps the variable name
1122  // as a valid variable.  The index 0 is a placeholder for cleared definitions.
1123  Context clearDefinition(const NamedDecl *D, Context Ctx) {
1124    Context NewCtx = Ctx;
1125    if (NewCtx.contains(D)) {
1126      NewCtx = ContextFactory.remove(NewCtx, D);
1127      NewCtx = ContextFactory.add(NewCtx, D, 0);
1128    }
1129    return NewCtx;
1130  }
1131
1132  // Remove a definition entirely frmo the context.
1133  Context removeDefinition(const NamedDecl *D, Context Ctx) {
1134    Context NewCtx = Ctx;
1135    if (NewCtx.contains(D)) {
1136      NewCtx = ContextFactory.remove(NewCtx, D);
1137    }
1138    return NewCtx;
1139  }
1140
1141  Context intersectContexts(Context C1, Context C2);
1142  Context createReferenceContext(Context C);
1143  void intersectBackEdge(Context C1, Context C2);
1144
1145  friend class VarMapBuilder;
1146};
1147
1148
1149// This has to be defined after LocalVariableMap.
1150CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
1151  return CFGBlockInfo(M.getEmptyContext());
1152}
1153
1154
1155/// Visitor which builds a LocalVariableMap
1156class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
1157public:
1158  LocalVariableMap* VMap;
1159  LocalVariableMap::Context Ctx;
1160
1161  VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
1162    : VMap(VM), Ctx(C) {}
1163
1164  void VisitDeclStmt(DeclStmt *S);
1165  void VisitBinaryOperator(BinaryOperator *BO);
1166};
1167
1168
1169// Add new local variables to the variable map
1170void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
1171  bool modifiedCtx = false;
1172  DeclGroupRef DGrp = S->getDeclGroup();
1173  for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
1174    if (VarDecl *VD = dyn_cast_or_null<VarDecl>(*I)) {
1175      Expr *E = VD->getInit();
1176
1177      // Add local variables with trivial type to the variable map
1178      QualType T = VD->getType();
1179      if (T.isTrivialType(VD->getASTContext())) {
1180        Ctx = VMap->addDefinition(VD, E, Ctx);
1181        modifiedCtx = true;
1182      }
1183    }
1184  }
1185  if (modifiedCtx)
1186    VMap->saveContext(S, Ctx);
1187}
1188
1189// Update local variable definitions in variable map
1190void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
1191  if (!BO->isAssignmentOp())
1192    return;
1193
1194  Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
1195
1196  // Update the variable map and current context.
1197  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
1198    ValueDecl *VDec = DRE->getDecl();
1199    if (Ctx.lookup(VDec)) {
1200      if (BO->getOpcode() == BO_Assign)
1201        Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
1202      else
1203        // FIXME -- handle compound assignment operators
1204        Ctx = VMap->clearDefinition(VDec, Ctx);
1205      VMap->saveContext(BO, Ctx);
1206    }
1207  }
1208}
1209
1210
1211// Computes the intersection of two contexts.  The intersection is the
1212// set of variables which have the same definition in both contexts;
1213// variables with different definitions are discarded.
1214LocalVariableMap::Context
1215LocalVariableMap::intersectContexts(Context C1, Context C2) {
1216  Context Result = C1;
1217  for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
1218    const NamedDecl *Dec = I.getKey();
1219    unsigned i1 = I.getData();
1220    const unsigned *i2 = C2.lookup(Dec);
1221    if (!i2)             // variable doesn't exist on second path
1222      Result = removeDefinition(Dec, Result);
1223    else if (*i2 != i1)  // variable exists, but has different definition
1224      Result = clearDefinition(Dec, Result);
1225  }
1226  return Result;
1227}
1228
1229// For every variable in C, create a new variable that refers to the
1230// definition in C.  Return a new context that contains these new variables.
1231// (We use this for a naive implementation of SSA on loop back-edges.)
1232LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
1233  Context Result = getEmptyContext();
1234  for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
1235    const NamedDecl *Dec = I.getKey();
1236    unsigned i = I.getData();
1237    Result = addReference(Dec, i, Result);
1238  }
1239  return Result;
1240}
1241
1242// This routine also takes the intersection of C1 and C2, but it does so by
1243// altering the VarDefinitions.  C1 must be the result of an earlier call to
1244// createReferenceContext.
1245void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
1246  for (Context::iterator I = C1.begin(), E = C1.end(); I != E; ++I) {
1247    const NamedDecl *Dec = I.getKey();
1248    unsigned i1 = I.getData();
1249    VarDefinition *VDef = &VarDefinitions[i1];
1250    assert(VDef->isReference());
1251
1252    const unsigned *i2 = C2.lookup(Dec);
1253    if (!i2 || (*i2 != i1))
1254      VDef->Ref = 0;    // Mark this variable as undefined
1255  }
1256}
1257
1258
1259// Traverse the CFG in topological order, so all predecessors of a block
1260// (excluding back-edges) are visited before the block itself.  At
1261// each point in the code, we calculate a Context, which holds the set of
1262// variable definitions which are visible at that point in execution.
1263// Visible variables are mapped to their definitions using an array that
1264// contains all definitions.
1265//
1266// At join points in the CFG, the set is computed as the intersection of
1267// the incoming sets along each edge, E.g.
1268//
1269//                       { Context                 | VarDefinitions }
1270//   int x = 0;          { x -> x1                 | x1 = 0 }
1271//   int y = 0;          { x -> x1, y -> y1        | y1 = 0, x1 = 0 }
1272//   if (b) x = 1;       { x -> x2, y -> y1        | x2 = 1, y1 = 0, ... }
1273//   else   x = 2;       { x -> x3, y -> y1        | x3 = 2, x2 = 1, ... }
1274//   ...                 { y -> y1  (x is unknown) | x3 = 2, x2 = 1, ... }
1275//
1276// This is essentially a simpler and more naive version of the standard SSA
1277// algorithm.  Those definitions that remain in the intersection are from blocks
1278// that strictly dominate the current block.  We do not bother to insert proper
1279// phi nodes, because they are not used in our analysis; instead, wherever
1280// a phi node would be required, we simply remove that definition from the
1281// context (E.g. x above).
1282//
1283// The initial traversal does not capture back-edges, so those need to be
1284// handled on a separate pass.  Whenever the first pass encounters an
1285// incoming back edge, it duplicates the context, creating new definitions
1286// that refer back to the originals.  (These correspond to places where SSA
1287// might have to insert a phi node.)  On the second pass, these definitions are
1288// set to NULL if the variable has changed on the back-edge (i.e. a phi
1289// node was actually required.)  E.g.
1290//
1291//                       { Context           | VarDefinitions }
1292//   int x = 0, y = 0;   { x -> x1, y -> y1  | y1 = 0, x1 = 0 }
1293//   while (b)           { x -> x2, y -> y1  | [1st:] x2=x1; [2nd:] x2=NULL; }
1294//     x = x+1;          { x -> x3, y -> y1  | x3 = x2 + 1, ... }
1295//   ...                 { y -> y1           | x3 = 2, x2 = 1, ... }
1296//
1297void LocalVariableMap::traverseCFG(CFG *CFGraph,
1298                                   PostOrderCFGView *SortedGraph,
1299                                   std::vector<CFGBlockInfo> &BlockInfo) {
1300  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
1301
1302  CtxIndices.resize(CFGraph->getNumBlockIDs());
1303
1304  for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1305       E = SortedGraph->end(); I!= E; ++I) {
1306    const CFGBlock *CurrBlock = *I;
1307    int CurrBlockID = CurrBlock->getBlockID();
1308    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
1309
1310    VisitedBlocks.insert(CurrBlock);
1311
1312    // Calculate the entry context for the current block
1313    bool HasBackEdges = false;
1314    bool CtxInit = true;
1315    for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1316         PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
1317      // if *PI -> CurrBlock is a back edge, so skip it
1318      if (*PI == 0 || !VisitedBlocks.alreadySet(*PI)) {
1319        HasBackEdges = true;
1320        continue;
1321      }
1322
1323      int PrevBlockID = (*PI)->getBlockID();
1324      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1325
1326      if (CtxInit) {
1327        CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
1328        CtxInit = false;
1329      }
1330      else {
1331        CurrBlockInfo->EntryContext =
1332          intersectContexts(CurrBlockInfo->EntryContext,
1333                            PrevBlockInfo->ExitContext);
1334      }
1335    }
1336
1337    // Duplicate the context if we have back-edges, so we can call
1338    // intersectBackEdges later.
1339    if (HasBackEdges)
1340      CurrBlockInfo->EntryContext =
1341        createReferenceContext(CurrBlockInfo->EntryContext);
1342
1343    // Create a starting context index for the current block
1344    saveContext(0, CurrBlockInfo->EntryContext);
1345    CurrBlockInfo->EntryIndex = getContextIndex();
1346
1347    // Visit all the statements in the basic block.
1348    VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
1349    for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1350         BE = CurrBlock->end(); BI != BE; ++BI) {
1351      switch (BI->getKind()) {
1352        case CFGElement::Statement: {
1353          CFGStmt CS = BI->castAs<CFGStmt>();
1354          VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
1355          break;
1356        }
1357        default:
1358          break;
1359      }
1360    }
1361    CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
1362
1363    // Mark variables on back edges as "unknown" if they've been changed.
1364    for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
1365         SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
1366      // if CurrBlock -> *SI is *not* a back edge
1367      if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
1368        continue;
1369
1370      CFGBlock *FirstLoopBlock = *SI;
1371      Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
1372      Context LoopEnd   = CurrBlockInfo->ExitContext;
1373      intersectBackEdge(LoopBegin, LoopEnd);
1374    }
1375  }
1376
1377  // Put an extra entry at the end of the indexed context array
1378  unsigned exitID = CFGraph->getExit().getBlockID();
1379  saveContext(0, BlockInfo[exitID].ExitContext);
1380}
1381
1382/// Find the appropriate source locations to use when producing diagnostics for
1383/// each block in the CFG.
1384static void findBlockLocations(CFG *CFGraph,
1385                               PostOrderCFGView *SortedGraph,
1386                               std::vector<CFGBlockInfo> &BlockInfo) {
1387  for (PostOrderCFGView::iterator I = SortedGraph->begin(),
1388       E = SortedGraph->end(); I!= E; ++I) {
1389    const CFGBlock *CurrBlock = *I;
1390    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
1391
1392    // Find the source location of the last statement in the block, if the
1393    // block is not empty.
1394    if (const Stmt *S = CurrBlock->getTerminator()) {
1395      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
1396    } else {
1397      for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
1398           BE = CurrBlock->rend(); BI != BE; ++BI) {
1399        // FIXME: Handle other CFGElement kinds.
1400        if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1401          CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
1402          break;
1403        }
1404      }
1405    }
1406
1407    if (!CurrBlockInfo->ExitLoc.isInvalid()) {
1408      // This block contains at least one statement. Find the source location
1409      // of the first statement in the block.
1410      for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1411           BE = CurrBlock->end(); BI != BE; ++BI) {
1412        // FIXME: Handle other CFGElement kinds.
1413        if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
1414          CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
1415          break;
1416        }
1417      }
1418    } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
1419               CurrBlock != &CFGraph->getExit()) {
1420      // The block is empty, and has a single predecessor. Use its exit
1421      // location.
1422      CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
1423          BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
1424    }
1425  }
1426}
1427
1428/// \brief Class which implements the core thread safety analysis routines.
1429class ThreadSafetyAnalyzer {
1430  friend class BuildLockset;
1431
1432  ThreadSafetyHandler       &Handler;
1433  LocalVariableMap          LocalVarMap;
1434  FactManager               FactMan;
1435  std::vector<CFGBlockInfo> BlockInfo;
1436
1437public:
1438  ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
1439
1440  void addLock(FactSet &FSet, const SExpr &Mutex, const LockData &LDat);
1441  void removeLock(FactSet &FSet, const SExpr &Mutex,
1442                  SourceLocation UnlockLoc, bool FullyRemove=false);
1443
1444  template <typename AttrType>
1445  void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1446                   const NamedDecl *D, VarDecl *SelfDecl=0);
1447
1448  template <class AttrType>
1449  void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
1450                   const NamedDecl *D,
1451                   const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1452                   Expr *BrE, bool Neg);
1453
1454  const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1455                                     bool &Negate);
1456
1457  void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1458                      const CFGBlock* PredBlock,
1459                      const CFGBlock *CurrBlock);
1460
1461  void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1462                        SourceLocation JoinLoc,
1463                        LockErrorKind LEK1, LockErrorKind LEK2,
1464                        bool Modify=true);
1465
1466  void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1467                        SourceLocation JoinLoc, LockErrorKind LEK1,
1468                        bool Modify=true) {
1469    intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
1470  }
1471
1472  void runAnalysis(AnalysisDeclContext &AC);
1473};
1474
1475
1476/// \brief Add a new lock to the lockset, warning if the lock is already there.
1477/// \param Mutex -- the Mutex expression for the lock
1478/// \param LDat  -- the LockData for the lock
1479void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const SExpr &Mutex,
1480                                   const LockData &LDat) {
1481  // FIXME: deal with acquired before/after annotations.
1482  // FIXME: Don't always warn when we have support for reentrant locks.
1483  if (Mutex.shouldIgnore())
1484    return;
1485
1486  if (FSet.findLock(FactMan, Mutex)) {
1487    Handler.handleDoubleLock(Mutex.toString(), LDat.AcquireLoc);
1488  } else {
1489    FSet.addLock(FactMan, Mutex, LDat);
1490  }
1491}
1492
1493
1494/// \brief Remove a lock from the lockset, warning if the lock is not there.
1495/// \param Mutex The lock expression corresponding to the lock to be removed
1496/// \param UnlockLoc The source location of the unlock (only used in error msg)
1497void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
1498                                      const SExpr &Mutex,
1499                                      SourceLocation UnlockLoc,
1500                                      bool FullyRemove) {
1501  if (Mutex.shouldIgnore())
1502    return;
1503
1504  const LockData *LDat = FSet.findLock(FactMan, Mutex);
1505  if (!LDat) {
1506    Handler.handleUnmatchedUnlock(Mutex.toString(), UnlockLoc);
1507    return;
1508  }
1509
1510  if (LDat->UnderlyingMutex.isValid()) {
1511    // This is scoped lockable object, which manages the real mutex.
1512    if (FullyRemove) {
1513      // We're destroying the managing object.
1514      // Remove the underlying mutex if it exists; but don't warn.
1515      if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1516        FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1517    } else {
1518      // We're releasing the underlying mutex, but not destroying the
1519      // managing object.  Warn on dual release.
1520      if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
1521        Handler.handleUnmatchedUnlock(LDat->UnderlyingMutex.toString(),
1522                                      UnlockLoc);
1523      }
1524      FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1525      return;
1526    }
1527  }
1528  FSet.removeLock(FactMan, Mutex);
1529}
1530
1531
1532/// \brief Extract the list of mutexIDs from the attribute on an expression,
1533/// and push them onto Mtxs, discarding any duplicates.
1534template <typename AttrType>
1535void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1536                                       Expr *Exp, const NamedDecl *D,
1537                                       VarDecl *SelfDecl) {
1538  typedef typename AttrType::args_iterator iterator_type;
1539
1540  if (Attr->args_size() == 0) {
1541    // The mutex held is the "this" object.
1542    SExpr Mu(0, Exp, D, SelfDecl);
1543    if (!Mu.isValid())
1544      SExpr::warnInvalidLock(Handler, 0, Exp, D);
1545    else
1546      Mtxs.push_back_nodup(Mu);
1547    return;
1548  }
1549
1550  for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
1551    SExpr Mu(*I, Exp, D, SelfDecl);
1552    if (!Mu.isValid())
1553      SExpr::warnInvalidLock(Handler, *I, Exp, D);
1554    else
1555      Mtxs.push_back_nodup(Mu);
1556  }
1557}
1558
1559
1560/// \brief Extract the list of mutexIDs from a trylock attribute.  If the
1561/// trylock applies to the given edge, then push them onto Mtxs, discarding
1562/// any duplicates.
1563template <class AttrType>
1564void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1565                                       Expr *Exp, const NamedDecl *D,
1566                                       const CFGBlock *PredBlock,
1567                                       const CFGBlock *CurrBlock,
1568                                       Expr *BrE, bool Neg) {
1569  // Find out which branch has the lock
1570  bool branch = 0;
1571  if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) {
1572    branch = BLE->getValue();
1573  }
1574  else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) {
1575    branch = ILE->getValue().getBoolValue();
1576  }
1577  int branchnum = branch ? 0 : 1;
1578  if (Neg) branchnum = !branchnum;
1579
1580  // If we've taken the trylock branch, then add the lock
1581  int i = 0;
1582  for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1583       SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1584    if (*SI == CurrBlock && i == branchnum) {
1585      getMutexIDs(Mtxs, Attr, Exp, D);
1586    }
1587  }
1588}
1589
1590
1591bool getStaticBooleanValue(Expr* E, bool& TCond) {
1592  if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1593    TCond = false;
1594    return true;
1595  } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1596    TCond = BLE->getValue();
1597    return true;
1598  } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1599    TCond = ILE->getValue().getBoolValue();
1600    return true;
1601  } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1602    return getStaticBooleanValue(CE->getSubExpr(), TCond);
1603  }
1604  return false;
1605}
1606
1607
1608// If Cond can be traced back to a function call, return the call expression.
1609// The negate variable should be called with false, and will be set to true
1610// if the function call is negated, e.g. if (!mu.tryLock(...))
1611const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1612                                                         LocalVarContext C,
1613                                                         bool &Negate) {
1614  if (!Cond)
1615    return 0;
1616
1617  if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1618    return CallExp;
1619  }
1620  else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1621    return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1622  }
1623  else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1624    return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1625  }
1626  else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1627    return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1628  }
1629  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1630    const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1631    return getTrylockCallExpr(E, C, Negate);
1632  }
1633  else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1634    if (UOP->getOpcode() == UO_LNot) {
1635      Negate = !Negate;
1636      return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1637    }
1638    return 0;
1639  }
1640  else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1641    if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1642      if (BOP->getOpcode() == BO_NE)
1643        Negate = !Negate;
1644
1645      bool TCond = false;
1646      if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1647        if (!TCond) Negate = !Negate;
1648        return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1649      }
1650      else if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1651        if (!TCond) Negate = !Negate;
1652        return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1653      }
1654      return 0;
1655    }
1656    return 0;
1657  }
1658  // FIXME -- handle && and || as well.
1659  return 0;
1660}
1661
1662
1663/// \brief Find the lockset that holds on the edge between PredBlock
1664/// and CurrBlock.  The edge set is the exit set of PredBlock (passed
1665/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1666void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1667                                          const FactSet &ExitSet,
1668                                          const CFGBlock *PredBlock,
1669                                          const CFGBlock *CurrBlock) {
1670  Result = ExitSet;
1671
1672  if (!PredBlock->getTerminatorCondition())
1673    return;
1674
1675  bool Negate = false;
1676  const Stmt *Cond = PredBlock->getTerminatorCondition();
1677  const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1678  const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1679
1680  CallExpr *Exp =
1681    const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
1682  if (!Exp)
1683    return;
1684
1685  NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1686  if(!FunDecl || !FunDecl->hasAttrs())
1687    return;
1688
1689
1690  MutexIDList ExclusiveLocksToAdd;
1691  MutexIDList SharedLocksToAdd;
1692
1693  // If the condition is a call to a Trylock function, then grab the attributes
1694  AttrVec &ArgAttrs = FunDecl->getAttrs();
1695  for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
1696    Attr *Attr = ArgAttrs[i];
1697    switch (Attr->getKind()) {
1698      case attr::ExclusiveTrylockFunction: {
1699        ExclusiveTrylockFunctionAttr *A =
1700          cast<ExclusiveTrylockFunctionAttr>(Attr);
1701        getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1702                    PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1703        break;
1704      }
1705      case attr::SharedTrylockFunction: {
1706        SharedTrylockFunctionAttr *A =
1707          cast<SharedTrylockFunctionAttr>(Attr);
1708        getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
1709                    PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1710        break;
1711      }
1712      default:
1713        break;
1714    }
1715  }
1716
1717  // Add and remove locks.
1718  SourceLocation Loc = Exp->getExprLoc();
1719  for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1720    addLock(Result, ExclusiveLocksToAdd[i],
1721            LockData(Loc, LK_Exclusive));
1722  }
1723  for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1724    addLock(Result, SharedLocksToAdd[i],
1725            LockData(Loc, LK_Shared));
1726  }
1727}
1728
1729
1730/// \brief We use this class to visit different types of expressions in
1731/// CFGBlocks, and build up the lockset.
1732/// An expression may cause us to add or remove locks from the lockset, or else
1733/// output error messages related to missing locks.
1734/// FIXME: In future, we may be able to not inherit from a visitor.
1735class BuildLockset : public StmtVisitor<BuildLockset> {
1736  friend class ThreadSafetyAnalyzer;
1737
1738  ThreadSafetyAnalyzer *Analyzer;
1739  FactSet FSet;
1740  LocalVariableMap::Context LVarCtx;
1741  unsigned CtxIndex;
1742
1743  // Helper functions
1744  const ValueDecl *getValueDecl(const Expr *Exp);
1745
1746  void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1747                          Expr *MutexExp, ProtectedOperationKind POK);
1748  void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp);
1749
1750  void checkAccess(const Expr *Exp, AccessKind AK);
1751  void checkPtAccess(const Expr *Exp, AccessKind AK);
1752
1753  void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = 0);
1754
1755public:
1756  BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1757    : StmtVisitor<BuildLockset>(),
1758      Analyzer(Anlzr),
1759      FSet(Info.EntrySet),
1760      LVarCtx(Info.EntryContext),
1761      CtxIndex(Info.EntryIndex)
1762  {}
1763
1764  void VisitUnaryOperator(UnaryOperator *UO);
1765  void VisitBinaryOperator(BinaryOperator *BO);
1766  void VisitCastExpr(CastExpr *CE);
1767  void VisitCallExpr(CallExpr *Exp);
1768  void VisitCXXConstructExpr(CXXConstructExpr *Exp);
1769  void VisitDeclStmt(DeclStmt *S);
1770};
1771
1772
1773/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
1774const ValueDecl *BuildLockset::getValueDecl(const Expr *Exp) {
1775  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Exp))
1776    return getValueDecl(CE->getSubExpr());
1777
1778  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
1779    return DR->getDecl();
1780
1781  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
1782    return ME->getMemberDecl();
1783
1784  return 0;
1785}
1786
1787/// \brief Warn if the LSet does not contain a lock sufficient to protect access
1788/// of at least the passed in AccessKind.
1789void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1790                                      AccessKind AK, Expr *MutexExp,
1791                                      ProtectedOperationKind POK) {
1792  LockKind LK = getLockKindFromAccessKind(AK);
1793
1794  SExpr Mutex(MutexExp, Exp, D);
1795  if (!Mutex.isValid()) {
1796    SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1797    return;
1798  } else if (Mutex.shouldIgnore()) {
1799    return;
1800  }
1801
1802  LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
1803  bool NoError = true;
1804  if (!LDat) {
1805    // No exact match found.  Look for a partial match.
1806    FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1807    if (FEntry) {
1808      // Warn that there's no precise match.
1809      LDat = &FEntry->LDat;
1810      std::string PartMatchStr = FEntry->MutID.toString();
1811      StringRef   PartMatchName(PartMatchStr);
1812      Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1813                                           Exp->getExprLoc(), &PartMatchName);
1814    } else {
1815      // Warn that there's no match at all.
1816      Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1817                                           Exp->getExprLoc());
1818    }
1819    NoError = false;
1820  }
1821  // Make sure the mutex we found is the right kind.
1822  if (NoError && LDat && !LDat->isAtLeast(LK))
1823    Analyzer->Handler.handleMutexNotHeld(D, POK, Mutex.toString(), LK,
1824                                         Exp->getExprLoc());
1825}
1826
1827/// \brief Warn if the LSet contains the given lock.
1828void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr* Exp,
1829                                   Expr *MutexExp) {
1830  SExpr Mutex(MutexExp, Exp, D);
1831  if (!Mutex.isValid()) {
1832    SExpr::warnInvalidLock(Analyzer->Handler, MutexExp, Exp, D);
1833    return;
1834  }
1835
1836  LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
1837  if (LDat) {
1838    std::string DeclName = D->getNameAsString();
1839    StringRef   DeclNameSR (DeclName);
1840    Analyzer->Handler.handleFunExcludesLock(DeclNameSR, Mutex.toString(),
1841                                            Exp->getExprLoc());
1842  }
1843}
1844
1845
1846/// \brief Checks guarded_by and pt_guarded_by attributes.
1847/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1848/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1849/// Similarly, we check if the access is to an expression that dereferences
1850/// a pointer marked with pt_guarded_by.
1851void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1852  Exp = Exp->IgnoreParenCasts();
1853
1854  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1855    // For dereferences
1856    if (UO->getOpcode() == clang::UO_Deref)
1857      checkPtAccess(UO->getSubExpr(), AK);
1858    return;
1859  }
1860
1861  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1862    if (ME->isArrow())
1863      checkPtAccess(ME->getBase(), AK);
1864    else
1865      checkAccess(ME->getBase(), AK);
1866  }
1867
1868  const ValueDecl *D = getValueDecl(Exp);
1869  if (!D || !D->hasAttrs())
1870    return;
1871
1872  if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
1873    Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
1874                                        Exp->getExprLoc());
1875
1876  const AttrVec &ArgAttrs = D->getAttrs();
1877  for (unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1878    if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
1879      warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
1880}
1881
1882/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1883void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
1884  Exp = Exp->IgnoreParenCasts();
1885
1886  const ValueDecl *D = getValueDecl(Exp);
1887  if (!D || !D->hasAttrs())
1888    return;
1889
1890  if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
1891    Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
1892                                        Exp->getExprLoc());
1893
1894  const AttrVec &ArgAttrs = D->getAttrs();
1895  for (unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
1896    if (PtGuardedByAttr *GBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
1897      warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarDereference);
1898}
1899
1900
1901/// \brief Process a function call, method call, constructor call,
1902/// or destructor call.  This involves looking at the attributes on the
1903/// corresponding function/method/constructor/destructor, issuing warnings,
1904/// and updating the locksets accordingly.
1905///
1906/// FIXME: For classes annotated with one of the guarded annotations, we need
1907/// to treat const method calls as reads and non-const method calls as writes,
1908/// and check that the appropriate locks are held. Non-const method calls with
1909/// the same signature as const method calls can be also treated as reads.
1910///
1911void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
1912  const AttrVec &ArgAttrs = D->getAttrs();
1913  MutexIDList ExclusiveLocksToAdd;
1914  MutexIDList SharedLocksToAdd;
1915  MutexIDList LocksToRemove;
1916
1917  for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
1918    Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1919    switch (At->getKind()) {
1920      // When we encounter an exclusive lock function, we need to add the lock
1921      // to our lockset with kind exclusive.
1922      case attr::ExclusiveLockFunction: {
1923        ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
1924        Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D, VD);
1925        break;
1926      }
1927
1928      // When we encounter a shared lock function, we need to add the lock
1929      // to our lockset with kind shared.
1930      case attr::SharedLockFunction: {
1931        SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
1932        Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D, VD);
1933        break;
1934      }
1935
1936      // When we encounter an unlock function, we need to remove unlocked
1937      // mutexes from the lockset, and flag a warning if they are not there.
1938      case attr::UnlockFunction: {
1939        UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
1940        Analyzer->getMutexIDs(LocksToRemove, A, Exp, D, VD);
1941        break;
1942      }
1943
1944      case attr::ExclusiveLocksRequired: {
1945        ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
1946
1947        for (ExclusiveLocksRequiredAttr::args_iterator
1948             I = A->args_begin(), E = A->args_end(); I != E; ++I)
1949          warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
1950        break;
1951      }
1952
1953      case attr::SharedLocksRequired: {
1954        SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
1955
1956        for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
1957             E = A->args_end(); I != E; ++I)
1958          warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
1959        break;
1960      }
1961
1962      case attr::LocksExcluded: {
1963        LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
1964
1965        for (LocksExcludedAttr::args_iterator I = A->args_begin(),
1966            E = A->args_end(); I != E; ++I) {
1967          warnIfMutexHeld(D, Exp, *I);
1968        }
1969        break;
1970      }
1971
1972      // Ignore other (non thread-safety) attributes
1973      default:
1974        break;
1975    }
1976  }
1977
1978  // Figure out if we're calling the constructor of scoped lockable class
1979  bool isScopedVar = false;
1980  if (VD) {
1981    if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1982      const CXXRecordDecl* PD = CD->getParent();
1983      if (PD && PD->getAttr<ScopedLockableAttr>())
1984        isScopedVar = true;
1985    }
1986  }
1987
1988  // Add locks.
1989  SourceLocation Loc = Exp->getExprLoc();
1990  for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
1991    Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
1992                            LockData(Loc, LK_Exclusive, isScopedVar));
1993  }
1994  for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
1995    Analyzer->addLock(FSet, SharedLocksToAdd[i],
1996                            LockData(Loc, LK_Shared, isScopedVar));
1997  }
1998
1999  // Add the managing object as a dummy mutex, mapped to the underlying mutex.
2000  // FIXME -- this doesn't work if we acquire multiple locks.
2001  if (isScopedVar) {
2002    SourceLocation MLoc = VD->getLocation();
2003    DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
2004    SExpr SMutex(&DRE, 0, 0);
2005
2006    for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
2007      Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
2008                                               ExclusiveLocksToAdd[i]));
2009    }
2010    for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
2011      Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
2012                                               SharedLocksToAdd[i]));
2013    }
2014  }
2015
2016  // Remove locks.
2017  // FIXME -- should only fully remove if the attribute refers to 'this'.
2018  bool Dtor = isa<CXXDestructorDecl>(D);
2019  for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
2020    Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
2021  }
2022}
2023
2024
2025/// \brief For unary operations which read and write a variable, we need to
2026/// check whether we hold any required mutexes. Reads are checked in
2027/// VisitCastExpr.
2028void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
2029  switch (UO->getOpcode()) {
2030    case clang::UO_PostDec:
2031    case clang::UO_PostInc:
2032    case clang::UO_PreDec:
2033    case clang::UO_PreInc: {
2034      checkAccess(UO->getSubExpr(), AK_Written);
2035      break;
2036    }
2037    default:
2038      break;
2039  }
2040}
2041
2042/// For binary operations which assign to a variable (writes), we need to check
2043/// whether we hold any required mutexes.
2044/// FIXME: Deal with non-primitive types.
2045void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
2046  if (!BO->isAssignmentOp())
2047    return;
2048
2049  // adjust the context
2050  LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
2051
2052  checkAccess(BO->getLHS(), AK_Written);
2053}
2054
2055/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
2056/// need to ensure we hold any required mutexes.
2057/// FIXME: Deal with non-primitive types.
2058void BuildLockset::VisitCastExpr(CastExpr *CE) {
2059  if (CE->getCastKind() != CK_LValueToRValue)
2060    return;
2061  checkAccess(CE->getSubExpr(), AK_Read);
2062}
2063
2064
2065void BuildLockset::VisitCallExpr(CallExpr *Exp) {
2066  if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2067    MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
2068    // ME can be null when calling a method pointer
2069    CXXMethodDecl *MD = CE->getMethodDecl();
2070
2071    if (ME && MD) {
2072      if (ME->isArrow()) {
2073        if (MD->isConst()) {
2074          checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2075        } else {  // FIXME -- should be AK_Written
2076          checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2077        }
2078      } else {
2079        if (MD->isConst())
2080          checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2081        else     // FIXME -- should be AK_Written
2082          checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2083      }
2084    }
2085  } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2086    switch (OE->getOperator()) {
2087      case OO_Equal: {
2088        const Expr *Target = OE->getArg(0);
2089        const Expr *Source = OE->getArg(1);
2090        checkAccess(Target, AK_Written);
2091        checkAccess(Source, AK_Read);
2092        break;
2093      }
2094      default: {
2095        const Expr *Source = OE->getArg(0);
2096        checkAccess(Source, AK_Read);
2097        break;
2098      }
2099    }
2100  }
2101  NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2102  if(!D || !D->hasAttrs())
2103    return;
2104  handleCall(Exp, D);
2105}
2106
2107void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
2108  const CXXConstructorDecl *D = Exp->getConstructor();
2109  if (D && D->isCopyConstructor()) {
2110    const Expr* Source = Exp->getArg(0);
2111    checkAccess(Source, AK_Read);
2112  }
2113  // FIXME -- only handles constructors in DeclStmt below.
2114}
2115
2116void BuildLockset::VisitDeclStmt(DeclStmt *S) {
2117  // adjust the context
2118  LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2119
2120  DeclGroupRef DGrp = S->getDeclGroup();
2121  for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
2122    Decl *D = *I;
2123    if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
2124      Expr *E = VD->getInit();
2125      // handle constructors that involve temporaries
2126      if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
2127        E = EWC->getSubExpr();
2128
2129      if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
2130        NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2131        if (!CtorD || !CtorD->hasAttrs())
2132          return;
2133        handleCall(CE, CtorD, VD);
2134      }
2135    }
2136  }
2137}
2138
2139
2140
2141/// \brief Compute the intersection of two locksets and issue warnings for any
2142/// locks in the symmetric difference.
2143///
2144/// This function is used at a merge point in the CFG when comparing the lockset
2145/// of each branch being merged. For example, given the following sequence:
2146/// A; if () then B; else C; D; we need to check that the lockset after B and C
2147/// are the same. In the event of a difference, we use the intersection of these
2148/// two locksets at the start of D.
2149///
2150/// \param FSet1 The first lockset.
2151/// \param FSet2 The second lockset.
2152/// \param JoinLoc The location of the join point for error reporting
2153/// \param LEK1 The error message to report if a mutex is missing from LSet1
2154/// \param LEK2 The error message to report if a mutex is missing from Lset2
2155void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2156                                            const FactSet &FSet2,
2157                                            SourceLocation JoinLoc,
2158                                            LockErrorKind LEK1,
2159                                            LockErrorKind LEK2,
2160                                            bool Modify) {
2161  FactSet FSet1Orig = FSet1;
2162
2163  for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
2164       I != E; ++I) {
2165    const SExpr &FSet2Mutex = FactMan[*I].MutID;
2166    const LockData &LDat2 = FactMan[*I].LDat;
2167
2168    if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
2169      if (LDat1->LKind != LDat2.LKind) {
2170        Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
2171                                         LDat2.AcquireLoc,
2172                                         LDat1->AcquireLoc);
2173        if (Modify && LDat1->LKind != LK_Exclusive) {
2174          FSet1.removeLock(FactMan, FSet2Mutex);
2175          FSet1.addLock(FactMan, FSet2Mutex, LDat2);
2176        }
2177      }
2178    } else {
2179      if (LDat2.UnderlyingMutex.isValid()) {
2180        if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
2181          // If this is a scoped lock that manages another mutex, and if the
2182          // underlying mutex is still held, then warn about the underlying
2183          // mutex.
2184          Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
2185                                            LDat2.AcquireLoc,
2186                                            JoinLoc, LEK1);
2187        }
2188      }
2189      else if (!LDat2.Managed && !FSet2Mutex.isUniversal())
2190        Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
2191                                          LDat2.AcquireLoc,
2192                                          JoinLoc, LEK1);
2193    }
2194  }
2195
2196  for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
2197       I != E; ++I) {
2198    const SExpr &FSet1Mutex = FactMan[*I].MutID;
2199    const LockData &LDat1 = FactMan[*I].LDat;
2200
2201    if (!FSet2.findLock(FactMan, FSet1Mutex)) {
2202      if (LDat1.UnderlyingMutex.isValid()) {
2203        if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
2204          // If this is a scoped lock that manages another mutex, and if the
2205          // underlying mutex is still held, then warn about the underlying
2206          // mutex.
2207          Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
2208                                            LDat1.AcquireLoc,
2209                                            JoinLoc, LEK1);
2210        }
2211      }
2212      else if (!LDat1.Managed && !FSet1Mutex.isUniversal())
2213        Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
2214                                          LDat1.AcquireLoc,
2215                                          JoinLoc, LEK2);
2216      if (Modify)
2217        FSet1.removeLock(FactMan, FSet1Mutex);
2218    }
2219  }
2220}
2221
2222
2223// Return true if block B never continues to its successors.
2224inline bool neverReturns(const CFGBlock* B) {
2225  if (B->hasNoReturnElement())
2226    return true;
2227  if (B->empty())
2228    return false;
2229
2230  CFGElement Last = B->back();
2231  if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2232    if (isa<CXXThrowExpr>(S->getStmt()))
2233      return true;
2234  }
2235  return false;
2236}
2237
2238
2239/// \brief Check a function's CFG for thread-safety violations.
2240///
2241/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2242/// at the end of each block, and issue warnings for thread safety violations.
2243/// Each block in the CFG is traversed exactly once.
2244void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2245  CFG *CFGraph = AC.getCFG();
2246  if (!CFGraph) return;
2247  const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
2248
2249  // AC.dumpCFG(true);
2250
2251  if (!D)
2252    return;  // Ignore anonymous functions for now.
2253  if (D->getAttr<NoThreadSafetyAnalysisAttr>())
2254    return;
2255  // FIXME: Do something a bit more intelligent inside constructor and
2256  // destructor code.  Constructors and destructors must assume unique access
2257  // to 'this', so checks on member variable access is disabled, but we should
2258  // still enable checks on other objects.
2259  if (isa<CXXConstructorDecl>(D))
2260    return;  // Don't check inside constructors.
2261  if (isa<CXXDestructorDecl>(D))
2262    return;  // Don't check inside destructors.
2263
2264  BlockInfo.resize(CFGraph->getNumBlockIDs(),
2265    CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2266
2267  // We need to explore the CFG via a "topological" ordering.
2268  // That way, we will be guaranteed to have information about required
2269  // predecessor locksets when exploring a new block.
2270  PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
2271  PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2272
2273  // Mark entry block as reachable
2274  BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2275
2276  // Compute SSA names for local variables
2277  LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2278
2279  // Fill in source locations for all CFGBlocks.
2280  findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2281
2282  MutexIDList ExclusiveLocksAcquired;
2283  MutexIDList SharedLocksAcquired;
2284  MutexIDList LocksReleased;
2285
2286  // Add locks from exclusive_locks_required and shared_locks_required
2287  // to initial lockset. Also turn off checking for lock and unlock functions.
2288  // FIXME: is there a more intelligent way to check lock/unlock functions?
2289  if (!SortedGraph->empty() && D->hasAttrs()) {
2290    const CFGBlock *FirstBlock = *SortedGraph->begin();
2291    FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2292    const AttrVec &ArgAttrs = D->getAttrs();
2293
2294    MutexIDList ExclusiveLocksToAdd;
2295    MutexIDList SharedLocksToAdd;
2296
2297    SourceLocation Loc = D->getLocation();
2298    for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
2299      Attr *Attr = ArgAttrs[i];
2300      Loc = Attr->getLocation();
2301      if (ExclusiveLocksRequiredAttr *A
2302            = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
2303        getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2304      } else if (SharedLocksRequiredAttr *A
2305                   = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
2306        getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
2307      } else if (UnlockFunctionAttr *A = dyn_cast<UnlockFunctionAttr>(Attr)) {
2308        if (!Handler.issueBetaWarnings())
2309          return;
2310        // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2311        // We must ignore such methods.
2312        if (A->args_size() == 0)
2313          return;
2314        // FIXME -- deal with exclusive vs. shared unlock functions?
2315        getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
2316        getMutexIDs(LocksReleased, A, (Expr*) 0, D);
2317      } else if (ExclusiveLockFunctionAttr *A
2318                   = dyn_cast<ExclusiveLockFunctionAttr>(Attr)) {
2319        if (!Handler.issueBetaWarnings())
2320          return;
2321        if (A->args_size() == 0)
2322          return;
2323        getMutexIDs(ExclusiveLocksAcquired, A, (Expr*) 0, D);
2324      } else if (SharedLockFunctionAttr *A
2325                   = dyn_cast<SharedLockFunctionAttr>(Attr)) {
2326        if (!Handler.issueBetaWarnings())
2327          return;
2328        if (A->args_size() == 0)
2329          return;
2330        getMutexIDs(SharedLocksAcquired, A, (Expr*) 0, D);
2331      } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2332        // Don't try to check trylock functions for now
2333        return;
2334      } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2335        // Don't try to check trylock functions for now
2336        return;
2337      }
2338    }
2339
2340    // FIXME -- Loc can be wrong here.
2341    for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
2342      addLock(InitialLockset, ExclusiveLocksToAdd[i],
2343              LockData(Loc, LK_Exclusive));
2344    }
2345    for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
2346      addLock(InitialLockset, SharedLocksToAdd[i],
2347              LockData(Loc, LK_Shared));
2348    }
2349  }
2350
2351  for (PostOrderCFGView::iterator I = SortedGraph->begin(),
2352       E = SortedGraph->end(); I!= E; ++I) {
2353    const CFGBlock *CurrBlock = *I;
2354    int CurrBlockID = CurrBlock->getBlockID();
2355    CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2356
2357    // Use the default initial lockset in case there are no predecessors.
2358    VisitedBlocks.insert(CurrBlock);
2359
2360    // Iterate through the predecessor blocks and warn if the lockset for all
2361    // predecessors is not the same. We take the entry lockset of the current
2362    // block to be the intersection of all previous locksets.
2363    // FIXME: By keeping the intersection, we may output more errors in future
2364    // for a lock which is not in the intersection, but was in the union. We
2365    // may want to also keep the union in future. As an example, let's say
2366    // the intersection contains Mutex L, and the union contains L and M.
2367    // Later we unlock M. At this point, we would output an error because we
2368    // never locked M; although the real error is probably that we forgot to
2369    // lock M on all code paths. Conversely, let's say that later we lock M.
2370    // In this case, we should compare against the intersection instead of the
2371    // union because the real error is probably that we forgot to unlock M on
2372    // all code paths.
2373    bool LocksetInitialized = false;
2374    SmallVector<CFGBlock *, 8> SpecialBlocks;
2375    for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2376         PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
2377
2378      // if *PI -> CurrBlock is a back edge
2379      if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
2380        continue;
2381
2382      int PrevBlockID = (*PI)->getBlockID();
2383      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2384
2385      // Ignore edges from blocks that can't return.
2386      if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
2387        continue;
2388
2389      // Okay, we can reach this block from the entry.
2390      CurrBlockInfo->Reachable = true;
2391
2392      // If the previous block ended in a 'continue' or 'break' statement, then
2393      // a difference in locksets is probably due to a bug in that block, rather
2394      // than in some other predecessor. In that case, keep the other
2395      // predecessor's lockset.
2396      if (const Stmt *Terminator = (*PI)->getTerminator()) {
2397        if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2398          SpecialBlocks.push_back(*PI);
2399          continue;
2400        }
2401      }
2402
2403      FactSet PrevLockset;
2404      getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2405
2406      if (!LocksetInitialized) {
2407        CurrBlockInfo->EntrySet = PrevLockset;
2408        LocksetInitialized = true;
2409      } else {
2410        intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2411                         CurrBlockInfo->EntryLoc,
2412                         LEK_LockedSomePredecessors);
2413      }
2414    }
2415
2416    // Skip rest of block if it's not reachable.
2417    if (!CurrBlockInfo->Reachable)
2418      continue;
2419
2420    // Process continue and break blocks. Assume that the lockset for the
2421    // resulting block is unaffected by any discrepancies in them.
2422    for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
2423         SpecialI < SpecialN; ++SpecialI) {
2424      CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
2425      int PrevBlockID = PrevBlock->getBlockID();
2426      CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2427
2428      if (!LocksetInitialized) {
2429        CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2430        LocksetInitialized = true;
2431      } else {
2432        // Determine whether this edge is a loop terminator for diagnostic
2433        // purposes. FIXME: A 'break' statement might be a loop terminator, but
2434        // it might also be part of a switch. Also, a subsequent destructor
2435        // might add to the lockset, in which case the real issue might be a
2436        // double lock on the other path.
2437        const Stmt *Terminator = PrevBlock->getTerminator();
2438        bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2439
2440        FactSet PrevLockset;
2441        getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2442                       PrevBlock, CurrBlock);
2443
2444        // Do not update EntrySet.
2445        intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2446                         PrevBlockInfo->ExitLoc,
2447                         IsLoop ? LEK_LockedSomeLoopIterations
2448                                : LEK_LockedSomePredecessors,
2449                         false);
2450      }
2451    }
2452
2453    BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2454
2455    // Visit all the statements in the basic block.
2456    for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2457         BE = CurrBlock->end(); BI != BE; ++BI) {
2458      switch (BI->getKind()) {
2459        case CFGElement::Statement: {
2460          CFGStmt CS = BI->castAs<CFGStmt>();
2461          LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
2462          break;
2463        }
2464        // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2465        case CFGElement::AutomaticObjectDtor: {
2466          CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2467          CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2468              AD.getDestructorDecl(AC.getASTContext()));
2469          if (!DD->hasAttrs())
2470            break;
2471
2472          // Create a dummy expression,
2473          VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
2474          DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
2475                          AD.getTriggerStmt()->getLocEnd());
2476          LocksetBuilder.handleCall(&DRE, DD);
2477          break;
2478        }
2479        default:
2480          break;
2481      }
2482    }
2483    CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2484
2485    // For every back edge from CurrBlock (the end of the loop) to another block
2486    // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2487    // the one held at the beginning of FirstLoopBlock. We can look up the
2488    // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2489    for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2490         SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
2491
2492      // if CurrBlock -> *SI is *not* a back edge
2493      if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
2494        continue;
2495
2496      CFGBlock *FirstLoopBlock = *SI;
2497      CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2498      CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2499      intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2500                       PreLoop->EntryLoc,
2501                       LEK_LockedSomeLoopIterations,
2502                       false);
2503    }
2504  }
2505
2506  CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2507  CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
2508
2509  // Skip the final check if the exit block is unreachable.
2510  if (!Final->Reachable)
2511    return;
2512
2513  // By default, we expect all locks held on entry to be held on exit.
2514  FactSet ExpectedExitSet = Initial->EntrySet;
2515
2516  // Adjust the expected exit set by adding or removing locks, as declared
2517  // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
2518  // issue the appropriate warning.
2519  // FIXME: the location here is not quite right.
2520  for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) {
2521    ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i],
2522                            LockData(D->getLocation(), LK_Exclusive));
2523  }
2524  for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) {
2525    ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i],
2526                            LockData(D->getLocation(), LK_Shared));
2527  }
2528  for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) {
2529    ExpectedExitSet.removeLock(FactMan, LocksReleased[i]);
2530  }
2531
2532  // FIXME: Should we call this function for all blocks which exit the function?
2533  intersectAndWarn(ExpectedExitSet, Final->ExitSet,
2534                   Final->ExitLoc,
2535                   LEK_LockedAtEndOfFunction,
2536                   LEK_NotLockedAtEndOfFunction,
2537                   false);
2538}
2539
2540} // end anonymous namespace
2541
2542
2543namespace clang {
2544namespace thread_safety {
2545
2546/// \brief Check a function's CFG for thread-safety violations.
2547///
2548/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2549/// at the end of each block, and issue warnings for thread safety violations.
2550/// Each block in the CFG is traversed exactly once.
2551void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2552                             ThreadSafetyHandler &Handler) {
2553  ThreadSafetyAnalyzer Analyzer(Handler);
2554  Analyzer.runAnalysis(AC);
2555}
2556
2557/// \brief Helper function that returns a LockKind required for the given level
2558/// of access.
2559LockKind getLockKindFromAccessKind(AccessKind AK) {
2560  switch (AK) {
2561    case AK_Read :
2562      return LK_Shared;
2563    case AK_Written :
2564      return LK_Exclusive;
2565  }
2566  llvm_unreachable("Unknown AccessKind");
2567}
2568
2569}} // end namespace clang::thread_safety
2570