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