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