Home | History | Annotate | Download | only in Analysis
      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 
     42 using namespace clang;
     43 using namespace thread_safety;
     44 
     45 // Key method definition
     46 ThreadSafetyHandler::~ThreadSafetyHandler() {}
     47 
     48 namespace {
     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.
     71 class SExpr {
     72 private:
     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 
    185 private:
    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 
    190 private:
    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 
    545 public:
    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
    721 class MutexIDList : public SmallVector<SExpr, 3> {
    722 public:
    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.
    743 struct 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.
    788 struct 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 
    798 typedef unsigned short FactID;
    799 
    800 /// \brief FactManager manages the memory for all facts that are created during
    801 /// the analysis of a single routine.
    802 class FactManager {
    803 private:
    804   std::vector<FactEntry> Facts;
    805 
    806 public:
    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.
    824 class FactSet {
    825 private:
    826   typedef SmallVector<FactID, 4> FactVec;
    827 
    828   FactVec FactIDs;
    829 
    830 public:
    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.
    898 typedef llvm::ImmutableMap<SExpr, LockData> Lockset;
    899 typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
    900 
    901 class LocalVariableMap;
    902 
    903 /// A side (entry or exit) of a CFG node.
    904 enum 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.
    909 struct 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 
    926 private:
    927   CFGBlockInfo(LocalVarContext EmptyCtx)
    928     : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
    929   { }
    930 
    931 public:
    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.
    950 class LocalVariableMap {
    951 public:
    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 
    981 private:
    982   Context::Factory ContextFactory;
    983   std::vector<VarDefinition> VarDefinitions;
    984   std::vector<unsigned> CtxIndices;
    985   std::vector<std::pair<Stmt*, Context> > SavedContexts;
    986 
    987 public:
    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 
   1081 protected:
   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.
   1150 CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
   1151   return CFGBlockInfo(M.getEmptyContext());
   1152 }
   1153 
   1154 
   1155 /// Visitor which builds a LocalVariableMap
   1156 class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
   1157 public:
   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
   1170 void 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
   1190 void 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.
   1214 LocalVariableMap::Context
   1215 LocalVariableMap::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.)
   1232 LocalVariableMap::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.
   1245 void 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 //
   1297 void 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.
   1384 static 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.
   1429 class ThreadSafetyAnalyzer {
   1430   friend class BuildLockset;
   1431 
   1432   ThreadSafetyHandler       &Handler;
   1433   LocalVariableMap          LocalVarMap;
   1434   FactManager               FactMan;
   1435   std::vector<CFGBlockInfo> BlockInfo;
   1436 
   1437 public:
   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
   1479 void 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)
   1497 void 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.
   1534 template <typename AttrType>
   1535 void 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.
   1563 template <class AttrType>
   1564 void 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 
   1591 bool 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(...))
   1611 const 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.
   1666 void 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.
   1735 class 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 
   1755 public:
   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
   1774 const 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.
   1789 void 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.
   1828 void 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.
   1851 void 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 (Analyzer->Handler.issueBetaWarnings()) {
   1862     if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
   1863       if (ME->isArrow())
   1864         checkPtAccess(ME->getBase(), AK);
   1865       else
   1866         checkAccess(ME->getBase(), AK);
   1867     }
   1868   }
   1869 
   1870   const ValueDecl *D = getValueDecl(Exp);
   1871   if (!D || !D->hasAttrs())
   1872     return;
   1873 
   1874   if (D->getAttr<GuardedVarAttr>() && FSet.isEmpty())
   1875     Analyzer->Handler.handleNoMutexHeld(D, POK_VarAccess, AK,
   1876                                         Exp->getExprLoc());
   1877 
   1878   const AttrVec &ArgAttrs = D->getAttrs();
   1879   for (unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
   1880     if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
   1881       warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
   1882 }
   1883 
   1884 /// \brief Checks pt_guarded_by and pt_guarded_var attributes.
   1885 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
   1886   Exp = Exp->IgnoreParenCasts();
   1887 
   1888   const ValueDecl *D = getValueDecl(Exp);
   1889   if (!D || !D->hasAttrs())
   1890     return;
   1891 
   1892   if (D->getAttr<PtGuardedVarAttr>() && FSet.isEmpty())
   1893     Analyzer->Handler.handleNoMutexHeld(D, POK_VarDereference, AK,
   1894                                         Exp->getExprLoc());
   1895 
   1896   const AttrVec &ArgAttrs = D->getAttrs();
   1897   for (unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
   1898     if (PtGuardedByAttr *GBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
   1899       warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarDereference);
   1900 }
   1901 
   1902 
   1903 /// \brief Process a function call, method call, constructor call,
   1904 /// or destructor call.  This involves looking at the attributes on the
   1905 /// corresponding function/method/constructor/destructor, issuing warnings,
   1906 /// and updating the locksets accordingly.
   1907 ///
   1908 /// FIXME: For classes annotated with one of the guarded annotations, we need
   1909 /// to treat const method calls as reads and non-const method calls as writes,
   1910 /// and check that the appropriate locks are held. Non-const method calls with
   1911 /// the same signature as const method calls can be also treated as reads.
   1912 ///
   1913 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
   1914   const AttrVec &ArgAttrs = D->getAttrs();
   1915   MutexIDList ExclusiveLocksToAdd;
   1916   MutexIDList SharedLocksToAdd;
   1917   MutexIDList LocksToRemove;
   1918 
   1919   for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
   1920     Attr *At = const_cast<Attr*>(ArgAttrs[i]);
   1921     switch (At->getKind()) {
   1922       // When we encounter an exclusive lock function, we need to add the lock
   1923       // to our lockset with kind exclusive.
   1924       case attr::ExclusiveLockFunction: {
   1925         ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(At);
   1926         Analyzer->getMutexIDs(ExclusiveLocksToAdd, A, Exp, D, VD);
   1927         break;
   1928       }
   1929 
   1930       // When we encounter a shared lock function, we need to add the lock
   1931       // to our lockset with kind shared.
   1932       case attr::SharedLockFunction: {
   1933         SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(At);
   1934         Analyzer->getMutexIDs(SharedLocksToAdd, A, Exp, D, VD);
   1935         break;
   1936       }
   1937 
   1938       // When we encounter an unlock function, we need to remove unlocked
   1939       // mutexes from the lockset, and flag a warning if they are not there.
   1940       case attr::UnlockFunction: {
   1941         UnlockFunctionAttr *A = cast<UnlockFunctionAttr>(At);
   1942         Analyzer->getMutexIDs(LocksToRemove, A, Exp, D, VD);
   1943         break;
   1944       }
   1945 
   1946       case attr::ExclusiveLocksRequired: {
   1947         ExclusiveLocksRequiredAttr *A = cast<ExclusiveLocksRequiredAttr>(At);
   1948 
   1949         for (ExclusiveLocksRequiredAttr::args_iterator
   1950              I = A->args_begin(), E = A->args_end(); I != E; ++I)
   1951           warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
   1952         break;
   1953       }
   1954 
   1955       case attr::SharedLocksRequired: {
   1956         SharedLocksRequiredAttr *A = cast<SharedLocksRequiredAttr>(At);
   1957 
   1958         for (SharedLocksRequiredAttr::args_iterator I = A->args_begin(),
   1959              E = A->args_end(); I != E; ++I)
   1960           warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
   1961         break;
   1962       }
   1963 
   1964       case attr::LocksExcluded: {
   1965         LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
   1966 
   1967         for (LocksExcludedAttr::args_iterator I = A->args_begin(),
   1968             E = A->args_end(); I != E; ++I) {
   1969           warnIfMutexHeld(D, Exp, *I);
   1970         }
   1971         break;
   1972       }
   1973 
   1974       // Ignore other (non thread-safety) attributes
   1975       default:
   1976         break;
   1977     }
   1978   }
   1979 
   1980   // Figure out if we're calling the constructor of scoped lockable class
   1981   bool isScopedVar = false;
   1982   if (VD) {
   1983     if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
   1984       const CXXRecordDecl* PD = CD->getParent();
   1985       if (PD && PD->getAttr<ScopedLockableAttr>())
   1986         isScopedVar = true;
   1987     }
   1988   }
   1989 
   1990   // Add locks.
   1991   SourceLocation Loc = Exp->getExprLoc();
   1992   for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
   1993     Analyzer->addLock(FSet, ExclusiveLocksToAdd[i],
   1994                             LockData(Loc, LK_Exclusive, isScopedVar));
   1995   }
   1996   for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
   1997     Analyzer->addLock(FSet, SharedLocksToAdd[i],
   1998                             LockData(Loc, LK_Shared, isScopedVar));
   1999   }
   2000 
   2001   // Add the managing object as a dummy mutex, mapped to the underlying mutex.
   2002   // FIXME -- this doesn't work if we acquire multiple locks.
   2003   if (isScopedVar) {
   2004     SourceLocation MLoc = VD->getLocation();
   2005     DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
   2006     SExpr SMutex(&DRE, 0, 0);
   2007 
   2008     for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
   2009       Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive,
   2010                                                ExclusiveLocksToAdd[i]));
   2011     }
   2012     for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
   2013       Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared,
   2014                                                SharedLocksToAdd[i]));
   2015     }
   2016   }
   2017 
   2018   // Remove locks.
   2019   // FIXME -- should only fully remove if the attribute refers to 'this'.
   2020   bool Dtor = isa<CXXDestructorDecl>(D);
   2021   for (unsigned i=0,n=LocksToRemove.size(); i<n; ++i) {
   2022     Analyzer->removeLock(FSet, LocksToRemove[i], Loc, Dtor);
   2023   }
   2024 }
   2025 
   2026 
   2027 /// \brief For unary operations which read and write a variable, we need to
   2028 /// check whether we hold any required mutexes. Reads are checked in
   2029 /// VisitCastExpr.
   2030 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
   2031   switch (UO->getOpcode()) {
   2032     case clang::UO_PostDec:
   2033     case clang::UO_PostInc:
   2034     case clang::UO_PreDec:
   2035     case clang::UO_PreInc: {
   2036       checkAccess(UO->getSubExpr(), AK_Written);
   2037       break;
   2038     }
   2039     default:
   2040       break;
   2041   }
   2042 }
   2043 
   2044 /// For binary operations which assign to a variable (writes), we need to check
   2045 /// whether we hold any required mutexes.
   2046 /// FIXME: Deal with non-primitive types.
   2047 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
   2048   if (!BO->isAssignmentOp())
   2049     return;
   2050 
   2051   // adjust the context
   2052   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
   2053 
   2054   checkAccess(BO->getLHS(), AK_Written);
   2055 }
   2056 
   2057 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
   2058 /// need to ensure we hold any required mutexes.
   2059 /// FIXME: Deal with non-primitive types.
   2060 void BuildLockset::VisitCastExpr(CastExpr *CE) {
   2061   if (CE->getCastKind() != CK_LValueToRValue)
   2062     return;
   2063   checkAccess(CE->getSubExpr(), AK_Read);
   2064 }
   2065 
   2066 
   2067 void BuildLockset::VisitCallExpr(CallExpr *Exp) {
   2068   if (Analyzer->Handler.issueBetaWarnings()) {
   2069     if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
   2070       MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
   2071       // ME can be null when calling a method pointer
   2072       CXXMethodDecl *MD = CE->getMethodDecl();
   2073 
   2074       if (ME && MD) {
   2075         if (ME->isArrow()) {
   2076           if (MD->isConst()) {
   2077             checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
   2078           } else {  // FIXME -- should be AK_Written
   2079             checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
   2080           }
   2081         } else {
   2082           if (MD->isConst())
   2083             checkAccess(CE->getImplicitObjectArgument(), AK_Read);
   2084           else     // FIXME -- should be AK_Written
   2085             checkAccess(CE->getImplicitObjectArgument(), AK_Read);
   2086         }
   2087       }
   2088     } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
   2089       switch (OE->getOperator()) {
   2090         case OO_Equal: {
   2091           const Expr *Target = OE->getArg(0);
   2092           const Expr *Source = OE->getArg(1);
   2093           checkAccess(Target, AK_Written);
   2094           checkAccess(Source, AK_Read);
   2095           break;
   2096         }
   2097         default: {
   2098           const Expr *Source = OE->getArg(0);
   2099           checkAccess(Source, AK_Read);
   2100           break;
   2101         }
   2102       }
   2103     }
   2104   }
   2105   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
   2106   if(!D || !D->hasAttrs())
   2107     return;
   2108   handleCall(Exp, D);
   2109 }
   2110 
   2111 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
   2112   if (Analyzer->Handler.issueBetaWarnings()) {
   2113     const CXXConstructorDecl *D = Exp->getConstructor();
   2114     if (D && D->isCopyConstructor()) {
   2115       const Expr* Source = Exp->getArg(0);
   2116       checkAccess(Source, AK_Read);
   2117     }
   2118   }
   2119   // FIXME -- only handles constructors in DeclStmt below.
   2120 }
   2121 
   2122 void BuildLockset::VisitDeclStmt(DeclStmt *S) {
   2123   // adjust the context
   2124   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
   2125 
   2126   DeclGroupRef DGrp = S->getDeclGroup();
   2127   for (DeclGroupRef::iterator I = DGrp.begin(), E = DGrp.end(); I != E; ++I) {
   2128     Decl *D = *I;
   2129     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
   2130       Expr *E = VD->getInit();
   2131       // handle constructors that involve temporaries
   2132       if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
   2133         E = EWC->getSubExpr();
   2134 
   2135       if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
   2136         NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
   2137         if (!CtorD || !CtorD->hasAttrs())
   2138           return;
   2139         handleCall(CE, CtorD, VD);
   2140       }
   2141     }
   2142   }
   2143 }
   2144 
   2145 
   2146 
   2147 /// \brief Compute the intersection of two locksets and issue warnings for any
   2148 /// locks in the symmetric difference.
   2149 ///
   2150 /// This function is used at a merge point in the CFG when comparing the lockset
   2151 /// of each branch being merged. For example, given the following sequence:
   2152 /// A; if () then B; else C; D; we need to check that the lockset after B and C
   2153 /// are the same. In the event of a difference, we use the intersection of these
   2154 /// two locksets at the start of D.
   2155 ///
   2156 /// \param FSet1 The first lockset.
   2157 /// \param FSet2 The second lockset.
   2158 /// \param JoinLoc The location of the join point for error reporting
   2159 /// \param LEK1 The error message to report if a mutex is missing from LSet1
   2160 /// \param LEK2 The error message to report if a mutex is missing from Lset2
   2161 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
   2162                                             const FactSet &FSet2,
   2163                                             SourceLocation JoinLoc,
   2164                                             LockErrorKind LEK1,
   2165                                             LockErrorKind LEK2,
   2166                                             bool Modify) {
   2167   FactSet FSet1Orig = FSet1;
   2168 
   2169   for (FactSet::const_iterator I = FSet2.begin(), E = FSet2.end();
   2170        I != E; ++I) {
   2171     const SExpr &FSet2Mutex = FactMan[*I].MutID;
   2172     const LockData &LDat2 = FactMan[*I].LDat;
   2173 
   2174     if (const LockData *LDat1 = FSet1.findLock(FactMan, FSet2Mutex)) {
   2175       if (LDat1->LKind != LDat2.LKind) {
   2176         Handler.handleExclusiveAndShared(FSet2Mutex.toString(),
   2177                                          LDat2.AcquireLoc,
   2178                                          LDat1->AcquireLoc);
   2179         if (Modify && LDat1->LKind != LK_Exclusive) {
   2180           FSet1.removeLock(FactMan, FSet2Mutex);
   2181           FSet1.addLock(FactMan, FSet2Mutex, LDat2);
   2182         }
   2183       }
   2184     } else {
   2185       if (LDat2.UnderlyingMutex.isValid()) {
   2186         if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
   2187           // If this is a scoped lock that manages another mutex, and if the
   2188           // underlying mutex is still held, then warn about the underlying
   2189           // mutex.
   2190           Handler.handleMutexHeldEndOfScope(LDat2.UnderlyingMutex.toString(),
   2191                                             LDat2.AcquireLoc,
   2192                                             JoinLoc, LEK1);
   2193         }
   2194       }
   2195       else if (!LDat2.Managed && !FSet2Mutex.isUniversal())
   2196         Handler.handleMutexHeldEndOfScope(FSet2Mutex.toString(),
   2197                                           LDat2.AcquireLoc,
   2198                                           JoinLoc, LEK1);
   2199     }
   2200   }
   2201 
   2202   for (FactSet::const_iterator I = FSet1.begin(), E = FSet1.end();
   2203        I != E; ++I) {
   2204     const SExpr &FSet1Mutex = FactMan[*I].MutID;
   2205     const LockData &LDat1 = FactMan[*I].LDat;
   2206 
   2207     if (!FSet2.findLock(FactMan, FSet1Mutex)) {
   2208       if (LDat1.UnderlyingMutex.isValid()) {
   2209         if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
   2210           // If this is a scoped lock that manages another mutex, and if the
   2211           // underlying mutex is still held, then warn about the underlying
   2212           // mutex.
   2213           Handler.handleMutexHeldEndOfScope(LDat1.UnderlyingMutex.toString(),
   2214                                             LDat1.AcquireLoc,
   2215                                             JoinLoc, LEK1);
   2216         }
   2217       }
   2218       else if (!LDat1.Managed && !FSet1Mutex.isUniversal())
   2219         Handler.handleMutexHeldEndOfScope(FSet1Mutex.toString(),
   2220                                           LDat1.AcquireLoc,
   2221                                           JoinLoc, LEK2);
   2222       if (Modify)
   2223         FSet1.removeLock(FactMan, FSet1Mutex);
   2224     }
   2225   }
   2226 }
   2227 
   2228 
   2229 // Return true if block B never continues to its successors.
   2230 inline bool neverReturns(const CFGBlock* B) {
   2231   if (B->hasNoReturnElement())
   2232     return true;
   2233   if (B->empty())
   2234     return false;
   2235 
   2236   CFGElement Last = B->back();
   2237   if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
   2238     if (isa<CXXThrowExpr>(S->getStmt()))
   2239       return true;
   2240   }
   2241   return false;
   2242 }
   2243 
   2244 
   2245 /// \brief Check a function's CFG for thread-safety violations.
   2246 ///
   2247 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
   2248 /// at the end of each block, and issue warnings for thread safety violations.
   2249 /// Each block in the CFG is traversed exactly once.
   2250 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
   2251   CFG *CFGraph = AC.getCFG();
   2252   if (!CFGraph) return;
   2253   const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
   2254 
   2255   // AC.dumpCFG(true);
   2256 
   2257   if (!D)
   2258     return;  // Ignore anonymous functions for now.
   2259   if (D->getAttr<NoThreadSafetyAnalysisAttr>())
   2260     return;
   2261   // FIXME: Do something a bit more intelligent inside constructor and
   2262   // destructor code.  Constructors and destructors must assume unique access
   2263   // to 'this', so checks on member variable access is disabled, but we should
   2264   // still enable checks on other objects.
   2265   if (isa<CXXConstructorDecl>(D))
   2266     return;  // Don't check inside constructors.
   2267   if (isa<CXXDestructorDecl>(D))
   2268     return;  // Don't check inside destructors.
   2269 
   2270   BlockInfo.resize(CFGraph->getNumBlockIDs(),
   2271     CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
   2272 
   2273   // We need to explore the CFG via a "topological" ordering.
   2274   // That way, we will be guaranteed to have information about required
   2275   // predecessor locksets when exploring a new block.
   2276   PostOrderCFGView *SortedGraph = AC.getAnalysis<PostOrderCFGView>();
   2277   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
   2278 
   2279   // Mark entry block as reachable
   2280   BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
   2281 
   2282   // Compute SSA names for local variables
   2283   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
   2284 
   2285   // Fill in source locations for all CFGBlocks.
   2286   findBlockLocations(CFGraph, SortedGraph, BlockInfo);
   2287 
   2288   // Add locks from exclusive_locks_required and shared_locks_required
   2289   // to initial lockset. Also turn off checking for lock and unlock functions.
   2290   // FIXME: is there a more intelligent way to check lock/unlock functions?
   2291   if (!SortedGraph->empty() && D->hasAttrs()) {
   2292     const CFGBlock *FirstBlock = *SortedGraph->begin();
   2293     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
   2294     const AttrVec &ArgAttrs = D->getAttrs();
   2295 
   2296     MutexIDList ExclusiveLocksToAdd;
   2297     MutexIDList SharedLocksToAdd;
   2298 
   2299     SourceLocation Loc = D->getLocation();
   2300     for (unsigned i = 0; i < ArgAttrs.size(); ++i) {
   2301       Attr *Attr = ArgAttrs[i];
   2302       Loc = Attr->getLocation();
   2303       if (ExclusiveLocksRequiredAttr *A
   2304             = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
   2305         getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
   2306       } else if (SharedLocksRequiredAttr *A
   2307                    = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
   2308         getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
   2309       } else if (isa<UnlockFunctionAttr>(Attr)) {
   2310         // Don't try to check unlock functions for now
   2311         return;
   2312       } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
   2313         // Don't try to check lock functions for now
   2314         return;
   2315       } else if (isa<SharedLockFunctionAttr>(Attr)) {
   2316         // Don't try to check lock functions for now
   2317         return;
   2318       } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
   2319         // Don't try to check trylock functions for now
   2320         return;
   2321       } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
   2322         // Don't try to check trylock functions for now
   2323         return;
   2324       }
   2325     }
   2326 
   2327     // FIXME -- Loc can be wrong here.
   2328     for (unsigned i=0,n=ExclusiveLocksToAdd.size(); i<n; ++i) {
   2329       addLock(InitialLockset, ExclusiveLocksToAdd[i],
   2330               LockData(Loc, LK_Exclusive));
   2331     }
   2332     for (unsigned i=0,n=SharedLocksToAdd.size(); i<n; ++i) {
   2333       addLock(InitialLockset, SharedLocksToAdd[i],
   2334               LockData(Loc, LK_Shared));
   2335     }
   2336   }
   2337 
   2338   for (PostOrderCFGView::iterator I = SortedGraph->begin(),
   2339        E = SortedGraph->end(); I!= E; ++I) {
   2340     const CFGBlock *CurrBlock = *I;
   2341     int CurrBlockID = CurrBlock->getBlockID();
   2342     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
   2343 
   2344     // Use the default initial lockset in case there are no predecessors.
   2345     VisitedBlocks.insert(CurrBlock);
   2346 
   2347     // Iterate through the predecessor blocks and warn if the lockset for all
   2348     // predecessors is not the same. We take the entry lockset of the current
   2349     // block to be the intersection of all previous locksets.
   2350     // FIXME: By keeping the intersection, we may output more errors in future
   2351     // for a lock which is not in the intersection, but was in the union. We
   2352     // may want to also keep the union in future. As an example, let's say
   2353     // the intersection contains Mutex L, and the union contains L and M.
   2354     // Later we unlock M. At this point, we would output an error because we
   2355     // never locked M; although the real error is probably that we forgot to
   2356     // lock M on all code paths. Conversely, let's say that later we lock M.
   2357     // In this case, we should compare against the intersection instead of the
   2358     // union because the real error is probably that we forgot to unlock M on
   2359     // all code paths.
   2360     bool LocksetInitialized = false;
   2361     SmallVector<CFGBlock *, 8> SpecialBlocks;
   2362     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
   2363          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
   2364 
   2365       // if *PI -> CurrBlock is a back edge
   2366       if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
   2367         continue;
   2368 
   2369       int PrevBlockID = (*PI)->getBlockID();
   2370       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
   2371 
   2372       // Ignore edges from blocks that can't return.
   2373       if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
   2374         continue;
   2375 
   2376       // Okay, we can reach this block from the entry.
   2377       CurrBlockInfo->Reachable = true;
   2378 
   2379       // If the previous block ended in a 'continue' or 'break' statement, then
   2380       // a difference in locksets is probably due to a bug in that block, rather
   2381       // than in some other predecessor. In that case, keep the other
   2382       // predecessor's lockset.
   2383       if (const Stmt *Terminator = (*PI)->getTerminator()) {
   2384         if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
   2385           SpecialBlocks.push_back(*PI);
   2386           continue;
   2387         }
   2388       }
   2389 
   2390       FactSet PrevLockset;
   2391       getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
   2392 
   2393       if (!LocksetInitialized) {
   2394         CurrBlockInfo->EntrySet = PrevLockset;
   2395         LocksetInitialized = true;
   2396       } else {
   2397         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
   2398                          CurrBlockInfo->EntryLoc,
   2399                          LEK_LockedSomePredecessors);
   2400       }
   2401     }
   2402 
   2403     // Skip rest of block if it's not reachable.
   2404     if (!CurrBlockInfo->Reachable)
   2405       continue;
   2406 
   2407     // Process continue and break blocks. Assume that the lockset for the
   2408     // resulting block is unaffected by any discrepancies in them.
   2409     for (unsigned SpecialI = 0, SpecialN = SpecialBlocks.size();
   2410          SpecialI < SpecialN; ++SpecialI) {
   2411       CFGBlock *PrevBlock = SpecialBlocks[SpecialI];
   2412       int PrevBlockID = PrevBlock->getBlockID();
   2413       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
   2414 
   2415       if (!LocksetInitialized) {
   2416         CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
   2417         LocksetInitialized = true;
   2418       } else {
   2419         // Determine whether this edge is a loop terminator for diagnostic
   2420         // purposes. FIXME: A 'break' statement might be a loop terminator, but
   2421         // it might also be part of a switch. Also, a subsequent destructor
   2422         // might add to the lockset, in which case the real issue might be a
   2423         // double lock on the other path.
   2424         const Stmt *Terminator = PrevBlock->getTerminator();
   2425         bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
   2426 
   2427         FactSet PrevLockset;
   2428         getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
   2429                        PrevBlock, CurrBlock);
   2430 
   2431         // Do not update EntrySet.
   2432         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
   2433                          PrevBlockInfo->ExitLoc,
   2434                          IsLoop ? LEK_LockedSomeLoopIterations
   2435                                 : LEK_LockedSomePredecessors,
   2436                          false);
   2437       }
   2438     }
   2439 
   2440     BuildLockset LocksetBuilder(this, *CurrBlockInfo);
   2441 
   2442     // Visit all the statements in the basic block.
   2443     for (CFGBlock::const_iterator BI = CurrBlock->begin(),
   2444          BE = CurrBlock->end(); BI != BE; ++BI) {
   2445       switch (BI->getKind()) {
   2446         case CFGElement::Statement: {
   2447           CFGStmt CS = BI->castAs<CFGStmt>();
   2448           LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
   2449           break;
   2450         }
   2451         // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
   2452         case CFGElement::AutomaticObjectDtor: {
   2453           CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
   2454           CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
   2455               AD.getDestructorDecl(AC.getASTContext()));
   2456           if (!DD->hasAttrs())
   2457             break;
   2458 
   2459           // Create a dummy expression,
   2460           VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
   2461           DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
   2462                           AD.getTriggerStmt()->getLocEnd());
   2463           LocksetBuilder.handleCall(&DRE, DD);
   2464           break;
   2465         }
   2466         default:
   2467           break;
   2468       }
   2469     }
   2470     CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
   2471 
   2472     // For every back edge from CurrBlock (the end of the loop) to another block
   2473     // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
   2474     // the one held at the beginning of FirstLoopBlock. We can look up the
   2475     // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
   2476     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
   2477          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
   2478 
   2479       // if CurrBlock -> *SI is *not* a back edge
   2480       if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
   2481         continue;
   2482 
   2483       CFGBlock *FirstLoopBlock = *SI;
   2484       CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
   2485       CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
   2486       intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
   2487                        PreLoop->EntryLoc,
   2488                        LEK_LockedSomeLoopIterations,
   2489                        false);
   2490     }
   2491   }
   2492 
   2493   CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
   2494   CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
   2495 
   2496   // Skip the final check if the exit block is unreachable.
   2497   if (!Final->Reachable)
   2498     return;
   2499 
   2500   // FIXME: Should we call this function for all blocks which exit the function?
   2501   intersectAndWarn(Initial->EntrySet, Final->ExitSet,
   2502                    Final->ExitLoc,
   2503                    LEK_LockedAtEndOfFunction,
   2504                    LEK_NotLockedAtEndOfFunction,
   2505                    false);
   2506 }
   2507 
   2508 } // end anonymous namespace
   2509 
   2510 
   2511 namespace clang {
   2512 namespace thread_safety {
   2513 
   2514 /// \brief Check a function's CFG for thread-safety violations.
   2515 ///
   2516 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
   2517 /// at the end of each block, and issue warnings for thread safety violations.
   2518 /// Each block in the CFG is traversed exactly once.
   2519 void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
   2520                              ThreadSafetyHandler &Handler) {
   2521   ThreadSafetyAnalyzer Analyzer(Handler);
   2522   Analyzer.runAnalysis(AC);
   2523 }
   2524 
   2525 /// \brief Helper function that returns a LockKind required for the given level
   2526 /// of access.
   2527 LockKind getLockKindFromAccessKind(AccessKind AK) {
   2528   switch (AK) {
   2529     case AK_Read :
   2530       return LK_Shared;
   2531     case AK_Written :
   2532       return LK_Exclusive;
   2533   }
   2534   llvm_unreachable("Unknown AccessKind");
   2535 }
   2536 
   2537 }} // end namespace clang::thread_safety
   2538