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