clang API Documentation

ThreadSafety.cpp
Go to the documentation of this file.
00001 //===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // A intra-procedural analysis for thread safety (e.g. deadlocks and race
00011 // conditions), based off of an annotation system.
00012 //
00013 // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
00014 // for more information.
00015 //
00016 //===----------------------------------------------------------------------===//
00017 
00018 #include "clang/AST/Attr.h"
00019 #include "clang/AST/DeclCXX.h"
00020 #include "clang/AST/ExprCXX.h"
00021 #include "clang/AST/StmtCXX.h"
00022 #include "clang/AST/StmtVisitor.h"
00023 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
00024 #include "clang/Analysis/Analyses/ThreadSafety.h"
00025 #include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
00026 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
00027 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
00028 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
00029 #include "clang/Analysis/AnalysisContext.h"
00030 #include "clang/Analysis/CFG.h"
00031 #include "clang/Analysis/CFGStmtMap.h"
00032 #include "clang/Basic/OperatorKinds.h"
00033 #include "clang/Basic/SourceLocation.h"
00034 #include "clang/Basic/SourceManager.h"
00035 #include "llvm/ADT/BitVector.h"
00036 #include "llvm/ADT/FoldingSet.h"
00037 #include "llvm/ADT/ImmutableMap.h"
00038 #include "llvm/ADT/PostOrderIterator.h"
00039 #include "llvm/ADT/SmallVector.h"
00040 #include "llvm/ADT/StringRef.h"
00041 #include "llvm/Support/raw_ostream.h"
00042 #include <algorithm>
00043 #include <ostream>
00044 #include <sstream>
00045 #include <utility>
00046 #include <vector>
00047 
00048 
00049 namespace clang {
00050 namespace threadSafety {
00051 
00052 // Key method definition
00053 ThreadSafetyHandler::~ThreadSafetyHandler() {}
00054 
00055 class TILPrinter :
00056   public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
00057 
00058 
00059 /// Issue a warning about an invalid lock expression
00060 static void warnInvalidLock(ThreadSafetyHandler &Handler,
00061                             const Expr *MutexExp, const NamedDecl *D,
00062                             const Expr *DeclExp, StringRef Kind) {
00063   SourceLocation Loc;
00064   if (DeclExp)
00065     Loc = DeclExp->getExprLoc();
00066 
00067   // FIXME: add a note about the attribute location in MutexExp or D
00068   if (Loc.isValid())
00069     Handler.handleInvalidLockExp(Kind, Loc);
00070 }
00071 
00072 
00073 /// \brief A set of CapabilityInfo objects, which are compiled from the
00074 /// requires attributes on a function.
00075 class CapExprSet : public SmallVector<CapabilityExpr, 4> {
00076 public:
00077   /// \brief Push M onto list, but discard duplicates.
00078   void push_back_nodup(const CapabilityExpr &CapE) {
00079     iterator It = std::find_if(begin(), end(),
00080                                [=](const CapabilityExpr &CapE2) {
00081       return CapE.equals(CapE2);
00082     });
00083     if (It == end())
00084       push_back(CapE);
00085   }
00086 };
00087 
00088 class FactManager;
00089 class FactSet;
00090 
00091 /// \brief This is a helper class that stores a fact that is known at a
00092 /// particular point in program execution.  Currently, a fact is a capability,
00093 /// along with additional information, such as where it was acquired, whether
00094 /// it is exclusive or shared, etc.
00095 ///
00096 /// FIXME: this analysis does not currently support either re-entrant
00097 /// locking or lock "upgrading" and "downgrading" between exclusive and
00098 /// shared.
00099 class FactEntry : public CapabilityExpr {
00100 private:
00101   LockKind          LKind;            ///<  exclusive or shared
00102   SourceLocation    AcquireLoc;       ///<  where it was acquired.
00103   bool              Asserted;         ///<  true if the lock was asserted
00104 
00105 public:
00106   FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
00107             bool Asrt)
00108       : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt) {}
00109 
00110   virtual ~FactEntry() {}
00111 
00112   LockKind          kind()       const { return LKind;    }
00113   SourceLocation    loc()        const { return AcquireLoc; }
00114   bool              asserted()   const { return Asserted; }
00115 
00116   virtual void
00117   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
00118                                 SourceLocation JoinLoc, LockErrorKind LEK,
00119                                 ThreadSafetyHandler &Handler) const = 0;
00120   virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
00121                             const CapabilityExpr &Cp, SourceLocation UnlockLoc,
00122                             bool FullyRemove, ThreadSafetyHandler &Handler,
00123                             StringRef DiagKind) const = 0;
00124 
00125   // Return true if LKind >= LK, where exclusive > shared
00126   bool isAtLeast(LockKind LK) {
00127     return  (LKind == LK_Exclusive) || (LK == LK_Shared);
00128   }
00129 };
00130 
00131 
00132 typedef unsigned short FactID;
00133 
00134 /// \brief FactManager manages the memory for all facts that are created during
00135 /// the analysis of a single routine.
00136 class FactManager {
00137 private:
00138   std::vector<std::unique_ptr<FactEntry>> Facts;
00139 
00140 public:
00141   FactID newFact(std::unique_ptr<FactEntry> Entry) {
00142     Facts.push_back(std::move(Entry));
00143     return static_cast<unsigned short>(Facts.size() - 1);
00144   }
00145 
00146   const FactEntry &operator[](FactID F) const { return *Facts[F]; }
00147   FactEntry &operator[](FactID F) { return *Facts[F]; }
00148 };
00149 
00150 
00151 /// \brief A FactSet is the set of facts that are known to be true at a
00152 /// particular program point.  FactSets must be small, because they are
00153 /// frequently copied, and are thus implemented as a set of indices into a
00154 /// table maintained by a FactManager.  A typical FactSet only holds 1 or 2
00155 /// locks, so we can get away with doing a linear search for lookup.  Note
00156 /// that a hashtable or map is inappropriate in this case, because lookups
00157 /// may involve partial pattern matches, rather than exact matches.
00158 class FactSet {
00159 private:
00160   typedef SmallVector<FactID, 4> FactVec;
00161 
00162   FactVec FactIDs;
00163 
00164 public:
00165   typedef FactVec::iterator       iterator;
00166   typedef FactVec::const_iterator const_iterator;
00167 
00168   iterator       begin()       { return FactIDs.begin(); }
00169   const_iterator begin() const { return FactIDs.begin(); }
00170 
00171   iterator       end()       { return FactIDs.end(); }
00172   const_iterator end() const { return FactIDs.end(); }
00173 
00174   bool isEmpty() const { return FactIDs.size() == 0; }
00175 
00176   // Return true if the set contains only negative facts
00177   bool isEmpty(FactManager &FactMan) const {
00178     for (FactID FID : *this) {
00179       if (!FactMan[FID].negative())
00180         return false;
00181     }
00182     return true;
00183   }
00184 
00185   void addLockByID(FactID ID) { FactIDs.push_back(ID); }
00186 
00187   FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
00188     FactID F = FM.newFact(std::move(Entry));
00189     FactIDs.push_back(F);
00190     return F;
00191   }
00192 
00193   bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
00194     unsigned n = FactIDs.size();
00195     if (n == 0)
00196       return false;
00197 
00198     for (unsigned i = 0; i < n-1; ++i) {
00199       if (FM[FactIDs[i]].matches(CapE)) {
00200         FactIDs[i] = FactIDs[n-1];
00201         FactIDs.pop_back();
00202         return true;
00203       }
00204     }
00205     if (FM[FactIDs[n-1]].matches(CapE)) {
00206       FactIDs.pop_back();
00207       return true;
00208     }
00209     return false;
00210   }
00211 
00212   iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
00213     return std::find_if(begin(), end(), [&](FactID ID) {
00214       return FM[ID].matches(CapE);
00215     });
00216   }
00217 
00218   FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
00219     auto I = std::find_if(begin(), end(), [&](FactID ID) {
00220       return FM[ID].matches(CapE);
00221     });
00222     return I != end() ? &FM[*I] : nullptr;
00223   }
00224 
00225   FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
00226     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
00227       return FM[ID].matchesUniv(CapE);
00228     });
00229     return I != end() ? &FM[*I] : nullptr;
00230   }
00231 
00232   FactEntry *findPartialMatch(FactManager &FM,
00233                               const CapabilityExpr &CapE) const {
00234     auto I = std::find_if(begin(), end(), [&](FactID ID) {
00235       return FM[ID].partiallyMatches(CapE);
00236     });
00237     return I != end() ? &FM[*I] : nullptr;
00238   }
00239 };
00240 
00241 
00242 typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
00243 class LocalVariableMap;
00244 
00245 /// A side (entry or exit) of a CFG node.
00246 enum CFGBlockSide { CBS_Entry, CBS_Exit };
00247 
00248 /// CFGBlockInfo is a struct which contains all the information that is
00249 /// maintained for each block in the CFG.  See LocalVariableMap for more
00250 /// information about the contexts.
00251 struct CFGBlockInfo {
00252   FactSet EntrySet;             // Lockset held at entry to block
00253   FactSet ExitSet;              // Lockset held at exit from block
00254   LocalVarContext EntryContext; // Context held at entry to block
00255   LocalVarContext ExitContext;  // Context held at exit from block
00256   SourceLocation EntryLoc;      // Location of first statement in block
00257   SourceLocation ExitLoc;       // Location of last statement in block.
00258   unsigned EntryIndex;          // Used to replay contexts later
00259   bool Reachable;               // Is this block reachable?
00260 
00261   const FactSet &getSet(CFGBlockSide Side) const {
00262     return Side == CBS_Entry ? EntrySet : ExitSet;
00263   }
00264   SourceLocation getLocation(CFGBlockSide Side) const {
00265     return Side == CBS_Entry ? EntryLoc : ExitLoc;
00266   }
00267 
00268 private:
00269   CFGBlockInfo(LocalVarContext EmptyCtx)
00270     : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
00271   { }
00272 
00273 public:
00274   static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
00275 };
00276 
00277 
00278 
00279 // A LocalVariableMap maintains a map from local variables to their currently
00280 // valid definitions.  It provides SSA-like functionality when traversing the
00281 // CFG.  Like SSA, each definition or assignment to a variable is assigned a
00282 // unique name (an integer), which acts as the SSA name for that definition.
00283 // The total set of names is shared among all CFG basic blocks.
00284 // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
00285 // with their SSA-names.  Instead, we compute a Context for each point in the
00286 // code, which maps local variables to the appropriate SSA-name.  This map
00287 // changes with each assignment.
00288 //
00289 // The map is computed in a single pass over the CFG.  Subsequent analyses can
00290 // then query the map to find the appropriate Context for a statement, and use
00291 // that Context to look up the definitions of variables.
00292 class LocalVariableMap {
00293 public:
00294   typedef LocalVarContext Context;
00295 
00296   /// A VarDefinition consists of an expression, representing the value of the
00297   /// variable, along with the context in which that expression should be
00298   /// interpreted.  A reference VarDefinition does not itself contain this
00299   /// information, but instead contains a pointer to a previous VarDefinition.
00300   struct VarDefinition {
00301   public:
00302     friend class LocalVariableMap;
00303 
00304     const NamedDecl *Dec;  // The original declaration for this variable.
00305     const Expr *Exp;       // The expression for this variable, OR
00306     unsigned Ref;          // Reference to another VarDefinition
00307     Context Ctx;           // The map with which Exp should be interpreted.
00308 
00309     bool isReference() { return !Exp; }
00310 
00311   private:
00312     // Create ordinary variable definition
00313     VarDefinition(const NamedDecl *D, const Expr *E, Context C)
00314       : Dec(D), Exp(E), Ref(0), Ctx(C)
00315     { }
00316 
00317     // Create reference to previous definition
00318     VarDefinition(const NamedDecl *D, unsigned R, Context C)
00319       : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
00320     { }
00321   };
00322 
00323 private:
00324   Context::Factory ContextFactory;
00325   std::vector<VarDefinition> VarDefinitions;
00326   std::vector<unsigned> CtxIndices;
00327   std::vector<std::pair<Stmt*, Context> > SavedContexts;
00328 
00329 public:
00330   LocalVariableMap() {
00331     // index 0 is a placeholder for undefined variables (aka phi-nodes).
00332     VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
00333   }
00334 
00335   /// Look up a definition, within the given context.
00336   const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
00337     const unsigned *i = Ctx.lookup(D);
00338     if (!i)
00339       return nullptr;
00340     assert(*i < VarDefinitions.size());
00341     return &VarDefinitions[*i];
00342   }
00343 
00344   /// Look up the definition for D within the given context.  Returns
00345   /// NULL if the expression is not statically known.  If successful, also
00346   /// modifies Ctx to hold the context of the return Expr.
00347   const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
00348     const unsigned *P = Ctx.lookup(D);
00349     if (!P)
00350       return nullptr;
00351 
00352     unsigned i = *P;
00353     while (i > 0) {
00354       if (VarDefinitions[i].Exp) {
00355         Ctx = VarDefinitions[i].Ctx;
00356         return VarDefinitions[i].Exp;
00357       }
00358       i = VarDefinitions[i].Ref;
00359     }
00360     return nullptr;
00361   }
00362 
00363   Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
00364 
00365   /// Return the next context after processing S.  This function is used by
00366   /// clients of the class to get the appropriate context when traversing the
00367   /// CFG.  It must be called for every assignment or DeclStmt.
00368   Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
00369     if (SavedContexts[CtxIndex+1].first == S) {
00370       CtxIndex++;
00371       Context Result = SavedContexts[CtxIndex].second;
00372       return Result;
00373     }
00374     return C;
00375   }
00376 
00377   void dumpVarDefinitionName(unsigned i) {
00378     if (i == 0) {
00379       llvm::errs() << "Undefined";
00380       return;
00381     }
00382     const NamedDecl *Dec = VarDefinitions[i].Dec;
00383     if (!Dec) {
00384       llvm::errs() << "<<NULL>>";
00385       return;
00386     }
00387     Dec->printName(llvm::errs());
00388     llvm::errs() << "." << i << " " << ((const void*) Dec);
00389   }
00390 
00391   /// Dumps an ASCII representation of the variable map to llvm::errs()
00392   void dump() {
00393     for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
00394       const Expr *Exp = VarDefinitions[i].Exp;
00395       unsigned Ref = VarDefinitions[i].Ref;
00396 
00397       dumpVarDefinitionName(i);
00398       llvm::errs() << " = ";
00399       if (Exp) Exp->dump();
00400       else {
00401         dumpVarDefinitionName(Ref);
00402         llvm::errs() << "\n";
00403       }
00404     }
00405   }
00406 
00407   /// Dumps an ASCII representation of a Context to llvm::errs()
00408   void dumpContext(Context C) {
00409     for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
00410       const NamedDecl *D = I.getKey();
00411       D->printName(llvm::errs());
00412       const unsigned *i = C.lookup(D);
00413       llvm::errs() << " -> ";
00414       dumpVarDefinitionName(*i);
00415       llvm::errs() << "\n";
00416     }
00417   }
00418 
00419   /// Builds the variable map.
00420   void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
00421                    std::vector<CFGBlockInfo> &BlockInfo);
00422 
00423 protected:
00424   // Get the current context index
00425   unsigned getContextIndex() { return SavedContexts.size()-1; }
00426 
00427   // Save the current context for later replay
00428   void saveContext(Stmt *S, Context C) {
00429     SavedContexts.push_back(std::make_pair(S,C));
00430   }
00431 
00432   // Adds a new definition to the given context, and returns a new context.
00433   // This method should be called when declaring a new variable.
00434   Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
00435     assert(!Ctx.contains(D));
00436     unsigned newID = VarDefinitions.size();
00437     Context NewCtx = ContextFactory.add(Ctx, D, newID);
00438     VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
00439     return NewCtx;
00440   }
00441 
00442   // Add a new reference to an existing definition.
00443   Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
00444     unsigned newID = VarDefinitions.size();
00445     Context NewCtx = ContextFactory.add(Ctx, D, newID);
00446     VarDefinitions.push_back(VarDefinition(D, i, Ctx));
00447     return NewCtx;
00448   }
00449 
00450   // Updates a definition only if that definition is already in the map.
00451   // This method should be called when assigning to an existing variable.
00452   Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
00453     if (Ctx.contains(D)) {
00454       unsigned newID = VarDefinitions.size();
00455       Context NewCtx = ContextFactory.remove(Ctx, D);
00456       NewCtx = ContextFactory.add(NewCtx, D, newID);
00457       VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
00458       return NewCtx;
00459     }
00460     return Ctx;
00461   }
00462 
00463   // Removes a definition from the context, but keeps the variable name
00464   // as a valid variable.  The index 0 is a placeholder for cleared definitions.
00465   Context clearDefinition(const NamedDecl *D, Context Ctx) {
00466     Context NewCtx = Ctx;
00467     if (NewCtx.contains(D)) {
00468       NewCtx = ContextFactory.remove(NewCtx, D);
00469       NewCtx = ContextFactory.add(NewCtx, D, 0);
00470     }
00471     return NewCtx;
00472   }
00473 
00474   // Remove a definition entirely frmo the context.
00475   Context removeDefinition(const NamedDecl *D, Context Ctx) {
00476     Context NewCtx = Ctx;
00477     if (NewCtx.contains(D)) {
00478       NewCtx = ContextFactory.remove(NewCtx, D);
00479     }
00480     return NewCtx;
00481   }
00482 
00483   Context intersectContexts(Context C1, Context C2);
00484   Context createReferenceContext(Context C);
00485   void intersectBackEdge(Context C1, Context C2);
00486 
00487   friend class VarMapBuilder;
00488 };
00489 
00490 
00491 // This has to be defined after LocalVariableMap.
00492 CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
00493   return CFGBlockInfo(M.getEmptyContext());
00494 }
00495 
00496 
00497 /// Visitor which builds a LocalVariableMap
00498 class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
00499 public:
00500   LocalVariableMap* VMap;
00501   LocalVariableMap::Context Ctx;
00502 
00503   VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
00504     : VMap(VM), Ctx(C) {}
00505 
00506   void VisitDeclStmt(DeclStmt *S);
00507   void VisitBinaryOperator(BinaryOperator *BO);
00508 };
00509 
00510 
00511 // Add new local variables to the variable map
00512 void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
00513   bool modifiedCtx = false;
00514   DeclGroupRef DGrp = S->getDeclGroup();
00515   for (const auto *D : DGrp) {
00516     if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
00517       const Expr *E = VD->getInit();
00518 
00519       // Add local variables with trivial type to the variable map
00520       QualType T = VD->getType();
00521       if (T.isTrivialType(VD->getASTContext())) {
00522         Ctx = VMap->addDefinition(VD, E, Ctx);
00523         modifiedCtx = true;
00524       }
00525     }
00526   }
00527   if (modifiedCtx)
00528     VMap->saveContext(S, Ctx);
00529 }
00530 
00531 // Update local variable definitions in variable map
00532 void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
00533   if (!BO->isAssignmentOp())
00534     return;
00535 
00536   Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
00537 
00538   // Update the variable map and current context.
00539   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
00540     ValueDecl *VDec = DRE->getDecl();
00541     if (Ctx.lookup(VDec)) {
00542       if (BO->getOpcode() == BO_Assign)
00543         Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
00544       else
00545         // FIXME -- handle compound assignment operators
00546         Ctx = VMap->clearDefinition(VDec, Ctx);
00547       VMap->saveContext(BO, Ctx);
00548     }
00549   }
00550 }
00551 
00552 
00553 // Computes the intersection of two contexts.  The intersection is the
00554 // set of variables which have the same definition in both contexts;
00555 // variables with different definitions are discarded.
00556 LocalVariableMap::Context
00557 LocalVariableMap::intersectContexts(Context C1, Context C2) {
00558   Context Result = C1;
00559   for (const auto &P : C1) {
00560     const NamedDecl *Dec = P.first;
00561     const unsigned *i2 = C2.lookup(Dec);
00562     if (!i2)             // variable doesn't exist on second path
00563       Result = removeDefinition(Dec, Result);
00564     else if (*i2 != P.second)  // variable exists, but has different definition
00565       Result = clearDefinition(Dec, Result);
00566   }
00567   return Result;
00568 }
00569 
00570 // For every variable in C, create a new variable that refers to the
00571 // definition in C.  Return a new context that contains these new variables.
00572 // (We use this for a naive implementation of SSA on loop back-edges.)
00573 LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
00574   Context Result = getEmptyContext();
00575   for (const auto &P : C)
00576     Result = addReference(P.first, P.second, Result);
00577   return Result;
00578 }
00579 
00580 // This routine also takes the intersection of C1 and C2, but it does so by
00581 // altering the VarDefinitions.  C1 must be the result of an earlier call to
00582 // createReferenceContext.
00583 void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
00584   for (const auto &P : C1) {
00585     unsigned i1 = P.second;
00586     VarDefinition *VDef = &VarDefinitions[i1];
00587     assert(VDef->isReference());
00588 
00589     const unsigned *i2 = C2.lookup(P.first);
00590     if (!i2 || (*i2 != i1))
00591       VDef->Ref = 0;    // Mark this variable as undefined
00592   }
00593 }
00594 
00595 
00596 // Traverse the CFG in topological order, so all predecessors of a block
00597 // (excluding back-edges) are visited before the block itself.  At
00598 // each point in the code, we calculate a Context, which holds the set of
00599 // variable definitions which are visible at that point in execution.
00600 // Visible variables are mapped to their definitions using an array that
00601 // contains all definitions.
00602 //
00603 // At join points in the CFG, the set is computed as the intersection of
00604 // the incoming sets along each edge, E.g.
00605 //
00606 //                       { Context                 | VarDefinitions }
00607 //   int x = 0;          { x -> x1                 | x1 = 0 }
00608 //   int y = 0;          { x -> x1, y -> y1        | y1 = 0, x1 = 0 }
00609 //   if (b) x = 1;       { x -> x2, y -> y1        | x2 = 1, y1 = 0, ... }
00610 //   else   x = 2;       { x -> x3, y -> y1        | x3 = 2, x2 = 1, ... }
00611 //   ...                 { y -> y1  (x is unknown) | x3 = 2, x2 = 1, ... }
00612 //
00613 // This is essentially a simpler and more naive version of the standard SSA
00614 // algorithm.  Those definitions that remain in the intersection are from blocks
00615 // that strictly dominate the current block.  We do not bother to insert proper
00616 // phi nodes, because they are not used in our analysis; instead, wherever
00617 // a phi node would be required, we simply remove that definition from the
00618 // context (E.g. x above).
00619 //
00620 // The initial traversal does not capture back-edges, so those need to be
00621 // handled on a separate pass.  Whenever the first pass encounters an
00622 // incoming back edge, it duplicates the context, creating new definitions
00623 // that refer back to the originals.  (These correspond to places where SSA
00624 // might have to insert a phi node.)  On the second pass, these definitions are
00625 // set to NULL if the variable has changed on the back-edge (i.e. a phi
00626 // node was actually required.)  E.g.
00627 //
00628 //                       { Context           | VarDefinitions }
00629 //   int x = 0, y = 0;   { x -> x1, y -> y1  | y1 = 0, x1 = 0 }
00630 //   while (b)           { x -> x2, y -> y1  | [1st:] x2=x1; [2nd:] x2=NULL; }
00631 //     x = x+1;          { x -> x3, y -> y1  | x3 = x2 + 1, ... }
00632 //   ...                 { y -> y1           | x3 = 2, x2 = 1, ... }
00633 //
00634 void LocalVariableMap::traverseCFG(CFG *CFGraph,
00635                                    const PostOrderCFGView *SortedGraph,
00636                                    std::vector<CFGBlockInfo> &BlockInfo) {
00637   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
00638 
00639   CtxIndices.resize(CFGraph->getNumBlockIDs());
00640 
00641   for (const auto *CurrBlock : *SortedGraph) {
00642     int CurrBlockID = CurrBlock->getBlockID();
00643     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
00644 
00645     VisitedBlocks.insert(CurrBlock);
00646 
00647     // Calculate the entry context for the current block
00648     bool HasBackEdges = false;
00649     bool CtxInit = true;
00650     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
00651          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
00652       // if *PI -> CurrBlock is a back edge, so skip it
00653       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
00654         HasBackEdges = true;
00655         continue;
00656       }
00657 
00658       int PrevBlockID = (*PI)->getBlockID();
00659       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
00660 
00661       if (CtxInit) {
00662         CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
00663         CtxInit = false;
00664       }
00665       else {
00666         CurrBlockInfo->EntryContext =
00667           intersectContexts(CurrBlockInfo->EntryContext,
00668                             PrevBlockInfo->ExitContext);
00669       }
00670     }
00671 
00672     // Duplicate the context if we have back-edges, so we can call
00673     // intersectBackEdges later.
00674     if (HasBackEdges)
00675       CurrBlockInfo->EntryContext =
00676         createReferenceContext(CurrBlockInfo->EntryContext);
00677 
00678     // Create a starting context index for the current block
00679     saveContext(nullptr, CurrBlockInfo->EntryContext);
00680     CurrBlockInfo->EntryIndex = getContextIndex();
00681 
00682     // Visit all the statements in the basic block.
00683     VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
00684     for (CFGBlock::const_iterator BI = CurrBlock->begin(),
00685          BE = CurrBlock->end(); BI != BE; ++BI) {
00686       switch (BI->getKind()) {
00687         case CFGElement::Statement: {
00688           CFGStmt CS = BI->castAs<CFGStmt>();
00689           VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
00690           break;
00691         }
00692         default:
00693           break;
00694       }
00695     }
00696     CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
00697 
00698     // Mark variables on back edges as "unknown" if they've been changed.
00699     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
00700          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
00701       // if CurrBlock -> *SI is *not* a back edge
00702       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
00703         continue;
00704 
00705       CFGBlock *FirstLoopBlock = *SI;
00706       Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
00707       Context LoopEnd   = CurrBlockInfo->ExitContext;
00708       intersectBackEdge(LoopBegin, LoopEnd);
00709     }
00710   }
00711 
00712   // Put an extra entry at the end of the indexed context array
00713   unsigned exitID = CFGraph->getExit().getBlockID();
00714   saveContext(nullptr, BlockInfo[exitID].ExitContext);
00715 }
00716 
00717 /// Find the appropriate source locations to use when producing diagnostics for
00718 /// each block in the CFG.
00719 static void findBlockLocations(CFG *CFGraph,
00720                                const PostOrderCFGView *SortedGraph,
00721                                std::vector<CFGBlockInfo> &BlockInfo) {
00722   for (const auto *CurrBlock : *SortedGraph) {
00723     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
00724 
00725     // Find the source location of the last statement in the block, if the
00726     // block is not empty.
00727     if (const Stmt *S = CurrBlock->getTerminator()) {
00728       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
00729     } else {
00730       for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
00731            BE = CurrBlock->rend(); BI != BE; ++BI) {
00732         // FIXME: Handle other CFGElement kinds.
00733         if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
00734           CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
00735           break;
00736         }
00737       }
00738     }
00739 
00740     if (!CurrBlockInfo->ExitLoc.isInvalid()) {
00741       // This block contains at least one statement. Find the source location
00742       // of the first statement in the block.
00743       for (CFGBlock::const_iterator BI = CurrBlock->begin(),
00744            BE = CurrBlock->end(); BI != BE; ++BI) {
00745         // FIXME: Handle other CFGElement kinds.
00746         if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
00747           CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
00748           break;
00749         }
00750       }
00751     } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
00752                CurrBlock != &CFGraph->getExit()) {
00753       // The block is empty, and has a single predecessor. Use its exit
00754       // location.
00755       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
00756           BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
00757     }
00758   }
00759 }
00760 
00761 class LockableFactEntry : public FactEntry {
00762 private:
00763   bool Managed; ///<  managed by ScopedLockable object
00764 
00765 public:
00766   LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
00767                     bool Mng = false, bool Asrt = false)
00768       : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
00769 
00770   void
00771   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
00772                                 SourceLocation JoinLoc, LockErrorKind LEK,
00773                                 ThreadSafetyHandler &Handler) const override {
00774     if (!Managed && !asserted() && !negative() && !isUniversal()) {
00775       Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
00776                                         LEK);
00777     }
00778   }
00779 
00780   void handleUnlock(FactSet &FSet, FactManager &FactMan,
00781                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
00782                     bool FullyRemove, ThreadSafetyHandler &Handler,
00783                     StringRef DiagKind) const override {
00784     FSet.removeLock(FactMan, Cp);
00785     if (!Cp.negative()) {
00786       FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
00787                                 !Cp, LK_Exclusive, UnlockLoc));
00788     }
00789   }
00790 };
00791 
00792 class ScopedLockableFactEntry : public FactEntry {
00793 private:
00794   SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
00795 
00796 public:
00797   ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
00798                           const CapExprSet &Excl, const CapExprSet &Shrd)
00799       : FactEntry(CE, LK_Exclusive, Loc, false) {
00800     for (const auto &M : Excl)
00801       UnderlyingMutexes.push_back(M.sexpr());
00802     for (const auto &M : Shrd)
00803       UnderlyingMutexes.push_back(M.sexpr());
00804   }
00805 
00806   void
00807   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
00808                                 SourceLocation JoinLoc, LockErrorKind LEK,
00809                                 ThreadSafetyHandler &Handler) const override {
00810     for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
00811       if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
00812         // If this scoped lock manages another mutex, and if the underlying
00813         // mutex is still held, then warn about the underlying mutex.
00814         Handler.handleMutexHeldEndOfScope(
00815             "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
00816       }
00817     }
00818   }
00819 
00820   void handleUnlock(FactSet &FSet, FactManager &FactMan,
00821                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
00822                     bool FullyRemove, ThreadSafetyHandler &Handler,
00823                     StringRef DiagKind) const override {
00824     assert(!Cp.negative() && "Managing object cannot be negative.");
00825     for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
00826       CapabilityExpr UnderCp(UnderlyingMutex, false);
00827       auto UnderEntry = llvm::make_unique<LockableFactEntry>(
00828           !UnderCp, LK_Exclusive, UnlockLoc);
00829 
00830       if (FullyRemove) {
00831         // We're destroying the managing object.
00832         // Remove the underlying mutex if it exists; but don't warn.
00833         if (FSet.findLock(FactMan, UnderCp)) {
00834           FSet.removeLock(FactMan, UnderCp);
00835           FSet.addLock(FactMan, std::move(UnderEntry));
00836         }
00837       } else {
00838         // We're releasing the underlying mutex, but not destroying the
00839         // managing object.  Warn on dual release.
00840         if (!FSet.findLock(FactMan, UnderCp)) {
00841           Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
00842                                         UnlockLoc);
00843         }
00844         FSet.removeLock(FactMan, UnderCp);
00845         FSet.addLock(FactMan, std::move(UnderEntry));
00846       }
00847     }
00848     if (FullyRemove)
00849       FSet.removeLock(FactMan, Cp);
00850   }
00851 };
00852 
00853 /// \brief Class which implements the core thread safety analysis routines.
00854 class ThreadSafetyAnalyzer {
00855   friend class BuildLockset;
00856 
00857   llvm::BumpPtrAllocator Bpa;
00858   threadSafety::til::MemRegionRef Arena;
00859   threadSafety::SExprBuilder SxBuilder;
00860 
00861   ThreadSafetyHandler       &Handler;
00862   const CXXMethodDecl       *CurrentMethod;
00863   LocalVariableMap          LocalVarMap;
00864   FactManager               FactMan;
00865   std::vector<CFGBlockInfo> BlockInfo;
00866 
00867 public:
00868   ThreadSafetyAnalyzer(ThreadSafetyHandler &H)
00869      : Arena(&Bpa), SxBuilder(Arena), Handler(H) {}
00870 
00871   bool inCurrentScope(const CapabilityExpr &CapE);
00872 
00873   void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
00874                StringRef DiagKind, bool ReqAttr = false);
00875   void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
00876                   SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
00877                   StringRef DiagKind);
00878 
00879   template <typename AttrType>
00880   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
00881                    const NamedDecl *D, VarDecl *SelfDecl = nullptr);
00882 
00883   template <class AttrType>
00884   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
00885                    const NamedDecl *D,
00886                    const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
00887                    Expr *BrE, bool Neg);
00888 
00889   const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
00890                                      bool &Negate);
00891 
00892   void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
00893                       const CFGBlock* PredBlock,
00894                       const CFGBlock *CurrBlock);
00895 
00896   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
00897                         SourceLocation JoinLoc,
00898                         LockErrorKind LEK1, LockErrorKind LEK2,
00899                         bool Modify=true);
00900 
00901   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
00902                         SourceLocation JoinLoc, LockErrorKind LEK1,
00903                         bool Modify=true) {
00904     intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
00905   }
00906 
00907   void runAnalysis(AnalysisDeclContext &AC);
00908 };
00909 
00910 /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
00911 static const ValueDecl *getValueDecl(const Expr *Exp) {
00912   if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
00913     return getValueDecl(CE->getSubExpr());
00914 
00915   if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
00916     return DR->getDecl();
00917 
00918   if (const auto *ME = dyn_cast<MemberExpr>(Exp))
00919     return ME->getMemberDecl();
00920 
00921   return nullptr;
00922 }
00923 
00924 template <typename Ty>
00925 class has_arg_iterator_range {
00926   typedef char yes[1];
00927   typedef char no[2];
00928 
00929   template <typename Inner>
00930   static yes& test(Inner *I, decltype(I->args()) * = nullptr);
00931 
00932   template <typename>
00933   static no& test(...);
00934 
00935 public:
00936   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
00937 };
00938 
00939 static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
00940   return A->getName();
00941 }
00942 
00943 static StringRef ClassifyDiagnostic(QualType VDT) {
00944   // We need to look at the declaration of the type of the value to determine
00945   // which it is. The type should either be a record or a typedef, or a pointer
00946   // or reference thereof.
00947   if (const auto *RT = VDT->getAs<RecordType>()) {
00948     if (const auto *RD = RT->getDecl())
00949       if (const auto *CA = RD->getAttr<CapabilityAttr>())
00950         return ClassifyDiagnostic(CA);
00951   } else if (const auto *TT = VDT->getAs<TypedefType>()) {
00952     if (const auto *TD = TT->getDecl())
00953       if (const auto *CA = TD->getAttr<CapabilityAttr>())
00954         return ClassifyDiagnostic(CA);
00955   } else if (VDT->isPointerType() || VDT->isReferenceType())
00956     return ClassifyDiagnostic(VDT->getPointeeType());
00957 
00958   return "mutex";
00959 }
00960 
00961 static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
00962   assert(VD && "No ValueDecl passed");
00963 
00964   // The ValueDecl is the declaration of a mutex or role (hopefully).
00965   return ClassifyDiagnostic(VD->getType());
00966 }
00967 
00968 template <typename AttrTy>
00969 static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
00970                                StringRef>::type
00971 ClassifyDiagnostic(const AttrTy *A) {
00972   if (const ValueDecl *VD = getValueDecl(A->getArg()))
00973     return ClassifyDiagnostic(VD);
00974   return "mutex";
00975 }
00976 
00977 template <typename AttrTy>
00978 static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
00979                                StringRef>::type
00980 ClassifyDiagnostic(const AttrTy *A) {
00981   for (const auto *Arg : A->args()) {
00982     if (const ValueDecl *VD = getValueDecl(Arg))
00983       return ClassifyDiagnostic(VD);
00984   }
00985   return "mutex";
00986 }
00987 
00988 
00989 inline bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
00990   if (!CurrentMethod)
00991       return false;
00992   if (auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
00993     auto *VD = P->clangDecl();
00994     if (VD)
00995       return VD->getDeclContext() == CurrentMethod->getDeclContext();
00996   }
00997   return false;
00998 }
00999 
01000 
01001 /// \brief Add a new lock to the lockset, warning if the lock is already there.
01002 /// \param ReqAttr -- true if this is part of an initial Requires attribute.
01003 void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
01004                                    std::unique_ptr<FactEntry> Entry,
01005                                    StringRef DiagKind, bool ReqAttr) {
01006   if (Entry->shouldIgnore())
01007     return;
01008 
01009   if (!ReqAttr && !Entry->negative()) {
01010     // look for the negative capability, and remove it from the fact set.
01011     CapabilityExpr NegC = !*Entry;
01012     FactEntry *Nen = FSet.findLock(FactMan, NegC);
01013     if (Nen) {
01014       FSet.removeLock(FactMan, NegC);
01015     }
01016     else {
01017       if (inCurrentScope(*Entry) && !Entry->asserted())
01018         Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
01019                                       NegC.toString(), Entry->loc());
01020     }
01021   }
01022 
01023   // FIXME: deal with acquired before/after annotations.
01024   // FIXME: Don't always warn when we have support for reentrant locks.
01025   if (FSet.findLock(FactMan, *Entry)) {
01026     if (!Entry->asserted())
01027       Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
01028   } else {
01029     FSet.addLock(FactMan, std::move(Entry));
01030   }
01031 }
01032 
01033 
01034 /// \brief Remove a lock from the lockset, warning if the lock is not there.
01035 /// \param UnlockLoc The source location of the unlock (only used in error msg)
01036 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
01037                                       SourceLocation UnlockLoc,
01038                                       bool FullyRemove, LockKind ReceivedKind,
01039                                       StringRef DiagKind) {
01040   if (Cp.shouldIgnore())
01041     return;
01042 
01043   const FactEntry *LDat = FSet.findLock(FactMan, Cp);
01044   if (!LDat) {
01045     Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
01046     return;
01047   }
01048 
01049   // Generic lock removal doesn't care about lock kind mismatches, but
01050   // otherwise diagnose when the lock kinds are mismatched.
01051   if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
01052     Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
01053                                       LDat->kind(), ReceivedKind, UnlockLoc);
01054   }
01055 
01056   LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
01057                      DiagKind);
01058 }
01059 
01060 
01061 /// \brief Extract the list of mutexIDs from the attribute on an expression,
01062 /// and push them onto Mtxs, discarding any duplicates.
01063 template <typename AttrType>
01064 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
01065                                        Expr *Exp, const NamedDecl *D,
01066                                        VarDecl *SelfDecl) {
01067   if (Attr->args_size() == 0) {
01068     // The mutex held is the "this" object.
01069     CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
01070     if (Cp.isInvalid()) {
01071        warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
01072        return;
01073     }
01074     //else
01075     if (!Cp.shouldIgnore())
01076       Mtxs.push_back_nodup(Cp);
01077     return;
01078   }
01079 
01080   for (const auto *Arg : Attr->args()) {
01081     CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
01082     if (Cp.isInvalid()) {
01083        warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
01084        continue;
01085     }
01086     //else
01087     if (!Cp.shouldIgnore())
01088       Mtxs.push_back_nodup(Cp);
01089   }
01090 }
01091 
01092 
01093 /// \brief Extract the list of mutexIDs from a trylock attribute.  If the
01094 /// trylock applies to the given edge, then push them onto Mtxs, discarding
01095 /// any duplicates.
01096 template <class AttrType>
01097 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
01098                                        Expr *Exp, const NamedDecl *D,
01099                                        const CFGBlock *PredBlock,
01100                                        const CFGBlock *CurrBlock,
01101                                        Expr *BrE, bool Neg) {
01102   // Find out which branch has the lock
01103   bool branch = false;
01104   if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
01105     branch = BLE->getValue();
01106   else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
01107     branch = ILE->getValue().getBoolValue();
01108 
01109   int branchnum = branch ? 0 : 1;
01110   if (Neg)
01111     branchnum = !branchnum;
01112 
01113   // If we've taken the trylock branch, then add the lock
01114   int i = 0;
01115   for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
01116        SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
01117     if (*SI == CurrBlock && i == branchnum)
01118       getMutexIDs(Mtxs, Attr, Exp, D);
01119   }
01120 }
01121 
01122 
01123 bool getStaticBooleanValue(Expr* E, bool& TCond) {
01124   if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
01125     TCond = false;
01126     return true;
01127   } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
01128     TCond = BLE->getValue();
01129     return true;
01130   } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
01131     TCond = ILE->getValue().getBoolValue();
01132     return true;
01133   } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
01134     return getStaticBooleanValue(CE->getSubExpr(), TCond);
01135   }
01136   return false;
01137 }
01138 
01139 
01140 // If Cond can be traced back to a function call, return the call expression.
01141 // The negate variable should be called with false, and will be set to true
01142 // if the function call is negated, e.g. if (!mu.tryLock(...))
01143 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
01144                                                          LocalVarContext C,
01145                                                          bool &Negate) {
01146   if (!Cond)
01147     return nullptr;
01148 
01149   if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
01150     return CallExp;
01151   }
01152   else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
01153     return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
01154   }
01155   else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
01156     return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
01157   }
01158   else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
01159     return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
01160   }
01161   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
01162     const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
01163     return getTrylockCallExpr(E, C, Negate);
01164   }
01165   else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
01166     if (UOP->getOpcode() == UO_LNot) {
01167       Negate = !Negate;
01168       return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
01169     }
01170     return nullptr;
01171   }
01172   else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
01173     if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
01174       if (BOP->getOpcode() == BO_NE)
01175         Negate = !Negate;
01176 
01177       bool TCond = false;
01178       if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
01179         if (!TCond) Negate = !Negate;
01180         return getTrylockCallExpr(BOP->getLHS(), C, Negate);
01181       }
01182       TCond = false;
01183       if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
01184         if (!TCond) Negate = !Negate;
01185         return getTrylockCallExpr(BOP->getRHS(), C, Negate);
01186       }
01187       return nullptr;
01188     }
01189     if (BOP->getOpcode() == BO_LAnd) {
01190       // LHS must have been evaluated in a different block.
01191       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
01192     }
01193     if (BOP->getOpcode() == BO_LOr) {
01194       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
01195     }
01196     return nullptr;
01197   }
01198   return nullptr;
01199 }
01200 
01201 
01202 /// \brief Find the lockset that holds on the edge between PredBlock
01203 /// and CurrBlock.  The edge set is the exit set of PredBlock (passed
01204 /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
01205 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
01206                                           const FactSet &ExitSet,
01207                                           const CFGBlock *PredBlock,
01208                                           const CFGBlock *CurrBlock) {
01209   Result = ExitSet;
01210 
01211   const Stmt *Cond = PredBlock->getTerminatorCondition();
01212   if (!Cond)
01213     return;
01214 
01215   bool Negate = false;
01216   const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
01217   const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
01218   StringRef CapDiagKind = "mutex";
01219 
01220   CallExpr *Exp =
01221     const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
01222   if (!Exp)
01223     return;
01224 
01225   NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
01226   if(!FunDecl || !FunDecl->hasAttrs())
01227     return;
01228 
01229   CapExprSet ExclusiveLocksToAdd;
01230   CapExprSet SharedLocksToAdd;
01231 
01232   // If the condition is a call to a Trylock function, then grab the attributes
01233   for (auto *Attr : FunDecl->getAttrs()) {
01234     switch (Attr->getKind()) {
01235       case attr::ExclusiveTrylockFunction: {
01236         ExclusiveTrylockFunctionAttr *A =
01237           cast<ExclusiveTrylockFunctionAttr>(Attr);
01238         getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
01239                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
01240         CapDiagKind = ClassifyDiagnostic(A);
01241         break;
01242       }
01243       case attr::SharedTrylockFunction: {
01244         SharedTrylockFunctionAttr *A =
01245           cast<SharedTrylockFunctionAttr>(Attr);
01246         getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
01247                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
01248         CapDiagKind = ClassifyDiagnostic(A);
01249         break;
01250       }
01251       default:
01252         break;
01253     }
01254   }
01255 
01256   // Add and remove locks.
01257   SourceLocation Loc = Exp->getExprLoc();
01258   for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
01259     addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
01260                                                          LK_Exclusive, Loc),
01261             CapDiagKind);
01262   for (const auto &SharedLockToAdd : SharedLocksToAdd)
01263     addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
01264                                                          LK_Shared, Loc),
01265             CapDiagKind);
01266 }
01267 
01268 /// \brief We use this class to visit different types of expressions in
01269 /// CFGBlocks, and build up the lockset.
01270 /// An expression may cause us to add or remove locks from the lockset, or else
01271 /// output error messages related to missing locks.
01272 /// FIXME: In future, we may be able to not inherit from a visitor.
01273 class BuildLockset : public StmtVisitor<BuildLockset> {
01274   friend class ThreadSafetyAnalyzer;
01275 
01276   ThreadSafetyAnalyzer *Analyzer;
01277   FactSet FSet;
01278   LocalVariableMap::Context LVarCtx;
01279   unsigned CtxIndex;
01280 
01281   // helper functions
01282   void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
01283                           Expr *MutexExp, ProtectedOperationKind POK,
01284                           StringRef DiagKind, SourceLocation Loc);
01285   void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
01286                        StringRef DiagKind);
01287 
01288   void checkAccess(const Expr *Exp, AccessKind AK,
01289                    ProtectedOperationKind POK = POK_VarAccess);
01290   void checkPtAccess(const Expr *Exp, AccessKind AK,
01291                      ProtectedOperationKind POK = POK_VarAccess);
01292 
01293   void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
01294 
01295 public:
01296   BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
01297     : StmtVisitor<BuildLockset>(),
01298       Analyzer(Anlzr),
01299       FSet(Info.EntrySet),
01300       LVarCtx(Info.EntryContext),
01301       CtxIndex(Info.EntryIndex)
01302   {}
01303 
01304   void VisitUnaryOperator(UnaryOperator *UO);
01305   void VisitBinaryOperator(BinaryOperator *BO);
01306   void VisitCastExpr(CastExpr *CE);
01307   void VisitCallExpr(CallExpr *Exp);
01308   void VisitCXXConstructExpr(CXXConstructExpr *Exp);
01309   void VisitDeclStmt(DeclStmt *S);
01310 };
01311 
01312 
01313 /// \brief Warn if the LSet does not contain a lock sufficient to protect access
01314 /// of at least the passed in AccessKind.
01315 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
01316                                       AccessKind AK, Expr *MutexExp,
01317                                       ProtectedOperationKind POK,
01318                                       StringRef DiagKind, SourceLocation Loc) {
01319   LockKind LK = getLockKindFromAccessKind(AK);
01320 
01321   CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
01322   if (Cp.isInvalid()) {
01323     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
01324     return;
01325   } else if (Cp.shouldIgnore()) {
01326     return;
01327   }
01328 
01329   if (Cp.negative()) {
01330     // Negative capabilities act like locks excluded
01331     FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
01332     if (LDat) {
01333       Analyzer->Handler.handleFunExcludesLock(
01334           DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
01335       return;
01336     }
01337 
01338     // If this does not refer to a negative capability in the same class,
01339     // then stop here.
01340     if (!Analyzer->inCurrentScope(Cp))
01341       return;
01342 
01343     // Otherwise the negative requirement must be propagated to the caller.
01344     LDat = FSet.findLock(Analyzer->FactMan, Cp);
01345     if (!LDat) {
01346       Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
01347                                            LK_Shared, Loc);
01348     }
01349     return;
01350   }
01351 
01352   FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
01353   bool NoError = true;
01354   if (!LDat) {
01355     // No exact match found.  Look for a partial match.
01356     LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
01357     if (LDat) {
01358       // Warn that there's no precise match.
01359       std::string PartMatchStr = LDat->toString();
01360       StringRef   PartMatchName(PartMatchStr);
01361       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
01362                                            LK, Loc, &PartMatchName);
01363     } else {
01364       // Warn that there's no match at all.
01365       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
01366                                            LK, Loc);
01367     }
01368     NoError = false;
01369   }
01370   // Make sure the mutex we found is the right kind.
01371   if (NoError && LDat && !LDat->isAtLeast(LK)) {
01372     Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
01373                                          LK, Loc);
01374   }
01375 }
01376 
01377 /// \brief Warn if the LSet contains the given lock.
01378 void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
01379                                    Expr *MutexExp, StringRef DiagKind) {
01380   CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
01381   if (Cp.isInvalid()) {
01382     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
01383     return;
01384   } else if (Cp.shouldIgnore()) {
01385     return;
01386   }
01387 
01388   FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
01389   if (LDat) {
01390     Analyzer->Handler.handleFunExcludesLock(
01391         DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
01392   }
01393 }
01394 
01395 /// \brief Checks guarded_by and pt_guarded_by attributes.
01396 /// Whenever we identify an access (read or write) to a DeclRefExpr that is
01397 /// marked with guarded_by, we must ensure the appropriate mutexes are held.
01398 /// Similarly, we check if the access is to an expression that dereferences
01399 /// a pointer marked with pt_guarded_by.
01400 void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
01401                                ProtectedOperationKind POK) {
01402   Exp = Exp->IgnoreParenCasts();
01403 
01404   SourceLocation Loc = Exp->getExprLoc();
01405 
01406   // Local variables of reference type cannot be re-assigned;
01407   // map them to their initializer.
01408   while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
01409     const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
01410     if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
01411       if (const auto *E = VD->getInit()) {
01412         Exp = E;
01413         continue;
01414       }
01415     }
01416     break;
01417   }
01418 
01419   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
01420     // For dereferences
01421     if (UO->getOpcode() == clang::UO_Deref)
01422       checkPtAccess(UO->getSubExpr(), AK, POK);
01423     return;
01424   }
01425 
01426   if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
01427     checkPtAccess(AE->getLHS(), AK, POK);
01428     return;
01429   }
01430 
01431   if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
01432     if (ME->isArrow())
01433       checkPtAccess(ME->getBase(), AK, POK);
01434     else
01435       checkAccess(ME->getBase(), AK, POK);
01436   }
01437 
01438   const ValueDecl *D = getValueDecl(Exp);
01439   if (!D || !D->hasAttrs())
01440     return;
01441 
01442   if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
01443     Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
01444   }
01445 
01446   for (const auto *I : D->specific_attrs<GuardedByAttr>())
01447     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
01448                        ClassifyDiagnostic(I), Loc);
01449 }
01450 
01451 
01452 /// \brief Checks pt_guarded_by and pt_guarded_var attributes.
01453 /// POK is the same  operationKind that was passed to checkAccess.
01454 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
01455                                  ProtectedOperationKind POK) {
01456   while (true) {
01457     if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
01458       Exp = PE->getSubExpr();
01459       continue;
01460     }
01461     if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
01462       if (CE->getCastKind() == CK_ArrayToPointerDecay) {
01463         // If it's an actual array, and not a pointer, then it's elements
01464         // are protected by GUARDED_BY, not PT_GUARDED_BY;
01465         checkAccess(CE->getSubExpr(), AK, POK);
01466         return;
01467       }
01468       Exp = CE->getSubExpr();
01469       continue;
01470     }
01471     break;
01472   }
01473 
01474   // Pass by reference warnings are under a different flag.
01475   ProtectedOperationKind PtPOK = POK_VarDereference;
01476   if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
01477 
01478   const ValueDecl *D = getValueDecl(Exp);
01479   if (!D || !D->hasAttrs())
01480     return;
01481 
01482   if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
01483     Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
01484                                         Exp->getExprLoc());
01485 
01486   for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
01487     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
01488                        ClassifyDiagnostic(I), Exp->getExprLoc());
01489 }
01490 
01491 /// \brief Process a function call, method call, constructor call,
01492 /// or destructor call.  This involves looking at the attributes on the
01493 /// corresponding function/method/constructor/destructor, issuing warnings,
01494 /// and updating the locksets accordingly.
01495 ///
01496 /// FIXME: For classes annotated with one of the guarded annotations, we need
01497 /// to treat const method calls as reads and non-const method calls as writes,
01498 /// and check that the appropriate locks are held. Non-const method calls with
01499 /// the same signature as const method calls can be also treated as reads.
01500 ///
01501 void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
01502   SourceLocation Loc = Exp->getExprLoc();
01503   const AttrVec &ArgAttrs = D->getAttrs();
01504   CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
01505   CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
01506   StringRef CapDiagKind = "mutex";
01507 
01508   for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
01509     Attr *At = const_cast<Attr*>(ArgAttrs[i]);
01510     switch (At->getKind()) {
01511       // When we encounter a lock function, we need to add the lock to our
01512       // lockset.
01513       case attr::AcquireCapability: {
01514         auto *A = cast<AcquireCapabilityAttr>(At);
01515         Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
01516                                             : ExclusiveLocksToAdd,
01517                               A, Exp, D, VD);
01518 
01519         CapDiagKind = ClassifyDiagnostic(A);
01520         break;
01521       }
01522 
01523       // An assert will add a lock to the lockset, but will not generate
01524       // a warning if it is already there, and will not generate a warning
01525       // if it is not removed.
01526       case attr::AssertExclusiveLock: {
01527         AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
01528 
01529         CapExprSet AssertLocks;
01530         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
01531         for (const auto &AssertLock : AssertLocks)
01532           Analyzer->addLock(FSet,
01533                             llvm::make_unique<LockableFactEntry>(
01534                                 AssertLock, LK_Exclusive, Loc, false, true),
01535                             ClassifyDiagnostic(A));
01536         break;
01537       }
01538       case attr::AssertSharedLock: {
01539         AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
01540 
01541         CapExprSet AssertLocks;
01542         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
01543         for (const auto &AssertLock : AssertLocks)
01544           Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
01545                                       AssertLock, LK_Shared, Loc, false, true),
01546                             ClassifyDiagnostic(A));
01547         break;
01548       }
01549 
01550       // When we encounter an unlock function, we need to remove unlocked
01551       // mutexes from the lockset, and flag a warning if they are not there.
01552       case attr::ReleaseCapability: {
01553         auto *A = cast<ReleaseCapabilityAttr>(At);
01554         if (A->isGeneric())
01555           Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
01556         else if (A->isShared())
01557           Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
01558         else
01559           Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
01560 
01561         CapDiagKind = ClassifyDiagnostic(A);
01562         break;
01563       }
01564 
01565       case attr::RequiresCapability: {
01566         RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
01567         for (auto *Arg : A->args())
01568           warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
01569                              POK_FunctionCall, ClassifyDiagnostic(A),
01570                              Exp->getExprLoc());
01571         break;
01572       }
01573 
01574       case attr::LocksExcluded: {
01575         LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
01576         for (auto *Arg : A->args())
01577           warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
01578         break;
01579       }
01580 
01581       // Ignore attributes unrelated to thread-safety
01582       default:
01583         break;
01584     }
01585   }
01586 
01587   // Figure out if we're calling the constructor of scoped lockable class
01588   bool isScopedVar = false;
01589   if (VD) {
01590     if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
01591       const CXXRecordDecl* PD = CD->getParent();
01592       if (PD && PD->hasAttr<ScopedLockableAttr>())
01593         isScopedVar = true;
01594     }
01595   }
01596 
01597   // Add locks.
01598   for (const auto &M : ExclusiveLocksToAdd)
01599     Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
01600                                 M, LK_Exclusive, Loc, isScopedVar),
01601                       CapDiagKind);
01602   for (const auto &M : SharedLocksToAdd)
01603     Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
01604                                 M, LK_Shared, Loc, isScopedVar),
01605                       CapDiagKind);
01606 
01607   if (isScopedVar) {
01608     // Add the managing object as a dummy mutex, mapped to the underlying mutex.
01609     SourceLocation MLoc = VD->getLocation();
01610     DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
01611     // FIXME: does this store a pointer to DRE?
01612     CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
01613 
01614     CapExprSet UnderlyingMutexes(ExclusiveLocksToAdd);
01615     std::copy(SharedLocksToAdd.begin(), SharedLocksToAdd.end(),
01616               std::back_inserter(UnderlyingMutexes));
01617     Analyzer->addLock(FSet,
01618                       llvm::make_unique<ScopedLockableFactEntry>(
01619                           Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
01620                       CapDiagKind);
01621   }
01622 
01623   // Remove locks.
01624   // FIXME -- should only fully remove if the attribute refers to 'this'.
01625   bool Dtor = isa<CXXDestructorDecl>(D);
01626   for (const auto &M : ExclusiveLocksToRemove)
01627     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
01628   for (const auto &M : SharedLocksToRemove)
01629     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
01630   for (const auto &M : GenericLocksToRemove)
01631     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
01632 }
01633 
01634 
01635 /// \brief For unary operations which read and write a variable, we need to
01636 /// check whether we hold any required mutexes. Reads are checked in
01637 /// VisitCastExpr.
01638 void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
01639   switch (UO->getOpcode()) {
01640     case clang::UO_PostDec:
01641     case clang::UO_PostInc:
01642     case clang::UO_PreDec:
01643     case clang::UO_PreInc: {
01644       checkAccess(UO->getSubExpr(), AK_Written);
01645       break;
01646     }
01647     default:
01648       break;
01649   }
01650 }
01651 
01652 /// For binary operations which assign to a variable (writes), we need to check
01653 /// whether we hold any required mutexes.
01654 /// FIXME: Deal with non-primitive types.
01655 void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
01656   if (!BO->isAssignmentOp())
01657     return;
01658 
01659   // adjust the context
01660   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
01661 
01662   checkAccess(BO->getLHS(), AK_Written);
01663 }
01664 
01665 
01666 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
01667 /// need to ensure we hold any required mutexes.
01668 /// FIXME: Deal with non-primitive types.
01669 void BuildLockset::VisitCastExpr(CastExpr *CE) {
01670   if (CE->getCastKind() != CK_LValueToRValue)
01671     return;
01672   checkAccess(CE->getSubExpr(), AK_Read);
01673 }
01674 
01675 
01676 void BuildLockset::VisitCallExpr(CallExpr *Exp) {
01677   bool ExamineArgs = true;
01678   bool OperatorFun = false;
01679 
01680   if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
01681     MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
01682     // ME can be null when calling a method pointer
01683     CXXMethodDecl *MD = CE->getMethodDecl();
01684 
01685     if (ME && MD) {
01686       if (ME->isArrow()) {
01687         if (MD->isConst()) {
01688           checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
01689         } else {  // FIXME -- should be AK_Written
01690           checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
01691         }
01692       } else {
01693         if (MD->isConst())
01694           checkAccess(CE->getImplicitObjectArgument(), AK_Read);
01695         else     // FIXME -- should be AK_Written
01696           checkAccess(CE->getImplicitObjectArgument(), AK_Read);
01697       }
01698     }
01699   } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
01700     OperatorFun = true;
01701 
01702     auto OEop = OE->getOperator();
01703     switch (OEop) {
01704       case OO_Equal: {
01705         ExamineArgs = false;
01706         const Expr *Target = OE->getArg(0);
01707         const Expr *Source = OE->getArg(1);
01708         checkAccess(Target, AK_Written);
01709         checkAccess(Source, AK_Read);
01710         break;
01711       }
01712       case OO_Star:
01713       case OO_Arrow:
01714       case OO_Subscript: {
01715         const Expr *Obj = OE->getArg(0);
01716         checkAccess(Obj, AK_Read);
01717         if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
01718           // Grrr.  operator* can be multiplication...
01719           checkPtAccess(Obj, AK_Read);
01720         }
01721         break;
01722       }
01723       default: {
01724         // TODO: get rid of this, and rely on pass-by-ref instead.
01725         const Expr *Obj = OE->getArg(0);
01726         checkAccess(Obj, AK_Read);
01727         break;
01728       }
01729     }
01730   }
01731 
01732 
01733   if (ExamineArgs) {
01734     if (FunctionDecl *FD = Exp->getDirectCallee()) {
01735       unsigned Fn = FD->getNumParams();
01736       unsigned Cn = Exp->getNumArgs();
01737       unsigned Skip = 0;
01738 
01739       unsigned i = 0;
01740       if (OperatorFun) {
01741         if (isa<CXXMethodDecl>(FD)) {
01742           // First arg in operator call is implicit self argument,
01743           // and doesn't appear in the FunctionDecl.
01744           Skip = 1;
01745           Cn--;
01746         } else {
01747           // Ignore the first argument of operators; it's been checked above.
01748           i = 1;
01749         }
01750       }
01751       // Ignore default arguments
01752       unsigned n = (Fn < Cn) ? Fn : Cn;
01753 
01754       for (; i < n; ++i) {
01755         ParmVarDecl* Pvd = FD->getParamDecl(i);
01756         Expr* Arg = Exp->getArg(i+Skip);
01757         QualType Qt = Pvd->getType();
01758         if (Qt->isReferenceType())
01759           checkAccess(Arg, AK_Read, POK_PassByRef);
01760       }
01761     }
01762   }
01763 
01764   NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
01765   if(!D || !D->hasAttrs())
01766     return;
01767   handleCall(Exp, D);
01768 }
01769 
01770 void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
01771   const CXXConstructorDecl *D = Exp->getConstructor();
01772   if (D && D->isCopyConstructor()) {
01773     const Expr* Source = Exp->getArg(0);
01774     checkAccess(Source, AK_Read);
01775   }
01776   // FIXME -- only handles constructors in DeclStmt below.
01777 }
01778 
01779 void BuildLockset::VisitDeclStmt(DeclStmt *S) {
01780   // adjust the context
01781   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
01782 
01783   for (auto *D : S->getDeclGroup()) {
01784     if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
01785       Expr *E = VD->getInit();
01786       // handle constructors that involve temporaries
01787       if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
01788         E = EWC->getSubExpr();
01789 
01790       if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
01791         NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
01792         if (!CtorD || !CtorD->hasAttrs())
01793           return;
01794         handleCall(CE, CtorD, VD);
01795       }
01796     }
01797   }
01798 }
01799 
01800 
01801 
01802 /// \brief Compute the intersection of two locksets and issue warnings for any
01803 /// locks in the symmetric difference.
01804 ///
01805 /// This function is used at a merge point in the CFG when comparing the lockset
01806 /// of each branch being merged. For example, given the following sequence:
01807 /// A; if () then B; else C; D; we need to check that the lockset after B and C
01808 /// are the same. In the event of a difference, we use the intersection of these
01809 /// two locksets at the start of D.
01810 ///
01811 /// \param FSet1 The first lockset.
01812 /// \param FSet2 The second lockset.
01813 /// \param JoinLoc The location of the join point for error reporting
01814 /// \param LEK1 The error message to report if a mutex is missing from LSet1
01815 /// \param LEK2 The error message to report if a mutex is missing from Lset2
01816 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
01817                                             const FactSet &FSet2,
01818                                             SourceLocation JoinLoc,
01819                                             LockErrorKind LEK1,
01820                                             LockErrorKind LEK2,
01821                                             bool Modify) {
01822   FactSet FSet1Orig = FSet1;
01823 
01824   // Find locks in FSet2 that conflict or are not in FSet1, and warn.
01825   for (const auto &Fact : FSet2) {
01826     const FactEntry *LDat1 = nullptr;
01827     const FactEntry *LDat2 = &FactMan[Fact];
01828     FactSet::iterator Iter1  = FSet1.findLockIter(FactMan, *LDat2);
01829     if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
01830 
01831     if (LDat1) {
01832       if (LDat1->kind() != LDat2->kind()) {
01833         Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
01834                                          LDat2->loc(), LDat1->loc());
01835         if (Modify && LDat1->kind() != LK_Exclusive) {
01836           // Take the exclusive lock, which is the one in FSet2.
01837           *Iter1 = Fact;
01838         }
01839       }
01840       else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
01841         // The non-asserted lock in FSet2 is the one we want to track.
01842         *Iter1 = Fact;
01843       }
01844     } else {
01845       LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
01846                                            Handler);
01847     }
01848   }
01849 
01850   // Find locks in FSet1 that are not in FSet2, and remove them.
01851   for (const auto &Fact : FSet1Orig) {
01852     const FactEntry *LDat1 = &FactMan[Fact];
01853     const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
01854 
01855     if (!LDat2) {
01856       LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
01857                                            Handler);
01858       if (Modify)
01859         FSet1.removeLock(FactMan, *LDat1);
01860     }
01861   }
01862 }
01863 
01864 
01865 // Return true if block B never continues to its successors.
01866 inline bool neverReturns(const CFGBlock* B) {
01867   if (B->hasNoReturnElement())
01868     return true;
01869   if (B->empty())
01870     return false;
01871 
01872   CFGElement Last = B->back();
01873   if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
01874     if (isa<CXXThrowExpr>(S->getStmt()))
01875       return true;
01876   }
01877   return false;
01878 }
01879 
01880 
01881 /// \brief Check a function's CFG for thread-safety violations.
01882 ///
01883 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
01884 /// at the end of each block, and issue warnings for thread safety violations.
01885 /// Each block in the CFG is traversed exactly once.
01886 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
01887   // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
01888   // For now, we just use the walker to set things up.
01889   threadSafety::CFGWalker walker;
01890   if (!walker.init(AC))
01891     return;
01892 
01893   // AC.dumpCFG(true);
01894   // threadSafety::printSCFG(walker);
01895 
01896   CFG *CFGraph = walker.getGraph();
01897   const NamedDecl *D = walker.getDecl();
01898   const FunctionDecl *CurrentFunction = dyn_cast<FunctionDecl>(D);
01899   CurrentMethod = dyn_cast<CXXMethodDecl>(D);
01900 
01901   if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
01902     return;
01903 
01904   // FIXME: Do something a bit more intelligent inside constructor and
01905   // destructor code.  Constructors and destructors must assume unique access
01906   // to 'this', so checks on member variable access is disabled, but we should
01907   // still enable checks on other objects.
01908   if (isa<CXXConstructorDecl>(D))
01909     return;  // Don't check inside constructors.
01910   if (isa<CXXDestructorDecl>(D))
01911     return;  // Don't check inside destructors.
01912 
01913   Handler.enterFunction(CurrentFunction);
01914 
01915   BlockInfo.resize(CFGraph->getNumBlockIDs(),
01916     CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
01917 
01918   // We need to explore the CFG via a "topological" ordering.
01919   // That way, we will be guaranteed to have information about required
01920   // predecessor locksets when exploring a new block.
01921   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
01922   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
01923 
01924   // Mark entry block as reachable
01925   BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
01926 
01927   // Compute SSA names for local variables
01928   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
01929 
01930   // Fill in source locations for all CFGBlocks.
01931   findBlockLocations(CFGraph, SortedGraph, BlockInfo);
01932 
01933   CapExprSet ExclusiveLocksAcquired;
01934   CapExprSet SharedLocksAcquired;
01935   CapExprSet LocksReleased;
01936 
01937   // Add locks from exclusive_locks_required and shared_locks_required
01938   // to initial lockset. Also turn off checking for lock and unlock functions.
01939   // FIXME: is there a more intelligent way to check lock/unlock functions?
01940   if (!SortedGraph->empty() && D->hasAttrs()) {
01941     const CFGBlock *FirstBlock = *SortedGraph->begin();
01942     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
01943     const AttrVec &ArgAttrs = D->getAttrs();
01944 
01945     CapExprSet ExclusiveLocksToAdd;
01946     CapExprSet SharedLocksToAdd;
01947     StringRef CapDiagKind = "mutex";
01948 
01949     SourceLocation Loc = D->getLocation();
01950     for (const auto *Attr : ArgAttrs) {
01951       Loc = Attr->getLocation();
01952       if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
01953         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
01954                     nullptr, D);
01955         CapDiagKind = ClassifyDiagnostic(A);
01956       } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
01957         // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
01958         // We must ignore such methods.
01959         if (A->args_size() == 0)
01960           return;
01961         // FIXME -- deal with exclusive vs. shared unlock functions?
01962         getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
01963         getMutexIDs(LocksReleased, A, nullptr, D);
01964         CapDiagKind = ClassifyDiagnostic(A);
01965       } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
01966         if (A->args_size() == 0)
01967           return;
01968         getMutexIDs(A->isShared() ? SharedLocksAcquired
01969                                   : ExclusiveLocksAcquired,
01970                     A, nullptr, D);
01971         CapDiagKind = ClassifyDiagnostic(A);
01972       } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
01973         // Don't try to check trylock functions for now
01974         return;
01975       } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
01976         // Don't try to check trylock functions for now
01977         return;
01978       }
01979     }
01980 
01981     // FIXME -- Loc can be wrong here.
01982     for (const auto &Mu : ExclusiveLocksToAdd)
01983       addLock(InitialLockset,
01984               llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc),
01985               CapDiagKind, true);
01986     for (const auto &Mu : SharedLocksToAdd)
01987       addLock(InitialLockset,
01988               llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc),
01989               CapDiagKind, true);
01990   }
01991 
01992   for (const auto *CurrBlock : *SortedGraph) {
01993     int CurrBlockID = CurrBlock->getBlockID();
01994     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
01995 
01996     // Use the default initial lockset in case there are no predecessors.
01997     VisitedBlocks.insert(CurrBlock);
01998 
01999     // Iterate through the predecessor blocks and warn if the lockset for all
02000     // predecessors is not the same. We take the entry lockset of the current
02001     // block to be the intersection of all previous locksets.
02002     // FIXME: By keeping the intersection, we may output more errors in future
02003     // for a lock which is not in the intersection, but was in the union. We
02004     // may want to also keep the union in future. As an example, let's say
02005     // the intersection contains Mutex L, and the union contains L and M.
02006     // Later we unlock M. At this point, we would output an error because we
02007     // never locked M; although the real error is probably that we forgot to
02008     // lock M on all code paths. Conversely, let's say that later we lock M.
02009     // In this case, we should compare against the intersection instead of the
02010     // union because the real error is probably that we forgot to unlock M on
02011     // all code paths.
02012     bool LocksetInitialized = false;
02013     SmallVector<CFGBlock *, 8> SpecialBlocks;
02014     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
02015          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
02016 
02017       // if *PI -> CurrBlock is a back edge
02018       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
02019         continue;
02020 
02021       int PrevBlockID = (*PI)->getBlockID();
02022       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
02023 
02024       // Ignore edges from blocks that can't return.
02025       if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
02026         continue;
02027 
02028       // Okay, we can reach this block from the entry.
02029       CurrBlockInfo->Reachable = true;
02030 
02031       // If the previous block ended in a 'continue' or 'break' statement, then
02032       // a difference in locksets is probably due to a bug in that block, rather
02033       // than in some other predecessor. In that case, keep the other
02034       // predecessor's lockset.
02035       if (const Stmt *Terminator = (*PI)->getTerminator()) {
02036         if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
02037           SpecialBlocks.push_back(*PI);
02038           continue;
02039         }
02040       }
02041 
02042       FactSet PrevLockset;
02043       getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
02044 
02045       if (!LocksetInitialized) {
02046         CurrBlockInfo->EntrySet = PrevLockset;
02047         LocksetInitialized = true;
02048       } else {
02049         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
02050                          CurrBlockInfo->EntryLoc,
02051                          LEK_LockedSomePredecessors);
02052       }
02053     }
02054 
02055     // Skip rest of block if it's not reachable.
02056     if (!CurrBlockInfo->Reachable)
02057       continue;
02058 
02059     // Process continue and break blocks. Assume that the lockset for the
02060     // resulting block is unaffected by any discrepancies in them.
02061     for (const auto *PrevBlock : SpecialBlocks) {
02062       int PrevBlockID = PrevBlock->getBlockID();
02063       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
02064 
02065       if (!LocksetInitialized) {
02066         CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
02067         LocksetInitialized = true;
02068       } else {
02069         // Determine whether this edge is a loop terminator for diagnostic
02070         // purposes. FIXME: A 'break' statement might be a loop terminator, but
02071         // it might also be part of a switch. Also, a subsequent destructor
02072         // might add to the lockset, in which case the real issue might be a
02073         // double lock on the other path.
02074         const Stmt *Terminator = PrevBlock->getTerminator();
02075         bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
02076 
02077         FactSet PrevLockset;
02078         getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
02079                        PrevBlock, CurrBlock);
02080 
02081         // Do not update EntrySet.
02082         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
02083                          PrevBlockInfo->ExitLoc,
02084                          IsLoop ? LEK_LockedSomeLoopIterations
02085                                 : LEK_LockedSomePredecessors,
02086                          false);
02087       }
02088     }
02089 
02090     BuildLockset LocksetBuilder(this, *CurrBlockInfo);
02091 
02092     // Visit all the statements in the basic block.
02093     for (CFGBlock::const_iterator BI = CurrBlock->begin(),
02094          BE = CurrBlock->end(); BI != BE; ++BI) {
02095       switch (BI->getKind()) {
02096         case CFGElement::Statement: {
02097           CFGStmt CS = BI->castAs<CFGStmt>();
02098           LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
02099           break;
02100         }
02101         // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
02102         case CFGElement::AutomaticObjectDtor: {
02103           CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
02104           CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
02105               AD.getDestructorDecl(AC.getASTContext()));
02106           if (!DD->hasAttrs())
02107             break;
02108 
02109           // Create a dummy expression,
02110           VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
02111           DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
02112                           AD.getTriggerStmt()->getLocEnd());
02113           LocksetBuilder.handleCall(&DRE, DD);
02114           break;
02115         }
02116         default:
02117           break;
02118       }
02119     }
02120     CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
02121 
02122     // For every back edge from CurrBlock (the end of the loop) to another block
02123     // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
02124     // the one held at the beginning of FirstLoopBlock. We can look up the
02125     // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
02126     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
02127          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
02128 
02129       // if CurrBlock -> *SI is *not* a back edge
02130       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
02131         continue;
02132 
02133       CFGBlock *FirstLoopBlock = *SI;
02134       CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
02135       CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
02136       intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
02137                        PreLoop->EntryLoc,
02138                        LEK_LockedSomeLoopIterations,
02139                        false);
02140     }
02141   }
02142 
02143   CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
02144   CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
02145 
02146   // Skip the final check if the exit block is unreachable.
02147   if (!Final->Reachable)
02148     return;
02149 
02150   // By default, we expect all locks held on entry to be held on exit.
02151   FactSet ExpectedExitSet = Initial->EntrySet;
02152 
02153   // Adjust the expected exit set by adding or removing locks, as declared
02154   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
02155   // issue the appropriate warning.
02156   // FIXME: the location here is not quite right.
02157   for (const auto &Lock : ExclusiveLocksAcquired)
02158     ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
02159                                          Lock, LK_Exclusive, D->getLocation()));
02160   for (const auto &Lock : SharedLocksAcquired)
02161     ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
02162                                          Lock, LK_Shared, D->getLocation()));
02163   for (const auto &Lock : LocksReleased)
02164     ExpectedExitSet.removeLock(FactMan, Lock);
02165 
02166   // FIXME: Should we call this function for all blocks which exit the function?
02167   intersectAndWarn(ExpectedExitSet, Final->ExitSet,
02168                    Final->ExitLoc,
02169                    LEK_LockedAtEndOfFunction,
02170                    LEK_NotLockedAtEndOfFunction,
02171                    false);
02172 
02173   Handler.leaveFunction(CurrentFunction);
02174 }
02175 
02176 
02177 /// \brief Check a function's CFG for thread-safety violations.
02178 ///
02179 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
02180 /// at the end of each block, and issue warnings for thread safety violations.
02181 /// Each block in the CFG is traversed exactly once.
02182 void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
02183                              ThreadSafetyHandler &Handler) {
02184   ThreadSafetyAnalyzer Analyzer(Handler);
02185   Analyzer.runAnalysis(AC);
02186 }
02187 
02188 /// \brief Helper function that returns a LockKind required for the given level
02189 /// of access.
02190 LockKind getLockKindFromAccessKind(AccessKind AK) {
02191   switch (AK) {
02192     case AK_Read :
02193       return LK_Shared;
02194     case AK_Written :
02195       return LK_Exclusive;
02196   }
02197   llvm_unreachable("Unknown AccessKind");
02198 }
02199 
02200 }} // end namespace clang::threadSafety