xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Analysis/ThreadSafety.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- ThreadSafety.cpp ---------------------------------------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // A intra-procedural analysis for thread safety (e.g. deadlocks and race
107330f729Sjoerg // conditions), based off of an annotation system.
117330f729Sjoerg //
127330f729Sjoerg // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
137330f729Sjoerg // for more information.
147330f729Sjoerg //
157330f729Sjoerg //===----------------------------------------------------------------------===//
167330f729Sjoerg 
177330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafety.h"
187330f729Sjoerg #include "clang/AST/Attr.h"
197330f729Sjoerg #include "clang/AST/Decl.h"
207330f729Sjoerg #include "clang/AST/DeclCXX.h"
217330f729Sjoerg #include "clang/AST/DeclGroup.h"
227330f729Sjoerg #include "clang/AST/Expr.h"
237330f729Sjoerg #include "clang/AST/ExprCXX.h"
247330f729Sjoerg #include "clang/AST/OperationKinds.h"
257330f729Sjoerg #include "clang/AST/Stmt.h"
267330f729Sjoerg #include "clang/AST/StmtVisitor.h"
277330f729Sjoerg #include "clang/AST/Type.h"
287330f729Sjoerg #include "clang/Analysis/Analyses/PostOrderCFGView.h"
297330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
307330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
317330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
327330f729Sjoerg #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
337330f729Sjoerg #include "clang/Analysis/AnalysisDeclContext.h"
347330f729Sjoerg #include "clang/Analysis/CFG.h"
357330f729Sjoerg #include "clang/Basic/Builtins.h"
367330f729Sjoerg #include "clang/Basic/LLVM.h"
377330f729Sjoerg #include "clang/Basic/OperatorKinds.h"
387330f729Sjoerg #include "clang/Basic/SourceLocation.h"
397330f729Sjoerg #include "clang/Basic/Specifiers.h"
407330f729Sjoerg #include "llvm/ADT/ArrayRef.h"
417330f729Sjoerg #include "llvm/ADT/DenseMap.h"
427330f729Sjoerg #include "llvm/ADT/ImmutableMap.h"
437330f729Sjoerg #include "llvm/ADT/Optional.h"
447330f729Sjoerg #include "llvm/ADT/PointerIntPair.h"
457330f729Sjoerg #include "llvm/ADT/STLExtras.h"
467330f729Sjoerg #include "llvm/ADT/SmallVector.h"
477330f729Sjoerg #include "llvm/ADT/StringRef.h"
487330f729Sjoerg #include "llvm/Support/Allocator.h"
497330f729Sjoerg #include "llvm/Support/Casting.h"
507330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
517330f729Sjoerg #include "llvm/Support/raw_ostream.h"
527330f729Sjoerg #include <algorithm>
537330f729Sjoerg #include <cassert>
547330f729Sjoerg #include <functional>
557330f729Sjoerg #include <iterator>
567330f729Sjoerg #include <memory>
577330f729Sjoerg #include <string>
587330f729Sjoerg #include <type_traits>
597330f729Sjoerg #include <utility>
607330f729Sjoerg #include <vector>
617330f729Sjoerg 
627330f729Sjoerg using namespace clang;
637330f729Sjoerg using namespace threadSafety;
647330f729Sjoerg 
657330f729Sjoerg // Key method definition
667330f729Sjoerg ThreadSafetyHandler::~ThreadSafetyHandler() = default;
677330f729Sjoerg 
687330f729Sjoerg /// Issue a warning about an invalid lock expression
warnInvalidLock(ThreadSafetyHandler & Handler,const Expr * MutexExp,const NamedDecl * D,const Expr * DeclExp,StringRef Kind)697330f729Sjoerg static void warnInvalidLock(ThreadSafetyHandler &Handler,
707330f729Sjoerg                             const Expr *MutexExp, const NamedDecl *D,
717330f729Sjoerg                             const Expr *DeclExp, StringRef Kind) {
727330f729Sjoerg   SourceLocation Loc;
737330f729Sjoerg   if (DeclExp)
747330f729Sjoerg     Loc = DeclExp->getExprLoc();
757330f729Sjoerg 
767330f729Sjoerg   // FIXME: add a note about the attribute location in MutexExp or D
777330f729Sjoerg   if (Loc.isValid())
787330f729Sjoerg     Handler.handleInvalidLockExp(Kind, Loc);
797330f729Sjoerg }
807330f729Sjoerg 
817330f729Sjoerg namespace {
827330f729Sjoerg 
837330f729Sjoerg /// A set of CapabilityExpr objects, which are compiled from thread safety
847330f729Sjoerg /// attributes on a function.
857330f729Sjoerg class CapExprSet : public SmallVector<CapabilityExpr, 4> {
867330f729Sjoerg public:
877330f729Sjoerg   /// Push M onto list, but discard duplicates.
push_back_nodup(const CapabilityExpr & CapE)887330f729Sjoerg   void push_back_nodup(const CapabilityExpr &CapE) {
897330f729Sjoerg     iterator It = std::find_if(begin(), end(),
907330f729Sjoerg                                [=](const CapabilityExpr &CapE2) {
917330f729Sjoerg       return CapE.equals(CapE2);
927330f729Sjoerg     });
937330f729Sjoerg     if (It == end())
947330f729Sjoerg       push_back(CapE);
957330f729Sjoerg   }
967330f729Sjoerg };
977330f729Sjoerg 
987330f729Sjoerg class FactManager;
997330f729Sjoerg class FactSet;
1007330f729Sjoerg 
1017330f729Sjoerg /// This is a helper class that stores a fact that is known at a
1027330f729Sjoerg /// particular point in program execution.  Currently, a fact is a capability,
1037330f729Sjoerg /// along with additional information, such as where it was acquired, whether
1047330f729Sjoerg /// it is exclusive or shared, etc.
1057330f729Sjoerg ///
1067330f729Sjoerg /// FIXME: this analysis does not currently support re-entrant locking.
1077330f729Sjoerg class FactEntry : public CapabilityExpr {
108*e038c9c4Sjoerg public:
109*e038c9c4Sjoerg   /// Where a fact comes from.
110*e038c9c4Sjoerg   enum SourceKind {
111*e038c9c4Sjoerg     Acquired, ///< The fact has been directly acquired.
112*e038c9c4Sjoerg     Asserted, ///< The fact has been asserted to be held.
113*e038c9c4Sjoerg     Declared, ///< The fact is assumed to be held by callers.
114*e038c9c4Sjoerg     Managed,  ///< The fact has been acquired through a scoped capability.
115*e038c9c4Sjoerg   };
116*e038c9c4Sjoerg 
1177330f729Sjoerg private:
1187330f729Sjoerg   /// Exclusive or shared.
119*e038c9c4Sjoerg   LockKind LKind : 8;
120*e038c9c4Sjoerg 
121*e038c9c4Sjoerg   // How it was acquired.
122*e038c9c4Sjoerg   SourceKind Source : 8;
1237330f729Sjoerg 
1247330f729Sjoerg   /// Where it was acquired.
1257330f729Sjoerg   SourceLocation AcquireLoc;
1267330f729Sjoerg 
1277330f729Sjoerg public:
FactEntry(const CapabilityExpr & CE,LockKind LK,SourceLocation Loc,SourceKind Src)1287330f729Sjoerg   FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
129*e038c9c4Sjoerg             SourceKind Src)
130*e038c9c4Sjoerg       : CapabilityExpr(CE), LKind(LK), Source(Src), AcquireLoc(Loc) {}
1317330f729Sjoerg   virtual ~FactEntry() = default;
1327330f729Sjoerg 
kind() const1337330f729Sjoerg   LockKind kind() const { return LKind;      }
loc() const1347330f729Sjoerg   SourceLocation loc() const { return AcquireLoc; }
1357330f729Sjoerg 
asserted() const136*e038c9c4Sjoerg   bool asserted() const { return Source == Asserted; }
declared() const137*e038c9c4Sjoerg   bool declared() const { return Source == Declared; }
managed() const138*e038c9c4Sjoerg   bool managed() const { return Source == Managed; }
1397330f729Sjoerg 
1407330f729Sjoerg   virtual void
1417330f729Sjoerg   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
1427330f729Sjoerg                                 SourceLocation JoinLoc, LockErrorKind LEK,
1437330f729Sjoerg                                 ThreadSafetyHandler &Handler) const = 0;
1447330f729Sjoerg   virtual void handleLock(FactSet &FSet, FactManager &FactMan,
1457330f729Sjoerg                           const FactEntry &entry, ThreadSafetyHandler &Handler,
1467330f729Sjoerg                           StringRef DiagKind) const = 0;
1477330f729Sjoerg   virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
1487330f729Sjoerg                             const CapabilityExpr &Cp, SourceLocation UnlockLoc,
1497330f729Sjoerg                             bool FullyRemove, ThreadSafetyHandler &Handler,
1507330f729Sjoerg                             StringRef DiagKind) const = 0;
1517330f729Sjoerg 
1527330f729Sjoerg   // Return true if LKind >= LK, where exclusive > shared
isAtLeast(LockKind LK) const1537330f729Sjoerg   bool isAtLeast(LockKind LK) const {
1547330f729Sjoerg     return  (LKind == LK_Exclusive) || (LK == LK_Shared);
1557330f729Sjoerg   }
1567330f729Sjoerg };
1577330f729Sjoerg 
1587330f729Sjoerg using FactID = unsigned short;
1597330f729Sjoerg 
1607330f729Sjoerg /// FactManager manages the memory for all facts that are created during
1617330f729Sjoerg /// the analysis of a single routine.
1627330f729Sjoerg class FactManager {
1637330f729Sjoerg private:
1647330f729Sjoerg   std::vector<std::unique_ptr<const FactEntry>> Facts;
1657330f729Sjoerg 
1667330f729Sjoerg public:
newFact(std::unique_ptr<FactEntry> Entry)1677330f729Sjoerg   FactID newFact(std::unique_ptr<FactEntry> Entry) {
1687330f729Sjoerg     Facts.push_back(std::move(Entry));
1697330f729Sjoerg     return static_cast<unsigned short>(Facts.size() - 1);
1707330f729Sjoerg   }
1717330f729Sjoerg 
operator [](FactID F) const1727330f729Sjoerg   const FactEntry &operator[](FactID F) const { return *Facts[F]; }
1737330f729Sjoerg };
1747330f729Sjoerg 
1757330f729Sjoerg /// A FactSet is the set of facts that are known to be true at a
1767330f729Sjoerg /// particular program point.  FactSets must be small, because they are
1777330f729Sjoerg /// frequently copied, and are thus implemented as a set of indices into a
1787330f729Sjoerg /// table maintained by a FactManager.  A typical FactSet only holds 1 or 2
1797330f729Sjoerg /// locks, so we can get away with doing a linear search for lookup.  Note
1807330f729Sjoerg /// that a hashtable or map is inappropriate in this case, because lookups
1817330f729Sjoerg /// may involve partial pattern matches, rather than exact matches.
1827330f729Sjoerg class FactSet {
1837330f729Sjoerg private:
1847330f729Sjoerg   using FactVec = SmallVector<FactID, 4>;
1857330f729Sjoerg 
1867330f729Sjoerg   FactVec FactIDs;
1877330f729Sjoerg 
1887330f729Sjoerg public:
1897330f729Sjoerg   using iterator = FactVec::iterator;
1907330f729Sjoerg   using const_iterator = FactVec::const_iterator;
1917330f729Sjoerg 
begin()1927330f729Sjoerg   iterator begin() { return FactIDs.begin(); }
begin() const1937330f729Sjoerg   const_iterator begin() const { return FactIDs.begin(); }
1947330f729Sjoerg 
end()1957330f729Sjoerg   iterator end() { return FactIDs.end(); }
end() const1967330f729Sjoerg   const_iterator end() const { return FactIDs.end(); }
1977330f729Sjoerg 
isEmpty() const1987330f729Sjoerg   bool isEmpty() const { return FactIDs.size() == 0; }
1997330f729Sjoerg 
2007330f729Sjoerg   // Return true if the set contains only negative facts
isEmpty(FactManager & FactMan) const2017330f729Sjoerg   bool isEmpty(FactManager &FactMan) const {
2027330f729Sjoerg     for (const auto FID : *this) {
2037330f729Sjoerg       if (!FactMan[FID].negative())
2047330f729Sjoerg         return false;
2057330f729Sjoerg     }
2067330f729Sjoerg     return true;
2077330f729Sjoerg   }
2087330f729Sjoerg 
addLockByID(FactID ID)2097330f729Sjoerg   void addLockByID(FactID ID) { FactIDs.push_back(ID); }
2107330f729Sjoerg 
addLock(FactManager & FM,std::unique_ptr<FactEntry> Entry)2117330f729Sjoerg   FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
2127330f729Sjoerg     FactID F = FM.newFact(std::move(Entry));
2137330f729Sjoerg     FactIDs.push_back(F);
2147330f729Sjoerg     return F;
2157330f729Sjoerg   }
2167330f729Sjoerg 
removeLock(FactManager & FM,const CapabilityExpr & CapE)2177330f729Sjoerg   bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
2187330f729Sjoerg     unsigned n = FactIDs.size();
2197330f729Sjoerg     if (n == 0)
2207330f729Sjoerg       return false;
2217330f729Sjoerg 
2227330f729Sjoerg     for (unsigned i = 0; i < n-1; ++i) {
2237330f729Sjoerg       if (FM[FactIDs[i]].matches(CapE)) {
2247330f729Sjoerg         FactIDs[i] = FactIDs[n-1];
2257330f729Sjoerg         FactIDs.pop_back();
2267330f729Sjoerg         return true;
2277330f729Sjoerg       }
2287330f729Sjoerg     }
2297330f729Sjoerg     if (FM[FactIDs[n-1]].matches(CapE)) {
2307330f729Sjoerg       FactIDs.pop_back();
2317330f729Sjoerg       return true;
2327330f729Sjoerg     }
2337330f729Sjoerg     return false;
2347330f729Sjoerg   }
2357330f729Sjoerg 
findLockIter(FactManager & FM,const CapabilityExpr & CapE)2367330f729Sjoerg   iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
2377330f729Sjoerg     return std::find_if(begin(), end(), [&](FactID ID) {
2387330f729Sjoerg       return FM[ID].matches(CapE);
2397330f729Sjoerg     });
2407330f729Sjoerg   }
2417330f729Sjoerg 
findLock(FactManager & FM,const CapabilityExpr & CapE) const2427330f729Sjoerg   const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
2437330f729Sjoerg     auto I = std::find_if(begin(), end(), [&](FactID ID) {
2447330f729Sjoerg       return FM[ID].matches(CapE);
2457330f729Sjoerg     });
2467330f729Sjoerg     return I != end() ? &FM[*I] : nullptr;
2477330f729Sjoerg   }
2487330f729Sjoerg 
findLockUniv(FactManager & FM,const CapabilityExpr & CapE) const2497330f729Sjoerg   const FactEntry *findLockUniv(FactManager &FM,
2507330f729Sjoerg                                 const CapabilityExpr &CapE) const {
2517330f729Sjoerg     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2527330f729Sjoerg       return FM[ID].matchesUniv(CapE);
2537330f729Sjoerg     });
2547330f729Sjoerg     return I != end() ? &FM[*I] : nullptr;
2557330f729Sjoerg   }
2567330f729Sjoerg 
findPartialMatch(FactManager & FM,const CapabilityExpr & CapE) const2577330f729Sjoerg   const FactEntry *findPartialMatch(FactManager &FM,
2587330f729Sjoerg                                     const CapabilityExpr &CapE) const {
2597330f729Sjoerg     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2607330f729Sjoerg       return FM[ID].partiallyMatches(CapE);
2617330f729Sjoerg     });
2627330f729Sjoerg     return I != end() ? &FM[*I] : nullptr;
2637330f729Sjoerg   }
2647330f729Sjoerg 
containsMutexDecl(FactManager & FM,const ValueDecl * Vd) const2657330f729Sjoerg   bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
2667330f729Sjoerg     auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2677330f729Sjoerg       return FM[ID].valueDecl() == Vd;
2687330f729Sjoerg     });
2697330f729Sjoerg     return I != end();
2707330f729Sjoerg   }
2717330f729Sjoerg };
2727330f729Sjoerg 
2737330f729Sjoerg class ThreadSafetyAnalyzer;
2747330f729Sjoerg 
2757330f729Sjoerg } // namespace
2767330f729Sjoerg 
2777330f729Sjoerg namespace clang {
2787330f729Sjoerg namespace threadSafety {
2797330f729Sjoerg 
2807330f729Sjoerg class BeforeSet {
2817330f729Sjoerg private:
2827330f729Sjoerg   using BeforeVect = SmallVector<const ValueDecl *, 4>;
2837330f729Sjoerg 
2847330f729Sjoerg   struct BeforeInfo {
2857330f729Sjoerg     BeforeVect Vect;
2867330f729Sjoerg     int Visited = 0;
2877330f729Sjoerg 
2887330f729Sjoerg     BeforeInfo() = default;
2897330f729Sjoerg     BeforeInfo(BeforeInfo &&) = default;
2907330f729Sjoerg   };
2917330f729Sjoerg 
2927330f729Sjoerg   using BeforeMap =
2937330f729Sjoerg       llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
2947330f729Sjoerg   using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
2957330f729Sjoerg 
2967330f729Sjoerg public:
2977330f729Sjoerg   BeforeSet() = default;
2987330f729Sjoerg 
2997330f729Sjoerg   BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
3007330f729Sjoerg                               ThreadSafetyAnalyzer& Analyzer);
3017330f729Sjoerg 
3027330f729Sjoerg   BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
3037330f729Sjoerg                                    ThreadSafetyAnalyzer &Analyzer);
3047330f729Sjoerg 
3057330f729Sjoerg   void checkBeforeAfter(const ValueDecl* Vd,
3067330f729Sjoerg                         const FactSet& FSet,
3077330f729Sjoerg                         ThreadSafetyAnalyzer& Analyzer,
3087330f729Sjoerg                         SourceLocation Loc, StringRef CapKind);
3097330f729Sjoerg 
3107330f729Sjoerg private:
3117330f729Sjoerg   BeforeMap BMap;
3127330f729Sjoerg   CycleMap CycMap;
3137330f729Sjoerg };
3147330f729Sjoerg 
3157330f729Sjoerg } // namespace threadSafety
3167330f729Sjoerg } // namespace clang
3177330f729Sjoerg 
3187330f729Sjoerg namespace {
3197330f729Sjoerg 
3207330f729Sjoerg class LocalVariableMap;
3217330f729Sjoerg 
3227330f729Sjoerg using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
3237330f729Sjoerg 
3247330f729Sjoerg /// A side (entry or exit) of a CFG node.
3257330f729Sjoerg enum CFGBlockSide { CBS_Entry, CBS_Exit };
3267330f729Sjoerg 
3277330f729Sjoerg /// CFGBlockInfo is a struct which contains all the information that is
3287330f729Sjoerg /// maintained for each block in the CFG.  See LocalVariableMap for more
3297330f729Sjoerg /// information about the contexts.
3307330f729Sjoerg struct CFGBlockInfo {
3317330f729Sjoerg   // Lockset held at entry to block
3327330f729Sjoerg   FactSet EntrySet;
3337330f729Sjoerg 
3347330f729Sjoerg   // Lockset held at exit from block
3357330f729Sjoerg   FactSet ExitSet;
3367330f729Sjoerg 
3377330f729Sjoerg   // Context held at entry to block
3387330f729Sjoerg   LocalVarContext EntryContext;
3397330f729Sjoerg 
3407330f729Sjoerg   // Context held at exit from block
3417330f729Sjoerg   LocalVarContext ExitContext;
3427330f729Sjoerg 
3437330f729Sjoerg   // Location of first statement in block
3447330f729Sjoerg   SourceLocation EntryLoc;
3457330f729Sjoerg 
3467330f729Sjoerg   // Location of last statement in block.
3477330f729Sjoerg   SourceLocation ExitLoc;
3487330f729Sjoerg 
3497330f729Sjoerg   // Used to replay contexts later
3507330f729Sjoerg   unsigned EntryIndex;
3517330f729Sjoerg 
3527330f729Sjoerg   // Is this block reachable?
3537330f729Sjoerg   bool Reachable = false;
3547330f729Sjoerg 
getSet__anon68dfda3c0811::CFGBlockInfo3557330f729Sjoerg   const FactSet &getSet(CFGBlockSide Side) const {
3567330f729Sjoerg     return Side == CBS_Entry ? EntrySet : ExitSet;
3577330f729Sjoerg   }
3587330f729Sjoerg 
getLocation__anon68dfda3c0811::CFGBlockInfo3597330f729Sjoerg   SourceLocation getLocation(CFGBlockSide Side) const {
3607330f729Sjoerg     return Side == CBS_Entry ? EntryLoc : ExitLoc;
3617330f729Sjoerg   }
3627330f729Sjoerg 
3637330f729Sjoerg private:
CFGBlockInfo__anon68dfda3c0811::CFGBlockInfo3647330f729Sjoerg   CFGBlockInfo(LocalVarContext EmptyCtx)
3657330f729Sjoerg       : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
3667330f729Sjoerg 
3677330f729Sjoerg public:
3687330f729Sjoerg   static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
3697330f729Sjoerg };
3707330f729Sjoerg 
3717330f729Sjoerg // A LocalVariableMap maintains a map from local variables to their currently
3727330f729Sjoerg // valid definitions.  It provides SSA-like functionality when traversing the
3737330f729Sjoerg // CFG.  Like SSA, each definition or assignment to a variable is assigned a
3747330f729Sjoerg // unique name (an integer), which acts as the SSA name for that definition.
3757330f729Sjoerg // The total set of names is shared among all CFG basic blocks.
3767330f729Sjoerg // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
3777330f729Sjoerg // with their SSA-names.  Instead, we compute a Context for each point in the
3787330f729Sjoerg // code, which maps local variables to the appropriate SSA-name.  This map
3797330f729Sjoerg // changes with each assignment.
3807330f729Sjoerg //
3817330f729Sjoerg // The map is computed in a single pass over the CFG.  Subsequent analyses can
3827330f729Sjoerg // then query the map to find the appropriate Context for a statement, and use
3837330f729Sjoerg // that Context to look up the definitions of variables.
3847330f729Sjoerg class LocalVariableMap {
3857330f729Sjoerg public:
3867330f729Sjoerg   using Context = LocalVarContext;
3877330f729Sjoerg 
3887330f729Sjoerg   /// A VarDefinition consists of an expression, representing the value of the
3897330f729Sjoerg   /// variable, along with the context in which that expression should be
3907330f729Sjoerg   /// interpreted.  A reference VarDefinition does not itself contain this
3917330f729Sjoerg   /// information, but instead contains a pointer to a previous VarDefinition.
3927330f729Sjoerg   struct VarDefinition {
3937330f729Sjoerg   public:
3947330f729Sjoerg     friend class LocalVariableMap;
3957330f729Sjoerg 
3967330f729Sjoerg     // The original declaration for this variable.
3977330f729Sjoerg     const NamedDecl *Dec;
3987330f729Sjoerg 
3997330f729Sjoerg     // The expression for this variable, OR
4007330f729Sjoerg     const Expr *Exp = nullptr;
4017330f729Sjoerg 
4027330f729Sjoerg     // Reference to another VarDefinition
4037330f729Sjoerg     unsigned Ref = 0;
4047330f729Sjoerg 
4057330f729Sjoerg     // The map with which Exp should be interpreted.
4067330f729Sjoerg     Context Ctx;
4077330f729Sjoerg 
isReference__anon68dfda3c0811::LocalVariableMap::VarDefinition4087330f729Sjoerg     bool isReference() { return !Exp; }
4097330f729Sjoerg 
4107330f729Sjoerg   private:
4117330f729Sjoerg     // Create ordinary variable definition
VarDefinition__anon68dfda3c0811::LocalVariableMap::VarDefinition4127330f729Sjoerg     VarDefinition(const NamedDecl *D, const Expr *E, Context C)
4137330f729Sjoerg         : Dec(D), Exp(E), Ctx(C) {}
4147330f729Sjoerg 
4157330f729Sjoerg     // Create reference to previous definition
VarDefinition__anon68dfda3c0811::LocalVariableMap::VarDefinition4167330f729Sjoerg     VarDefinition(const NamedDecl *D, unsigned R, Context C)
4177330f729Sjoerg         : Dec(D), Ref(R), Ctx(C) {}
4187330f729Sjoerg   };
4197330f729Sjoerg 
4207330f729Sjoerg private:
4217330f729Sjoerg   Context::Factory ContextFactory;
4227330f729Sjoerg   std::vector<VarDefinition> VarDefinitions;
4237330f729Sjoerg   std::vector<unsigned> CtxIndices;
4247330f729Sjoerg   std::vector<std::pair<const Stmt *, Context>> SavedContexts;
4257330f729Sjoerg 
4267330f729Sjoerg public:
LocalVariableMap()4277330f729Sjoerg   LocalVariableMap() {
4287330f729Sjoerg     // index 0 is a placeholder for undefined variables (aka phi-nodes).
4297330f729Sjoerg     VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
4307330f729Sjoerg   }
4317330f729Sjoerg 
4327330f729Sjoerg   /// Look up a definition, within the given context.
lookup(const NamedDecl * D,Context Ctx)4337330f729Sjoerg   const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
4347330f729Sjoerg     const unsigned *i = Ctx.lookup(D);
4357330f729Sjoerg     if (!i)
4367330f729Sjoerg       return nullptr;
4377330f729Sjoerg     assert(*i < VarDefinitions.size());
4387330f729Sjoerg     return &VarDefinitions[*i];
4397330f729Sjoerg   }
4407330f729Sjoerg 
4417330f729Sjoerg   /// Look up the definition for D within the given context.  Returns
4427330f729Sjoerg   /// NULL if the expression is not statically known.  If successful, also
4437330f729Sjoerg   /// modifies Ctx to hold the context of the return Expr.
lookupExpr(const NamedDecl * D,Context & Ctx)4447330f729Sjoerg   const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
4457330f729Sjoerg     const unsigned *P = Ctx.lookup(D);
4467330f729Sjoerg     if (!P)
4477330f729Sjoerg       return nullptr;
4487330f729Sjoerg 
4497330f729Sjoerg     unsigned i = *P;
4507330f729Sjoerg     while (i > 0) {
4517330f729Sjoerg       if (VarDefinitions[i].Exp) {
4527330f729Sjoerg         Ctx = VarDefinitions[i].Ctx;
4537330f729Sjoerg         return VarDefinitions[i].Exp;
4547330f729Sjoerg       }
4557330f729Sjoerg       i = VarDefinitions[i].Ref;
4567330f729Sjoerg     }
4577330f729Sjoerg     return nullptr;
4587330f729Sjoerg   }
4597330f729Sjoerg 
getEmptyContext()4607330f729Sjoerg   Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
4617330f729Sjoerg 
4627330f729Sjoerg   /// Return the next context after processing S.  This function is used by
4637330f729Sjoerg   /// clients of the class to get the appropriate context when traversing the
4647330f729Sjoerg   /// CFG.  It must be called for every assignment or DeclStmt.
getNextContext(unsigned & CtxIndex,const Stmt * S,Context C)4657330f729Sjoerg   Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
4667330f729Sjoerg     if (SavedContexts[CtxIndex+1].first == S) {
4677330f729Sjoerg       CtxIndex++;
4687330f729Sjoerg       Context Result = SavedContexts[CtxIndex].second;
4697330f729Sjoerg       return Result;
4707330f729Sjoerg     }
4717330f729Sjoerg     return C;
4727330f729Sjoerg   }
4737330f729Sjoerg 
dumpVarDefinitionName(unsigned i)4747330f729Sjoerg   void dumpVarDefinitionName(unsigned i) {
4757330f729Sjoerg     if (i == 0) {
4767330f729Sjoerg       llvm::errs() << "Undefined";
4777330f729Sjoerg       return;
4787330f729Sjoerg     }
4797330f729Sjoerg     const NamedDecl *Dec = VarDefinitions[i].Dec;
4807330f729Sjoerg     if (!Dec) {
4817330f729Sjoerg       llvm::errs() << "<<NULL>>";
4827330f729Sjoerg       return;
4837330f729Sjoerg     }
4847330f729Sjoerg     Dec->printName(llvm::errs());
4857330f729Sjoerg     llvm::errs() << "." << i << " " << ((const void*) Dec);
4867330f729Sjoerg   }
4877330f729Sjoerg 
4887330f729Sjoerg   /// Dumps an ASCII representation of the variable map to llvm::errs()
dump()4897330f729Sjoerg   void dump() {
4907330f729Sjoerg     for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
4917330f729Sjoerg       const Expr *Exp = VarDefinitions[i].Exp;
4927330f729Sjoerg       unsigned Ref = VarDefinitions[i].Ref;
4937330f729Sjoerg 
4947330f729Sjoerg       dumpVarDefinitionName(i);
4957330f729Sjoerg       llvm::errs() << " = ";
4967330f729Sjoerg       if (Exp) Exp->dump();
4977330f729Sjoerg       else {
4987330f729Sjoerg         dumpVarDefinitionName(Ref);
4997330f729Sjoerg         llvm::errs() << "\n";
5007330f729Sjoerg       }
5017330f729Sjoerg     }
5027330f729Sjoerg   }
5037330f729Sjoerg 
5047330f729Sjoerg   /// Dumps an ASCII representation of a Context to llvm::errs()
dumpContext(Context C)5057330f729Sjoerg   void dumpContext(Context C) {
5067330f729Sjoerg     for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
5077330f729Sjoerg       const NamedDecl *D = I.getKey();
5087330f729Sjoerg       D->printName(llvm::errs());
5097330f729Sjoerg       const unsigned *i = C.lookup(D);
5107330f729Sjoerg       llvm::errs() << " -> ";
5117330f729Sjoerg       dumpVarDefinitionName(*i);
5127330f729Sjoerg       llvm::errs() << "\n";
5137330f729Sjoerg     }
5147330f729Sjoerg   }
5157330f729Sjoerg 
5167330f729Sjoerg   /// Builds the variable map.
5177330f729Sjoerg   void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
5187330f729Sjoerg                    std::vector<CFGBlockInfo> &BlockInfo);
5197330f729Sjoerg 
5207330f729Sjoerg protected:
5217330f729Sjoerg   friend class VarMapBuilder;
5227330f729Sjoerg 
5237330f729Sjoerg   // Get the current context index
getContextIndex()5247330f729Sjoerg   unsigned getContextIndex() { return SavedContexts.size()-1; }
5257330f729Sjoerg 
5267330f729Sjoerg   // Save the current context for later replay
saveContext(const Stmt * S,Context C)5277330f729Sjoerg   void saveContext(const Stmt *S, Context C) {
5287330f729Sjoerg     SavedContexts.push_back(std::make_pair(S, C));
5297330f729Sjoerg   }
5307330f729Sjoerg 
5317330f729Sjoerg   // Adds a new definition to the given context, and returns a new context.
5327330f729Sjoerg   // This method should be called when declaring a new variable.
addDefinition(const NamedDecl * D,const Expr * Exp,Context Ctx)5337330f729Sjoerg   Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
5347330f729Sjoerg     assert(!Ctx.contains(D));
5357330f729Sjoerg     unsigned newID = VarDefinitions.size();
5367330f729Sjoerg     Context NewCtx = ContextFactory.add(Ctx, D, newID);
5377330f729Sjoerg     VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
5387330f729Sjoerg     return NewCtx;
5397330f729Sjoerg   }
5407330f729Sjoerg 
5417330f729Sjoerg   // Add a new reference to an existing definition.
addReference(const NamedDecl * D,unsigned i,Context Ctx)5427330f729Sjoerg   Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
5437330f729Sjoerg     unsigned newID = VarDefinitions.size();
5447330f729Sjoerg     Context NewCtx = ContextFactory.add(Ctx, D, newID);
5457330f729Sjoerg     VarDefinitions.push_back(VarDefinition(D, i, Ctx));
5467330f729Sjoerg     return NewCtx;
5477330f729Sjoerg   }
5487330f729Sjoerg 
5497330f729Sjoerg   // Updates a definition only if that definition is already in the map.
5507330f729Sjoerg   // This method should be called when assigning to an existing variable.
updateDefinition(const NamedDecl * D,Expr * Exp,Context Ctx)5517330f729Sjoerg   Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
5527330f729Sjoerg     if (Ctx.contains(D)) {
5537330f729Sjoerg       unsigned newID = VarDefinitions.size();
5547330f729Sjoerg       Context NewCtx = ContextFactory.remove(Ctx, D);
5557330f729Sjoerg       NewCtx = ContextFactory.add(NewCtx, D, newID);
5567330f729Sjoerg       VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
5577330f729Sjoerg       return NewCtx;
5587330f729Sjoerg     }
5597330f729Sjoerg     return Ctx;
5607330f729Sjoerg   }
5617330f729Sjoerg 
5627330f729Sjoerg   // Removes a definition from the context, but keeps the variable name
5637330f729Sjoerg   // as a valid variable.  The index 0 is a placeholder for cleared definitions.
clearDefinition(const NamedDecl * D,Context Ctx)5647330f729Sjoerg   Context clearDefinition(const NamedDecl *D, Context Ctx) {
5657330f729Sjoerg     Context NewCtx = Ctx;
5667330f729Sjoerg     if (NewCtx.contains(D)) {
5677330f729Sjoerg       NewCtx = ContextFactory.remove(NewCtx, D);
5687330f729Sjoerg       NewCtx = ContextFactory.add(NewCtx, D, 0);
5697330f729Sjoerg     }
5707330f729Sjoerg     return NewCtx;
5717330f729Sjoerg   }
5727330f729Sjoerg 
5737330f729Sjoerg   // Remove a definition entirely frmo the context.
removeDefinition(const NamedDecl * D,Context Ctx)5747330f729Sjoerg   Context removeDefinition(const NamedDecl *D, Context Ctx) {
5757330f729Sjoerg     Context NewCtx = Ctx;
5767330f729Sjoerg     if (NewCtx.contains(D)) {
5777330f729Sjoerg       NewCtx = ContextFactory.remove(NewCtx, D);
5787330f729Sjoerg     }
5797330f729Sjoerg     return NewCtx;
5807330f729Sjoerg   }
5817330f729Sjoerg 
5827330f729Sjoerg   Context intersectContexts(Context C1, Context C2);
5837330f729Sjoerg   Context createReferenceContext(Context C);
5847330f729Sjoerg   void intersectBackEdge(Context C1, Context C2);
5857330f729Sjoerg };
5867330f729Sjoerg 
5877330f729Sjoerg } // namespace
5887330f729Sjoerg 
5897330f729Sjoerg // This has to be defined after LocalVariableMap.
getEmptyBlockInfo(LocalVariableMap & M)5907330f729Sjoerg CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
5917330f729Sjoerg   return CFGBlockInfo(M.getEmptyContext());
5927330f729Sjoerg }
5937330f729Sjoerg 
5947330f729Sjoerg namespace {
5957330f729Sjoerg 
5967330f729Sjoerg /// Visitor which builds a LocalVariableMap
5977330f729Sjoerg class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
5987330f729Sjoerg public:
5997330f729Sjoerg   LocalVariableMap* VMap;
6007330f729Sjoerg   LocalVariableMap::Context Ctx;
6017330f729Sjoerg 
VarMapBuilder(LocalVariableMap * VM,LocalVariableMap::Context C)6027330f729Sjoerg   VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
6037330f729Sjoerg       : VMap(VM), Ctx(C) {}
6047330f729Sjoerg 
6057330f729Sjoerg   void VisitDeclStmt(const DeclStmt *S);
6067330f729Sjoerg   void VisitBinaryOperator(const BinaryOperator *BO);
6077330f729Sjoerg };
6087330f729Sjoerg 
6097330f729Sjoerg } // namespace
6107330f729Sjoerg 
6117330f729Sjoerg // Add new local variables to the variable map
VisitDeclStmt(const DeclStmt * S)6127330f729Sjoerg void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
6137330f729Sjoerg   bool modifiedCtx = false;
6147330f729Sjoerg   const DeclGroupRef DGrp = S->getDeclGroup();
6157330f729Sjoerg   for (const auto *D : DGrp) {
6167330f729Sjoerg     if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
6177330f729Sjoerg       const Expr *E = VD->getInit();
6187330f729Sjoerg 
6197330f729Sjoerg       // Add local variables with trivial type to the variable map
6207330f729Sjoerg       QualType T = VD->getType();
6217330f729Sjoerg       if (T.isTrivialType(VD->getASTContext())) {
6227330f729Sjoerg         Ctx = VMap->addDefinition(VD, E, Ctx);
6237330f729Sjoerg         modifiedCtx = true;
6247330f729Sjoerg       }
6257330f729Sjoerg     }
6267330f729Sjoerg   }
6277330f729Sjoerg   if (modifiedCtx)
6287330f729Sjoerg     VMap->saveContext(S, Ctx);
6297330f729Sjoerg }
6307330f729Sjoerg 
6317330f729Sjoerg // Update local variable definitions in variable map
VisitBinaryOperator(const BinaryOperator * BO)6327330f729Sjoerg void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
6337330f729Sjoerg   if (!BO->isAssignmentOp())
6347330f729Sjoerg     return;
6357330f729Sjoerg 
6367330f729Sjoerg   Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
6377330f729Sjoerg 
6387330f729Sjoerg   // Update the variable map and current context.
6397330f729Sjoerg   if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
6407330f729Sjoerg     const ValueDecl *VDec = DRE->getDecl();
6417330f729Sjoerg     if (Ctx.lookup(VDec)) {
6427330f729Sjoerg       if (BO->getOpcode() == BO_Assign)
6437330f729Sjoerg         Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
6447330f729Sjoerg       else
6457330f729Sjoerg         // FIXME -- handle compound assignment operators
6467330f729Sjoerg         Ctx = VMap->clearDefinition(VDec, Ctx);
6477330f729Sjoerg       VMap->saveContext(BO, Ctx);
6487330f729Sjoerg     }
6497330f729Sjoerg   }
6507330f729Sjoerg }
6517330f729Sjoerg 
6527330f729Sjoerg // Computes the intersection of two contexts.  The intersection is the
6537330f729Sjoerg // set of variables which have the same definition in both contexts;
6547330f729Sjoerg // variables with different definitions are discarded.
6557330f729Sjoerg LocalVariableMap::Context
intersectContexts(Context C1,Context C2)6567330f729Sjoerg LocalVariableMap::intersectContexts(Context C1, Context C2) {
6577330f729Sjoerg   Context Result = C1;
6587330f729Sjoerg   for (const auto &P : C1) {
6597330f729Sjoerg     const NamedDecl *Dec = P.first;
6607330f729Sjoerg     const unsigned *i2 = C2.lookup(Dec);
6617330f729Sjoerg     if (!i2)             // variable doesn't exist on second path
6627330f729Sjoerg       Result = removeDefinition(Dec, Result);
6637330f729Sjoerg     else if (*i2 != P.second)  // variable exists, but has different definition
6647330f729Sjoerg       Result = clearDefinition(Dec, Result);
6657330f729Sjoerg   }
6667330f729Sjoerg   return Result;
6677330f729Sjoerg }
6687330f729Sjoerg 
6697330f729Sjoerg // For every variable in C, create a new variable that refers to the
6707330f729Sjoerg // definition in C.  Return a new context that contains these new variables.
6717330f729Sjoerg // (We use this for a naive implementation of SSA on loop back-edges.)
createReferenceContext(Context C)6727330f729Sjoerg LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
6737330f729Sjoerg   Context Result = getEmptyContext();
6747330f729Sjoerg   for (const auto &P : C)
6757330f729Sjoerg     Result = addReference(P.first, P.second, Result);
6767330f729Sjoerg   return Result;
6777330f729Sjoerg }
6787330f729Sjoerg 
6797330f729Sjoerg // This routine also takes the intersection of C1 and C2, but it does so by
6807330f729Sjoerg // altering the VarDefinitions.  C1 must be the result of an earlier call to
6817330f729Sjoerg // createReferenceContext.
intersectBackEdge(Context C1,Context C2)6827330f729Sjoerg void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
6837330f729Sjoerg   for (const auto &P : C1) {
6847330f729Sjoerg     unsigned i1 = P.second;
6857330f729Sjoerg     VarDefinition *VDef = &VarDefinitions[i1];
6867330f729Sjoerg     assert(VDef->isReference());
6877330f729Sjoerg 
6887330f729Sjoerg     const unsigned *i2 = C2.lookup(P.first);
6897330f729Sjoerg     if (!i2 || (*i2 != i1))
6907330f729Sjoerg       VDef->Ref = 0;    // Mark this variable as undefined
6917330f729Sjoerg   }
6927330f729Sjoerg }
6937330f729Sjoerg 
6947330f729Sjoerg // Traverse the CFG in topological order, so all predecessors of a block
6957330f729Sjoerg // (excluding back-edges) are visited before the block itself.  At
6967330f729Sjoerg // each point in the code, we calculate a Context, which holds the set of
6977330f729Sjoerg // variable definitions which are visible at that point in execution.
6987330f729Sjoerg // Visible variables are mapped to their definitions using an array that
6997330f729Sjoerg // contains all definitions.
7007330f729Sjoerg //
7017330f729Sjoerg // At join points in the CFG, the set is computed as the intersection of
7027330f729Sjoerg // the incoming sets along each edge, E.g.
7037330f729Sjoerg //
7047330f729Sjoerg //                       { Context                 | VarDefinitions }
7057330f729Sjoerg //   int x = 0;          { x -> x1                 | x1 = 0 }
7067330f729Sjoerg //   int y = 0;          { x -> x1, y -> y1        | y1 = 0, x1 = 0 }
7077330f729Sjoerg //   if (b) x = 1;       { x -> x2, y -> y1        | x2 = 1, y1 = 0, ... }
7087330f729Sjoerg //   else   x = 2;       { x -> x3, y -> y1        | x3 = 2, x2 = 1, ... }
7097330f729Sjoerg //   ...                 { y -> y1  (x is unknown) | x3 = 2, x2 = 1, ... }
7107330f729Sjoerg //
7117330f729Sjoerg // This is essentially a simpler and more naive version of the standard SSA
7127330f729Sjoerg // algorithm.  Those definitions that remain in the intersection are from blocks
7137330f729Sjoerg // that strictly dominate the current block.  We do not bother to insert proper
7147330f729Sjoerg // phi nodes, because they are not used in our analysis; instead, wherever
7157330f729Sjoerg // a phi node would be required, we simply remove that definition from the
7167330f729Sjoerg // context (E.g. x above).
7177330f729Sjoerg //
7187330f729Sjoerg // The initial traversal does not capture back-edges, so those need to be
7197330f729Sjoerg // handled on a separate pass.  Whenever the first pass encounters an
7207330f729Sjoerg // incoming back edge, it duplicates the context, creating new definitions
7217330f729Sjoerg // that refer back to the originals.  (These correspond to places where SSA
7227330f729Sjoerg // might have to insert a phi node.)  On the second pass, these definitions are
7237330f729Sjoerg // set to NULL if the variable has changed on the back-edge (i.e. a phi
7247330f729Sjoerg // node was actually required.)  E.g.
7257330f729Sjoerg //
7267330f729Sjoerg //                       { Context           | VarDefinitions }
7277330f729Sjoerg //   int x = 0, y = 0;   { x -> x1, y -> y1  | y1 = 0, x1 = 0 }
7287330f729Sjoerg //   while (b)           { x -> x2, y -> y1  | [1st:] x2=x1; [2nd:] x2=NULL; }
7297330f729Sjoerg //     x = x+1;          { x -> x3, y -> y1  | x3 = x2 + 1, ... }
7307330f729Sjoerg //   ...                 { y -> y1           | x3 = 2, x2 = 1, ... }
traverseCFG(CFG * CFGraph,const PostOrderCFGView * SortedGraph,std::vector<CFGBlockInfo> & BlockInfo)7317330f729Sjoerg void LocalVariableMap::traverseCFG(CFG *CFGraph,
7327330f729Sjoerg                                    const PostOrderCFGView *SortedGraph,
7337330f729Sjoerg                                    std::vector<CFGBlockInfo> &BlockInfo) {
7347330f729Sjoerg   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
7357330f729Sjoerg 
7367330f729Sjoerg   CtxIndices.resize(CFGraph->getNumBlockIDs());
7377330f729Sjoerg 
7387330f729Sjoerg   for (const auto *CurrBlock : *SortedGraph) {
7397330f729Sjoerg     unsigned CurrBlockID = CurrBlock->getBlockID();
7407330f729Sjoerg     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
7417330f729Sjoerg 
7427330f729Sjoerg     VisitedBlocks.insert(CurrBlock);
7437330f729Sjoerg 
7447330f729Sjoerg     // Calculate the entry context for the current block
7457330f729Sjoerg     bool HasBackEdges = false;
7467330f729Sjoerg     bool CtxInit = true;
7477330f729Sjoerg     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
7487330f729Sjoerg          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
7497330f729Sjoerg       // if *PI -> CurrBlock is a back edge, so skip it
7507330f729Sjoerg       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
7517330f729Sjoerg         HasBackEdges = true;
7527330f729Sjoerg         continue;
7537330f729Sjoerg       }
7547330f729Sjoerg 
7557330f729Sjoerg       unsigned PrevBlockID = (*PI)->getBlockID();
7567330f729Sjoerg       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
7577330f729Sjoerg 
7587330f729Sjoerg       if (CtxInit) {
7597330f729Sjoerg         CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
7607330f729Sjoerg         CtxInit = false;
7617330f729Sjoerg       }
7627330f729Sjoerg       else {
7637330f729Sjoerg         CurrBlockInfo->EntryContext =
7647330f729Sjoerg           intersectContexts(CurrBlockInfo->EntryContext,
7657330f729Sjoerg                             PrevBlockInfo->ExitContext);
7667330f729Sjoerg       }
7677330f729Sjoerg     }
7687330f729Sjoerg 
7697330f729Sjoerg     // Duplicate the context if we have back-edges, so we can call
7707330f729Sjoerg     // intersectBackEdges later.
7717330f729Sjoerg     if (HasBackEdges)
7727330f729Sjoerg       CurrBlockInfo->EntryContext =
7737330f729Sjoerg         createReferenceContext(CurrBlockInfo->EntryContext);
7747330f729Sjoerg 
7757330f729Sjoerg     // Create a starting context index for the current block
7767330f729Sjoerg     saveContext(nullptr, CurrBlockInfo->EntryContext);
7777330f729Sjoerg     CurrBlockInfo->EntryIndex = getContextIndex();
7787330f729Sjoerg 
7797330f729Sjoerg     // Visit all the statements in the basic block.
7807330f729Sjoerg     VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
7817330f729Sjoerg     for (const auto &BI : *CurrBlock) {
7827330f729Sjoerg       switch (BI.getKind()) {
7837330f729Sjoerg         case CFGElement::Statement: {
7847330f729Sjoerg           CFGStmt CS = BI.castAs<CFGStmt>();
7857330f729Sjoerg           VMapBuilder.Visit(CS.getStmt());
7867330f729Sjoerg           break;
7877330f729Sjoerg         }
7887330f729Sjoerg         default:
7897330f729Sjoerg           break;
7907330f729Sjoerg       }
7917330f729Sjoerg     }
7927330f729Sjoerg     CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
7937330f729Sjoerg 
7947330f729Sjoerg     // Mark variables on back edges as "unknown" if they've been changed.
7957330f729Sjoerg     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
7967330f729Sjoerg          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
7977330f729Sjoerg       // if CurrBlock -> *SI is *not* a back edge
7987330f729Sjoerg       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
7997330f729Sjoerg         continue;
8007330f729Sjoerg 
8017330f729Sjoerg       CFGBlock *FirstLoopBlock = *SI;
8027330f729Sjoerg       Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
8037330f729Sjoerg       Context LoopEnd   = CurrBlockInfo->ExitContext;
8047330f729Sjoerg       intersectBackEdge(LoopBegin, LoopEnd);
8057330f729Sjoerg     }
8067330f729Sjoerg   }
8077330f729Sjoerg 
8087330f729Sjoerg   // Put an extra entry at the end of the indexed context array
8097330f729Sjoerg   unsigned exitID = CFGraph->getExit().getBlockID();
8107330f729Sjoerg   saveContext(nullptr, BlockInfo[exitID].ExitContext);
8117330f729Sjoerg }
8127330f729Sjoerg 
8137330f729Sjoerg /// Find the appropriate source locations to use when producing diagnostics for
8147330f729Sjoerg /// each block in the CFG.
findBlockLocations(CFG * CFGraph,const PostOrderCFGView * SortedGraph,std::vector<CFGBlockInfo> & BlockInfo)8157330f729Sjoerg static void findBlockLocations(CFG *CFGraph,
8167330f729Sjoerg                                const PostOrderCFGView *SortedGraph,
8177330f729Sjoerg                                std::vector<CFGBlockInfo> &BlockInfo) {
8187330f729Sjoerg   for (const auto *CurrBlock : *SortedGraph) {
8197330f729Sjoerg     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
8207330f729Sjoerg 
8217330f729Sjoerg     // Find the source location of the last statement in the block, if the
8227330f729Sjoerg     // block is not empty.
8237330f729Sjoerg     if (const Stmt *S = CurrBlock->getTerminatorStmt()) {
8247330f729Sjoerg       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
8257330f729Sjoerg     } else {
8267330f729Sjoerg       for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
8277330f729Sjoerg            BE = CurrBlock->rend(); BI != BE; ++BI) {
8287330f729Sjoerg         // FIXME: Handle other CFGElement kinds.
8297330f729Sjoerg         if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
8307330f729Sjoerg           CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
8317330f729Sjoerg           break;
8327330f729Sjoerg         }
8337330f729Sjoerg       }
8347330f729Sjoerg     }
8357330f729Sjoerg 
8367330f729Sjoerg     if (CurrBlockInfo->ExitLoc.isValid()) {
8377330f729Sjoerg       // This block contains at least one statement. Find the source location
8387330f729Sjoerg       // of the first statement in the block.
8397330f729Sjoerg       for (const auto &BI : *CurrBlock) {
8407330f729Sjoerg         // FIXME: Handle other CFGElement kinds.
8417330f729Sjoerg         if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
8427330f729Sjoerg           CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
8437330f729Sjoerg           break;
8447330f729Sjoerg         }
8457330f729Sjoerg       }
8467330f729Sjoerg     } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
8477330f729Sjoerg                CurrBlock != &CFGraph->getExit()) {
8487330f729Sjoerg       // The block is empty, and has a single predecessor. Use its exit
8497330f729Sjoerg       // location.
8507330f729Sjoerg       CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
8517330f729Sjoerg           BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
8527330f729Sjoerg     }
8537330f729Sjoerg   }
8547330f729Sjoerg }
8557330f729Sjoerg 
8567330f729Sjoerg namespace {
8577330f729Sjoerg 
8587330f729Sjoerg class LockableFactEntry : public FactEntry {
8597330f729Sjoerg public:
LockableFactEntry(const CapabilityExpr & CE,LockKind LK,SourceLocation Loc,SourceKind Src=Acquired)8607330f729Sjoerg   LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
861*e038c9c4Sjoerg                     SourceKind Src = Acquired)
862*e038c9c4Sjoerg       : FactEntry(CE, LK, Loc, Src) {}
8637330f729Sjoerg 
8647330f729Sjoerg   void
handleRemovalFromIntersection(const FactSet & FSet,FactManager & FactMan,SourceLocation JoinLoc,LockErrorKind LEK,ThreadSafetyHandler & Handler) const8657330f729Sjoerg   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
8667330f729Sjoerg                                 SourceLocation JoinLoc, LockErrorKind LEK,
8677330f729Sjoerg                                 ThreadSafetyHandler &Handler) const override {
868*e038c9c4Sjoerg     if (!managed() && !asserted() && !negative() && !isUniversal()) {
8697330f729Sjoerg       Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
8707330f729Sjoerg                                         LEK);
8717330f729Sjoerg     }
8727330f729Sjoerg   }
8737330f729Sjoerg 
handleLock(FactSet & FSet,FactManager & FactMan,const FactEntry & entry,ThreadSafetyHandler & Handler,StringRef DiagKind) const8747330f729Sjoerg   void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
8757330f729Sjoerg                   ThreadSafetyHandler &Handler,
8767330f729Sjoerg                   StringRef DiagKind) const override {
8777330f729Sjoerg     Handler.handleDoubleLock(DiagKind, entry.toString(), loc(), entry.loc());
8787330f729Sjoerg   }
8797330f729Sjoerg 
handleUnlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,ThreadSafetyHandler & Handler,StringRef DiagKind) const8807330f729Sjoerg   void handleUnlock(FactSet &FSet, FactManager &FactMan,
8817330f729Sjoerg                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
8827330f729Sjoerg                     bool FullyRemove, ThreadSafetyHandler &Handler,
8837330f729Sjoerg                     StringRef DiagKind) const override {
8847330f729Sjoerg     FSet.removeLock(FactMan, Cp);
8857330f729Sjoerg     if (!Cp.negative()) {
8867330f729Sjoerg       FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
8877330f729Sjoerg                                 !Cp, LK_Exclusive, UnlockLoc));
8887330f729Sjoerg     }
8897330f729Sjoerg   }
8907330f729Sjoerg };
8917330f729Sjoerg 
8927330f729Sjoerg class ScopedLockableFactEntry : public FactEntry {
8937330f729Sjoerg private:
8947330f729Sjoerg   enum UnderlyingCapabilityKind {
8957330f729Sjoerg     UCK_Acquired,          ///< Any kind of acquired capability.
8967330f729Sjoerg     UCK_ReleasedShared,    ///< Shared capability that was released.
8977330f729Sjoerg     UCK_ReleasedExclusive, ///< Exclusive capability that was released.
8987330f729Sjoerg   };
8997330f729Sjoerg 
9007330f729Sjoerg   using UnderlyingCapability =
9017330f729Sjoerg       llvm::PointerIntPair<const til::SExpr *, 2, UnderlyingCapabilityKind>;
9027330f729Sjoerg 
9037330f729Sjoerg   SmallVector<UnderlyingCapability, 4> UnderlyingMutexes;
9047330f729Sjoerg 
9057330f729Sjoerg public:
ScopedLockableFactEntry(const CapabilityExpr & CE,SourceLocation Loc)9067330f729Sjoerg   ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc)
907*e038c9c4Sjoerg       : FactEntry(CE, LK_Exclusive, Loc, Acquired) {}
9087330f729Sjoerg 
addLock(const CapabilityExpr & M)909*e038c9c4Sjoerg   void addLock(const CapabilityExpr &M) {
9107330f729Sjoerg     UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
9117330f729Sjoerg   }
9127330f729Sjoerg 
addExclusiveUnlock(const CapabilityExpr & M)9137330f729Sjoerg   void addExclusiveUnlock(const CapabilityExpr &M) {
9147330f729Sjoerg     UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedExclusive);
9157330f729Sjoerg   }
9167330f729Sjoerg 
addSharedUnlock(const CapabilityExpr & M)9177330f729Sjoerg   void addSharedUnlock(const CapabilityExpr &M) {
9187330f729Sjoerg     UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedShared);
9197330f729Sjoerg   }
9207330f729Sjoerg 
9217330f729Sjoerg   void
handleRemovalFromIntersection(const FactSet & FSet,FactManager & FactMan,SourceLocation JoinLoc,LockErrorKind LEK,ThreadSafetyHandler & Handler) const9227330f729Sjoerg   handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
9237330f729Sjoerg                                 SourceLocation JoinLoc, LockErrorKind LEK,
9247330f729Sjoerg                                 ThreadSafetyHandler &Handler) const override {
9257330f729Sjoerg     for (const auto &UnderlyingMutex : UnderlyingMutexes) {
9267330f729Sjoerg       const auto *Entry = FSet.findLock(
9277330f729Sjoerg           FactMan, CapabilityExpr(UnderlyingMutex.getPointer(), false));
9287330f729Sjoerg       if ((UnderlyingMutex.getInt() == UCK_Acquired && Entry) ||
9297330f729Sjoerg           (UnderlyingMutex.getInt() != UCK_Acquired && !Entry)) {
9307330f729Sjoerg         // If this scoped lock manages another mutex, and if the underlying
9317330f729Sjoerg         // mutex is still/not held, then warn about the underlying mutex.
9327330f729Sjoerg         Handler.handleMutexHeldEndOfScope(
9337330f729Sjoerg             "mutex", sx::toString(UnderlyingMutex.getPointer()), loc(), JoinLoc,
9347330f729Sjoerg             LEK);
9357330f729Sjoerg       }
9367330f729Sjoerg     }
9377330f729Sjoerg   }
9387330f729Sjoerg 
handleLock(FactSet & FSet,FactManager & FactMan,const FactEntry & entry,ThreadSafetyHandler & Handler,StringRef DiagKind) const9397330f729Sjoerg   void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
9407330f729Sjoerg                   ThreadSafetyHandler &Handler,
9417330f729Sjoerg                   StringRef DiagKind) const override {
9427330f729Sjoerg     for (const auto &UnderlyingMutex : UnderlyingMutexes) {
9437330f729Sjoerg       CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
9447330f729Sjoerg 
9457330f729Sjoerg       if (UnderlyingMutex.getInt() == UCK_Acquired)
9467330f729Sjoerg         lock(FSet, FactMan, UnderCp, entry.kind(), entry.loc(), &Handler,
9477330f729Sjoerg              DiagKind);
9487330f729Sjoerg       else
9497330f729Sjoerg         unlock(FSet, FactMan, UnderCp, entry.loc(), &Handler, DiagKind);
9507330f729Sjoerg     }
9517330f729Sjoerg   }
9527330f729Sjoerg 
handleUnlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,ThreadSafetyHandler & Handler,StringRef DiagKind) const9537330f729Sjoerg   void handleUnlock(FactSet &FSet, FactManager &FactMan,
9547330f729Sjoerg                     const CapabilityExpr &Cp, SourceLocation UnlockLoc,
9557330f729Sjoerg                     bool FullyRemove, ThreadSafetyHandler &Handler,
9567330f729Sjoerg                     StringRef DiagKind) const override {
9577330f729Sjoerg     assert(!Cp.negative() && "Managing object cannot be negative.");
9587330f729Sjoerg     for (const auto &UnderlyingMutex : UnderlyingMutexes) {
9597330f729Sjoerg       CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
9607330f729Sjoerg 
9617330f729Sjoerg       // Remove/lock the underlying mutex if it exists/is still unlocked; warn
9627330f729Sjoerg       // on double unlocking/locking if we're not destroying the scoped object.
9637330f729Sjoerg       ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler;
9647330f729Sjoerg       if (UnderlyingMutex.getInt() == UCK_Acquired) {
9657330f729Sjoerg         unlock(FSet, FactMan, UnderCp, UnlockLoc, TSHandler, DiagKind);
9667330f729Sjoerg       } else {
9677330f729Sjoerg         LockKind kind = UnderlyingMutex.getInt() == UCK_ReleasedShared
9687330f729Sjoerg                             ? LK_Shared
9697330f729Sjoerg                             : LK_Exclusive;
9707330f729Sjoerg         lock(FSet, FactMan, UnderCp, kind, UnlockLoc, TSHandler, DiagKind);
9717330f729Sjoerg       }
9727330f729Sjoerg     }
9737330f729Sjoerg     if (FullyRemove)
9747330f729Sjoerg       FSet.removeLock(FactMan, Cp);
9757330f729Sjoerg   }
9767330f729Sjoerg 
9777330f729Sjoerg private:
lock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,LockKind kind,SourceLocation loc,ThreadSafetyHandler * Handler,StringRef DiagKind) const9787330f729Sjoerg   void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
9797330f729Sjoerg             LockKind kind, SourceLocation loc, ThreadSafetyHandler *Handler,
9807330f729Sjoerg             StringRef DiagKind) const {
9817330f729Sjoerg     if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
9827330f729Sjoerg       if (Handler)
9837330f729Sjoerg         Handler->handleDoubleLock(DiagKind, Cp.toString(), Fact->loc(), loc);
9847330f729Sjoerg     } else {
9857330f729Sjoerg       FSet.removeLock(FactMan, !Cp);
9867330f729Sjoerg       FSet.addLock(FactMan,
987*e038c9c4Sjoerg                    std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed));
9887330f729Sjoerg     }
9897330f729Sjoerg   }
9907330f729Sjoerg 
unlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation loc,ThreadSafetyHandler * Handler,StringRef DiagKind) const9917330f729Sjoerg   void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
9927330f729Sjoerg               SourceLocation loc, ThreadSafetyHandler *Handler,
9937330f729Sjoerg               StringRef DiagKind) const {
9947330f729Sjoerg     if (FSet.findLock(FactMan, Cp)) {
9957330f729Sjoerg       FSet.removeLock(FactMan, Cp);
9967330f729Sjoerg       FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
9977330f729Sjoerg                                 !Cp, LK_Exclusive, loc));
9987330f729Sjoerg     } else if (Handler) {
999*e038c9c4Sjoerg       SourceLocation PrevLoc;
1000*e038c9c4Sjoerg       if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
1001*e038c9c4Sjoerg         PrevLoc = Neg->loc();
1002*e038c9c4Sjoerg       Handler->handleUnmatchedUnlock(DiagKind, Cp.toString(), loc, PrevLoc);
10037330f729Sjoerg     }
10047330f729Sjoerg   }
10057330f729Sjoerg };
10067330f729Sjoerg 
10077330f729Sjoerg /// Class which implements the core thread safety analysis routines.
10087330f729Sjoerg class ThreadSafetyAnalyzer {
10097330f729Sjoerg   friend class BuildLockset;
10107330f729Sjoerg   friend class threadSafety::BeforeSet;
10117330f729Sjoerg 
10127330f729Sjoerg   llvm::BumpPtrAllocator Bpa;
10137330f729Sjoerg   threadSafety::til::MemRegionRef Arena;
10147330f729Sjoerg   threadSafety::SExprBuilder SxBuilder;
10157330f729Sjoerg 
10167330f729Sjoerg   ThreadSafetyHandler &Handler;
10177330f729Sjoerg   const CXXMethodDecl *CurrentMethod;
10187330f729Sjoerg   LocalVariableMap LocalVarMap;
10197330f729Sjoerg   FactManager FactMan;
10207330f729Sjoerg   std::vector<CFGBlockInfo> BlockInfo;
10217330f729Sjoerg 
10227330f729Sjoerg   BeforeSet *GlobalBeforeSet;
10237330f729Sjoerg 
10247330f729Sjoerg public:
ThreadSafetyAnalyzer(ThreadSafetyHandler & H,BeforeSet * Bset)10257330f729Sjoerg   ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
10267330f729Sjoerg       : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
10277330f729Sjoerg 
10287330f729Sjoerg   bool inCurrentScope(const CapabilityExpr &CapE);
10297330f729Sjoerg 
10307330f729Sjoerg   void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
10317330f729Sjoerg                StringRef DiagKind, bool ReqAttr = false);
10327330f729Sjoerg   void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
10337330f729Sjoerg                   SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
10347330f729Sjoerg                   StringRef DiagKind);
10357330f729Sjoerg 
10367330f729Sjoerg   template <typename AttrType>
10377330f729Sjoerg   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
10387330f729Sjoerg                    const NamedDecl *D, VarDecl *SelfDecl = nullptr);
10397330f729Sjoerg 
10407330f729Sjoerg   template <class AttrType>
10417330f729Sjoerg   void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
10427330f729Sjoerg                    const NamedDecl *D,
10437330f729Sjoerg                    const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
10447330f729Sjoerg                    Expr *BrE, bool Neg);
10457330f729Sjoerg 
10467330f729Sjoerg   const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
10477330f729Sjoerg                                      bool &Negate);
10487330f729Sjoerg 
10497330f729Sjoerg   void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
10507330f729Sjoerg                       const CFGBlock* PredBlock,
10517330f729Sjoerg                       const CFGBlock *CurrBlock);
10527330f729Sjoerg 
10537330f729Sjoerg   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1054*e038c9c4Sjoerg                         SourceLocation JoinLoc, LockErrorKind LEK1,
1055*e038c9c4Sjoerg                         LockErrorKind LEK2);
10567330f729Sjoerg 
intersectAndWarn(FactSet & FSet1,const FactSet & FSet2,SourceLocation JoinLoc,LockErrorKind LEK1)10577330f729Sjoerg   void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1058*e038c9c4Sjoerg                         SourceLocation JoinLoc, LockErrorKind LEK1) {
1059*e038c9c4Sjoerg     intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1);
10607330f729Sjoerg   }
10617330f729Sjoerg 
10627330f729Sjoerg   void runAnalysis(AnalysisDeclContext &AC);
10637330f729Sjoerg };
10647330f729Sjoerg 
10657330f729Sjoerg } // namespace
10667330f729Sjoerg 
10677330f729Sjoerg /// Process acquired_before and acquired_after attributes on Vd.
insertAttrExprs(const ValueDecl * Vd,ThreadSafetyAnalyzer & Analyzer)10687330f729Sjoerg BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
10697330f729Sjoerg     ThreadSafetyAnalyzer& Analyzer) {
10707330f729Sjoerg   // Create a new entry for Vd.
10717330f729Sjoerg   BeforeInfo *Info = nullptr;
10727330f729Sjoerg   {
10737330f729Sjoerg     // Keep InfoPtr in its own scope in case BMap is modified later and the
10747330f729Sjoerg     // reference becomes invalid.
10757330f729Sjoerg     std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
10767330f729Sjoerg     if (!InfoPtr)
10777330f729Sjoerg       InfoPtr.reset(new BeforeInfo());
10787330f729Sjoerg     Info = InfoPtr.get();
10797330f729Sjoerg   }
10807330f729Sjoerg 
10817330f729Sjoerg   for (const auto *At : Vd->attrs()) {
10827330f729Sjoerg     switch (At->getKind()) {
10837330f729Sjoerg       case attr::AcquiredBefore: {
10847330f729Sjoerg         const auto *A = cast<AcquiredBeforeAttr>(At);
10857330f729Sjoerg 
10867330f729Sjoerg         // Read exprs from the attribute, and add them to BeforeVect.
10877330f729Sjoerg         for (const auto *Arg : A->args()) {
10887330f729Sjoerg           CapabilityExpr Cp =
10897330f729Sjoerg             Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
10907330f729Sjoerg           if (const ValueDecl *Cpvd = Cp.valueDecl()) {
10917330f729Sjoerg             Info->Vect.push_back(Cpvd);
10927330f729Sjoerg             const auto It = BMap.find(Cpvd);
10937330f729Sjoerg             if (It == BMap.end())
10947330f729Sjoerg               insertAttrExprs(Cpvd, Analyzer);
10957330f729Sjoerg           }
10967330f729Sjoerg         }
10977330f729Sjoerg         break;
10987330f729Sjoerg       }
10997330f729Sjoerg       case attr::AcquiredAfter: {
11007330f729Sjoerg         const auto *A = cast<AcquiredAfterAttr>(At);
11017330f729Sjoerg 
11027330f729Sjoerg         // Read exprs from the attribute, and add them to BeforeVect.
11037330f729Sjoerg         for (const auto *Arg : A->args()) {
11047330f729Sjoerg           CapabilityExpr Cp =
11057330f729Sjoerg             Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
11067330f729Sjoerg           if (const ValueDecl *ArgVd = Cp.valueDecl()) {
11077330f729Sjoerg             // Get entry for mutex listed in attribute
11087330f729Sjoerg             BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
11097330f729Sjoerg             ArgInfo->Vect.push_back(Vd);
11107330f729Sjoerg           }
11117330f729Sjoerg         }
11127330f729Sjoerg         break;
11137330f729Sjoerg       }
11147330f729Sjoerg       default:
11157330f729Sjoerg         break;
11167330f729Sjoerg     }
11177330f729Sjoerg   }
11187330f729Sjoerg 
11197330f729Sjoerg   return Info;
11207330f729Sjoerg }
11217330f729Sjoerg 
11227330f729Sjoerg BeforeSet::BeforeInfo *
getBeforeInfoForDecl(const ValueDecl * Vd,ThreadSafetyAnalyzer & Analyzer)11237330f729Sjoerg BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
11247330f729Sjoerg                                 ThreadSafetyAnalyzer &Analyzer) {
11257330f729Sjoerg   auto It = BMap.find(Vd);
11267330f729Sjoerg   BeforeInfo *Info = nullptr;
11277330f729Sjoerg   if (It == BMap.end())
11287330f729Sjoerg     Info = insertAttrExprs(Vd, Analyzer);
11297330f729Sjoerg   else
11307330f729Sjoerg     Info = It->second.get();
11317330f729Sjoerg   assert(Info && "BMap contained nullptr?");
11327330f729Sjoerg   return Info;
11337330f729Sjoerg }
11347330f729Sjoerg 
11357330f729Sjoerg /// 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)11367330f729Sjoerg void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
11377330f729Sjoerg                                  const FactSet& FSet,
11387330f729Sjoerg                                  ThreadSafetyAnalyzer& Analyzer,
11397330f729Sjoerg                                  SourceLocation Loc, StringRef CapKind) {
11407330f729Sjoerg   SmallVector<BeforeInfo*, 8> InfoVect;
11417330f729Sjoerg 
11427330f729Sjoerg   // Do a depth-first traversal of Vd.
11437330f729Sjoerg   // Return true if there are cycles.
11447330f729Sjoerg   std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
11457330f729Sjoerg     if (!Vd)
11467330f729Sjoerg       return false;
11477330f729Sjoerg 
11487330f729Sjoerg     BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
11497330f729Sjoerg 
11507330f729Sjoerg     if (Info->Visited == 1)
11517330f729Sjoerg       return true;
11527330f729Sjoerg 
11537330f729Sjoerg     if (Info->Visited == 2)
11547330f729Sjoerg       return false;
11557330f729Sjoerg 
11567330f729Sjoerg     if (Info->Vect.empty())
11577330f729Sjoerg       return false;
11587330f729Sjoerg 
11597330f729Sjoerg     InfoVect.push_back(Info);
11607330f729Sjoerg     Info->Visited = 1;
11617330f729Sjoerg     for (const auto *Vdb : Info->Vect) {
11627330f729Sjoerg       // Exclude mutexes in our immediate before set.
11637330f729Sjoerg       if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
11647330f729Sjoerg         StringRef L1 = StartVd->getName();
11657330f729Sjoerg         StringRef L2 = Vdb->getName();
11667330f729Sjoerg         Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
11677330f729Sjoerg       }
11687330f729Sjoerg       // Transitively search other before sets, and warn on cycles.
11697330f729Sjoerg       if (traverse(Vdb)) {
11707330f729Sjoerg         if (CycMap.find(Vd) == CycMap.end()) {
11717330f729Sjoerg           CycMap.insert(std::make_pair(Vd, true));
11727330f729Sjoerg           StringRef L1 = Vd->getName();
11737330f729Sjoerg           Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
11747330f729Sjoerg         }
11757330f729Sjoerg       }
11767330f729Sjoerg     }
11777330f729Sjoerg     Info->Visited = 2;
11787330f729Sjoerg     return false;
11797330f729Sjoerg   };
11807330f729Sjoerg 
11817330f729Sjoerg   traverse(StartVd);
11827330f729Sjoerg 
11837330f729Sjoerg   for (auto *Info : InfoVect)
11847330f729Sjoerg     Info->Visited = 0;
11857330f729Sjoerg }
11867330f729Sjoerg 
11877330f729Sjoerg /// Gets the value decl pointer from DeclRefExprs or MemberExprs.
getValueDecl(const Expr * Exp)11887330f729Sjoerg static const ValueDecl *getValueDecl(const Expr *Exp) {
11897330f729Sjoerg   if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
11907330f729Sjoerg     return getValueDecl(CE->getSubExpr());
11917330f729Sjoerg 
11927330f729Sjoerg   if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
11937330f729Sjoerg     return DR->getDecl();
11947330f729Sjoerg 
11957330f729Sjoerg   if (const auto *ME = dyn_cast<MemberExpr>(Exp))
11967330f729Sjoerg     return ME->getMemberDecl();
11977330f729Sjoerg 
11987330f729Sjoerg   return nullptr;
11997330f729Sjoerg }
12007330f729Sjoerg 
12017330f729Sjoerg namespace {
12027330f729Sjoerg 
12037330f729Sjoerg template <typename Ty>
12047330f729Sjoerg class has_arg_iterator_range {
12057330f729Sjoerg   using yes = char[1];
12067330f729Sjoerg   using no = char[2];
12077330f729Sjoerg 
12087330f729Sjoerg   template <typename Inner>
12097330f729Sjoerg   static yes& test(Inner *I, decltype(I->args()) * = nullptr);
12107330f729Sjoerg 
12117330f729Sjoerg   template <typename>
12127330f729Sjoerg   static no& test(...);
12137330f729Sjoerg 
12147330f729Sjoerg public:
12157330f729Sjoerg   static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
12167330f729Sjoerg };
12177330f729Sjoerg 
12187330f729Sjoerg } // namespace
12197330f729Sjoerg 
ClassifyDiagnostic(const CapabilityAttr * A)12207330f729Sjoerg static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
12217330f729Sjoerg   return A->getName();
12227330f729Sjoerg }
12237330f729Sjoerg 
ClassifyDiagnostic(QualType VDT)12247330f729Sjoerg static StringRef ClassifyDiagnostic(QualType VDT) {
12257330f729Sjoerg   // We need to look at the declaration of the type of the value to determine
12267330f729Sjoerg   // which it is. The type should either be a record or a typedef, or a pointer
12277330f729Sjoerg   // or reference thereof.
12287330f729Sjoerg   if (const auto *RT = VDT->getAs<RecordType>()) {
12297330f729Sjoerg     if (const auto *RD = RT->getDecl())
12307330f729Sjoerg       if (const auto *CA = RD->getAttr<CapabilityAttr>())
12317330f729Sjoerg         return ClassifyDiagnostic(CA);
12327330f729Sjoerg   } else if (const auto *TT = VDT->getAs<TypedefType>()) {
12337330f729Sjoerg     if (const auto *TD = TT->getDecl())
12347330f729Sjoerg       if (const auto *CA = TD->getAttr<CapabilityAttr>())
12357330f729Sjoerg         return ClassifyDiagnostic(CA);
12367330f729Sjoerg   } else if (VDT->isPointerType() || VDT->isReferenceType())
12377330f729Sjoerg     return ClassifyDiagnostic(VDT->getPointeeType());
12387330f729Sjoerg 
12397330f729Sjoerg   return "mutex";
12407330f729Sjoerg }
12417330f729Sjoerg 
ClassifyDiagnostic(const ValueDecl * VD)12427330f729Sjoerg static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
12437330f729Sjoerg   assert(VD && "No ValueDecl passed");
12447330f729Sjoerg 
12457330f729Sjoerg   // The ValueDecl is the declaration of a mutex or role (hopefully).
12467330f729Sjoerg   return ClassifyDiagnostic(VD->getType());
12477330f729Sjoerg }
12487330f729Sjoerg 
12497330f729Sjoerg template <typename AttrTy>
1250*e038c9c4Sjoerg static std::enable_if_t<!has_arg_iterator_range<AttrTy>::value, StringRef>
ClassifyDiagnostic(const AttrTy * A)12517330f729Sjoerg ClassifyDiagnostic(const AttrTy *A) {
12527330f729Sjoerg   if (const ValueDecl *VD = getValueDecl(A->getArg()))
12537330f729Sjoerg     return ClassifyDiagnostic(VD);
12547330f729Sjoerg   return "mutex";
12557330f729Sjoerg }
12567330f729Sjoerg 
12577330f729Sjoerg template <typename AttrTy>
1258*e038c9c4Sjoerg static std::enable_if_t<has_arg_iterator_range<AttrTy>::value, StringRef>
ClassifyDiagnostic(const AttrTy * A)12597330f729Sjoerg ClassifyDiagnostic(const AttrTy *A) {
12607330f729Sjoerg   for (const auto *Arg : A->args()) {
12617330f729Sjoerg     if (const ValueDecl *VD = getValueDecl(Arg))
12627330f729Sjoerg       return ClassifyDiagnostic(VD);
12637330f729Sjoerg   }
12647330f729Sjoerg   return "mutex";
12657330f729Sjoerg }
12667330f729Sjoerg 
inCurrentScope(const CapabilityExpr & CapE)12677330f729Sjoerg bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1268*e038c9c4Sjoerg   const threadSafety::til::SExpr *SExp = CapE.sexpr();
1269*e038c9c4Sjoerg   assert(SExp && "Null expressions should be ignored");
1270*e038c9c4Sjoerg 
1271*e038c9c4Sjoerg   if (const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) {
1272*e038c9c4Sjoerg     const ValueDecl *VD = LP->clangDecl();
1273*e038c9c4Sjoerg     // Variables defined in a function are always inaccessible.
1274*e038c9c4Sjoerg     if (!VD->isDefinedOutsideFunctionOrMethod())
1275*e038c9c4Sjoerg       return false;
1276*e038c9c4Sjoerg     // For now we consider static class members to be inaccessible.
1277*e038c9c4Sjoerg     if (isa<CXXRecordDecl>(VD->getDeclContext()))
1278*e038c9c4Sjoerg       return false;
1279*e038c9c4Sjoerg     // Global variables are always in scope.
1280*e038c9c4Sjoerg     return true;
1281*e038c9c4Sjoerg   }
1282*e038c9c4Sjoerg 
1283*e038c9c4Sjoerg   // Members are in scope from methods of the same class.
1284*e038c9c4Sjoerg   if (const auto *P = dyn_cast<til::Project>(SExp)) {
12857330f729Sjoerg     if (!CurrentMethod)
12867330f729Sjoerg       return false;
1287*e038c9c4Sjoerg     const ValueDecl *VD = P->clangDecl();
12887330f729Sjoerg     return VD->getDeclContext() == CurrentMethod->getDeclContext();
12897330f729Sjoerg   }
1290*e038c9c4Sjoerg 
12917330f729Sjoerg   return false;
12927330f729Sjoerg }
12937330f729Sjoerg 
12947330f729Sjoerg /// Add a new lock to the lockset, warning if the lock is already there.
12957330f729Sjoerg /// \param ReqAttr -- true if this is part of an initial Requires attribute.
addLock(FactSet & FSet,std::unique_ptr<FactEntry> Entry,StringRef DiagKind,bool ReqAttr)12967330f729Sjoerg void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
12977330f729Sjoerg                                    std::unique_ptr<FactEntry> Entry,
12987330f729Sjoerg                                    StringRef DiagKind, bool ReqAttr) {
12997330f729Sjoerg   if (Entry->shouldIgnore())
13007330f729Sjoerg     return;
13017330f729Sjoerg 
13027330f729Sjoerg   if (!ReqAttr && !Entry->negative()) {
13037330f729Sjoerg     // look for the negative capability, and remove it from the fact set.
13047330f729Sjoerg     CapabilityExpr NegC = !*Entry;
13057330f729Sjoerg     const FactEntry *Nen = FSet.findLock(FactMan, NegC);
13067330f729Sjoerg     if (Nen) {
13077330f729Sjoerg       FSet.removeLock(FactMan, NegC);
13087330f729Sjoerg     }
13097330f729Sjoerg     else {
13107330f729Sjoerg       if (inCurrentScope(*Entry) && !Entry->asserted())
13117330f729Sjoerg         Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
13127330f729Sjoerg                                       NegC.toString(), Entry->loc());
13137330f729Sjoerg     }
13147330f729Sjoerg   }
13157330f729Sjoerg 
13167330f729Sjoerg   // Check before/after constraints
13177330f729Sjoerg   if (Handler.issueBetaWarnings() &&
13187330f729Sjoerg       !Entry->asserted() && !Entry->declared()) {
13197330f729Sjoerg     GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
13207330f729Sjoerg                                       Entry->loc(), DiagKind);
13217330f729Sjoerg   }
13227330f729Sjoerg 
13237330f729Sjoerg   // FIXME: Don't always warn when we have support for reentrant locks.
13247330f729Sjoerg   if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
13257330f729Sjoerg     if (!Entry->asserted())
13267330f729Sjoerg       Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind);
13277330f729Sjoerg   } else {
13287330f729Sjoerg     FSet.addLock(FactMan, std::move(Entry));
13297330f729Sjoerg   }
13307330f729Sjoerg }
13317330f729Sjoerg 
13327330f729Sjoerg /// Remove a lock from the lockset, warning if the lock is not there.
13337330f729Sjoerg /// \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)13347330f729Sjoerg void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
13357330f729Sjoerg                                       SourceLocation UnlockLoc,
13367330f729Sjoerg                                       bool FullyRemove, LockKind ReceivedKind,
13377330f729Sjoerg                                       StringRef DiagKind) {
13387330f729Sjoerg   if (Cp.shouldIgnore())
13397330f729Sjoerg     return;
13407330f729Sjoerg 
13417330f729Sjoerg   const FactEntry *LDat = FSet.findLock(FactMan, Cp);
13427330f729Sjoerg   if (!LDat) {
1343*e038c9c4Sjoerg     SourceLocation PrevLoc;
1344*e038c9c4Sjoerg     if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
1345*e038c9c4Sjoerg       PrevLoc = Neg->loc();
1346*e038c9c4Sjoerg     Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc, PrevLoc);
13477330f729Sjoerg     return;
13487330f729Sjoerg   }
13497330f729Sjoerg 
13507330f729Sjoerg   // Generic lock removal doesn't care about lock kind mismatches, but
13517330f729Sjoerg   // otherwise diagnose when the lock kinds are mismatched.
13527330f729Sjoerg   if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
13537330f729Sjoerg     Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(), LDat->kind(),
13547330f729Sjoerg                                       ReceivedKind, LDat->loc(), UnlockLoc);
13557330f729Sjoerg   }
13567330f729Sjoerg 
13577330f729Sjoerg   LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
13587330f729Sjoerg                      DiagKind);
13597330f729Sjoerg }
13607330f729Sjoerg 
13617330f729Sjoerg /// Extract the list of mutexIDs from the attribute on an expression,
13627330f729Sjoerg /// and push them onto Mtxs, discarding any duplicates.
13637330f729Sjoerg template <typename AttrType>
getMutexIDs(CapExprSet & Mtxs,AttrType * Attr,const Expr * Exp,const NamedDecl * D,VarDecl * SelfDecl)13647330f729Sjoerg void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
13657330f729Sjoerg                                        const Expr *Exp, const NamedDecl *D,
13667330f729Sjoerg                                        VarDecl *SelfDecl) {
13677330f729Sjoerg   if (Attr->args_size() == 0) {
13687330f729Sjoerg     // The mutex held is the "this" object.
13697330f729Sjoerg     CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
13707330f729Sjoerg     if (Cp.isInvalid()) {
13717330f729Sjoerg        warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
13727330f729Sjoerg        return;
13737330f729Sjoerg     }
13747330f729Sjoerg     //else
13757330f729Sjoerg     if (!Cp.shouldIgnore())
13767330f729Sjoerg       Mtxs.push_back_nodup(Cp);
13777330f729Sjoerg     return;
13787330f729Sjoerg   }
13797330f729Sjoerg 
13807330f729Sjoerg   for (const auto *Arg : Attr->args()) {
13817330f729Sjoerg     CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
13827330f729Sjoerg     if (Cp.isInvalid()) {
13837330f729Sjoerg        warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
13847330f729Sjoerg        continue;
13857330f729Sjoerg     }
13867330f729Sjoerg     //else
13877330f729Sjoerg     if (!Cp.shouldIgnore())
13887330f729Sjoerg       Mtxs.push_back_nodup(Cp);
13897330f729Sjoerg   }
13907330f729Sjoerg }
13917330f729Sjoerg 
13927330f729Sjoerg /// Extract the list of mutexIDs from a trylock attribute.  If the
13937330f729Sjoerg /// trylock applies to the given edge, then push them onto Mtxs, discarding
13947330f729Sjoerg /// any duplicates.
13957330f729Sjoerg template <class AttrType>
getMutexIDs(CapExprSet & Mtxs,AttrType * Attr,const Expr * Exp,const NamedDecl * D,const CFGBlock * PredBlock,const CFGBlock * CurrBlock,Expr * BrE,bool Neg)13967330f729Sjoerg void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
13977330f729Sjoerg                                        const Expr *Exp, const NamedDecl *D,
13987330f729Sjoerg                                        const CFGBlock *PredBlock,
13997330f729Sjoerg                                        const CFGBlock *CurrBlock,
14007330f729Sjoerg                                        Expr *BrE, bool Neg) {
14017330f729Sjoerg   // Find out which branch has the lock
14027330f729Sjoerg   bool branch = false;
14037330f729Sjoerg   if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
14047330f729Sjoerg     branch = BLE->getValue();
14057330f729Sjoerg   else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
14067330f729Sjoerg     branch = ILE->getValue().getBoolValue();
14077330f729Sjoerg 
14087330f729Sjoerg   int branchnum = branch ? 0 : 1;
14097330f729Sjoerg   if (Neg)
14107330f729Sjoerg     branchnum = !branchnum;
14117330f729Sjoerg 
14127330f729Sjoerg   // If we've taken the trylock branch, then add the lock
14137330f729Sjoerg   int i = 0;
14147330f729Sjoerg   for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
14157330f729Sjoerg        SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
14167330f729Sjoerg     if (*SI == CurrBlock && i == branchnum)
14177330f729Sjoerg       getMutexIDs(Mtxs, Attr, Exp, D);
14187330f729Sjoerg   }
14197330f729Sjoerg }
14207330f729Sjoerg 
getStaticBooleanValue(Expr * E,bool & TCond)14217330f729Sjoerg static bool getStaticBooleanValue(Expr *E, bool &TCond) {
14227330f729Sjoerg   if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
14237330f729Sjoerg     TCond = false;
14247330f729Sjoerg     return true;
14257330f729Sjoerg   } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
14267330f729Sjoerg     TCond = BLE->getValue();
14277330f729Sjoerg     return true;
14287330f729Sjoerg   } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
14297330f729Sjoerg     TCond = ILE->getValue().getBoolValue();
14307330f729Sjoerg     return true;
14317330f729Sjoerg   } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
14327330f729Sjoerg     return getStaticBooleanValue(CE->getSubExpr(), TCond);
14337330f729Sjoerg   return false;
14347330f729Sjoerg }
14357330f729Sjoerg 
14367330f729Sjoerg // If Cond can be traced back to a function call, return the call expression.
14377330f729Sjoerg // The negate variable should be called with false, and will be set to true
14387330f729Sjoerg // if the function call is negated, e.g. if (!mu.tryLock(...))
getTrylockCallExpr(const Stmt * Cond,LocalVarContext C,bool & Negate)14397330f729Sjoerg const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
14407330f729Sjoerg                                                          LocalVarContext C,
14417330f729Sjoerg                                                          bool &Negate) {
14427330f729Sjoerg   if (!Cond)
14437330f729Sjoerg     return nullptr;
14447330f729Sjoerg 
14457330f729Sjoerg   if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
14467330f729Sjoerg     if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
14477330f729Sjoerg       return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
14487330f729Sjoerg     return CallExp;
14497330f729Sjoerg   }
14507330f729Sjoerg   else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
14517330f729Sjoerg     return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
14527330f729Sjoerg   else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
14537330f729Sjoerg     return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
14547330f729Sjoerg   else if (const auto *FE = dyn_cast<FullExpr>(Cond))
14557330f729Sjoerg     return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
14567330f729Sjoerg   else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
14577330f729Sjoerg     const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
14587330f729Sjoerg     return getTrylockCallExpr(E, C, Negate);
14597330f729Sjoerg   }
14607330f729Sjoerg   else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
14617330f729Sjoerg     if (UOP->getOpcode() == UO_LNot) {
14627330f729Sjoerg       Negate = !Negate;
14637330f729Sjoerg       return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
14647330f729Sjoerg     }
14657330f729Sjoerg     return nullptr;
14667330f729Sjoerg   }
14677330f729Sjoerg   else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
14687330f729Sjoerg     if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
14697330f729Sjoerg       if (BOP->getOpcode() == BO_NE)
14707330f729Sjoerg         Negate = !Negate;
14717330f729Sjoerg 
14727330f729Sjoerg       bool TCond = false;
14737330f729Sjoerg       if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
14747330f729Sjoerg         if (!TCond) Negate = !Negate;
14757330f729Sjoerg         return getTrylockCallExpr(BOP->getLHS(), C, Negate);
14767330f729Sjoerg       }
14777330f729Sjoerg       TCond = false;
14787330f729Sjoerg       if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
14797330f729Sjoerg         if (!TCond) Negate = !Negate;
14807330f729Sjoerg         return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14817330f729Sjoerg       }
14827330f729Sjoerg       return nullptr;
14837330f729Sjoerg     }
14847330f729Sjoerg     if (BOP->getOpcode() == BO_LAnd) {
14857330f729Sjoerg       // LHS must have been evaluated in a different block.
14867330f729Sjoerg       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14877330f729Sjoerg     }
14887330f729Sjoerg     if (BOP->getOpcode() == BO_LOr)
14897330f729Sjoerg       return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14907330f729Sjoerg     return nullptr;
14917330f729Sjoerg   } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
14927330f729Sjoerg     bool TCond, FCond;
14937330f729Sjoerg     if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
14947330f729Sjoerg         getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
14957330f729Sjoerg       if (TCond && !FCond)
14967330f729Sjoerg         return getTrylockCallExpr(COP->getCond(), C, Negate);
14977330f729Sjoerg       if (!TCond && FCond) {
14987330f729Sjoerg         Negate = !Negate;
14997330f729Sjoerg         return getTrylockCallExpr(COP->getCond(), C, Negate);
15007330f729Sjoerg       }
15017330f729Sjoerg     }
15027330f729Sjoerg   }
15037330f729Sjoerg   return nullptr;
15047330f729Sjoerg }
15057330f729Sjoerg 
15067330f729Sjoerg /// Find the lockset that holds on the edge between PredBlock
15077330f729Sjoerg /// and CurrBlock.  The edge set is the exit set of PredBlock (passed
15087330f729Sjoerg /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
getEdgeLockset(FactSet & Result,const FactSet & ExitSet,const CFGBlock * PredBlock,const CFGBlock * CurrBlock)15097330f729Sjoerg void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
15107330f729Sjoerg                                           const FactSet &ExitSet,
15117330f729Sjoerg                                           const CFGBlock *PredBlock,
15127330f729Sjoerg                                           const CFGBlock *CurrBlock) {
15137330f729Sjoerg   Result = ExitSet;
15147330f729Sjoerg 
15157330f729Sjoerg   const Stmt *Cond = PredBlock->getTerminatorCondition();
15167330f729Sjoerg   // We don't acquire try-locks on ?: branches, only when its result is used.
15177330f729Sjoerg   if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminatorStmt()))
15187330f729Sjoerg     return;
15197330f729Sjoerg 
15207330f729Sjoerg   bool Negate = false;
15217330f729Sjoerg   const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
15227330f729Sjoerg   const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
15237330f729Sjoerg   StringRef CapDiagKind = "mutex";
15247330f729Sjoerg 
15257330f729Sjoerg   const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
15267330f729Sjoerg   if (!Exp)
15277330f729Sjoerg     return;
15287330f729Sjoerg 
15297330f729Sjoerg   auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
15307330f729Sjoerg   if(!FunDecl || !FunDecl->hasAttrs())
15317330f729Sjoerg     return;
15327330f729Sjoerg 
15337330f729Sjoerg   CapExprSet ExclusiveLocksToAdd;
15347330f729Sjoerg   CapExprSet SharedLocksToAdd;
15357330f729Sjoerg 
15367330f729Sjoerg   // If the condition is a call to a Trylock function, then grab the attributes
15377330f729Sjoerg   for (const auto *Attr : FunDecl->attrs()) {
15387330f729Sjoerg     switch (Attr->getKind()) {
15397330f729Sjoerg       case attr::TryAcquireCapability: {
15407330f729Sjoerg         auto *A = cast<TryAcquireCapabilityAttr>(Attr);
15417330f729Sjoerg         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
15427330f729Sjoerg                     Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
15437330f729Sjoerg                     Negate);
15447330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
15457330f729Sjoerg         break;
15467330f729Sjoerg       };
15477330f729Sjoerg       case attr::ExclusiveTrylockFunction: {
15487330f729Sjoerg         const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
15497330f729Sjoerg         getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
15507330f729Sjoerg                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
15517330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
15527330f729Sjoerg         break;
15537330f729Sjoerg       }
15547330f729Sjoerg       case attr::SharedTrylockFunction: {
15557330f729Sjoerg         const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
15567330f729Sjoerg         getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
15577330f729Sjoerg                     PredBlock, CurrBlock, A->getSuccessValue(), Negate);
15587330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
15597330f729Sjoerg         break;
15607330f729Sjoerg       }
15617330f729Sjoerg       default:
15627330f729Sjoerg         break;
15637330f729Sjoerg     }
15647330f729Sjoerg   }
15657330f729Sjoerg 
15667330f729Sjoerg   // Add and remove locks.
15677330f729Sjoerg   SourceLocation Loc = Exp->getExprLoc();
15687330f729Sjoerg   for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
15697330f729Sjoerg     addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
15707330f729Sjoerg                                                          LK_Exclusive, Loc),
15717330f729Sjoerg             CapDiagKind);
15727330f729Sjoerg   for (const auto &SharedLockToAdd : SharedLocksToAdd)
15737330f729Sjoerg     addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd,
15747330f729Sjoerg                                                          LK_Shared, Loc),
15757330f729Sjoerg             CapDiagKind);
15767330f729Sjoerg }
15777330f729Sjoerg 
15787330f729Sjoerg namespace {
15797330f729Sjoerg 
15807330f729Sjoerg /// We use this class to visit different types of expressions in
15817330f729Sjoerg /// CFGBlocks, and build up the lockset.
15827330f729Sjoerg /// An expression may cause us to add or remove locks from the lockset, or else
15837330f729Sjoerg /// output error messages related to missing locks.
15847330f729Sjoerg /// FIXME: In future, we may be able to not inherit from a visitor.
15857330f729Sjoerg class BuildLockset : public ConstStmtVisitor<BuildLockset> {
15867330f729Sjoerg   friend class ThreadSafetyAnalyzer;
15877330f729Sjoerg 
15887330f729Sjoerg   ThreadSafetyAnalyzer *Analyzer;
15897330f729Sjoerg   FactSet FSet;
15907330f729Sjoerg   LocalVariableMap::Context LVarCtx;
15917330f729Sjoerg   unsigned CtxIndex;
15927330f729Sjoerg 
15937330f729Sjoerg   // helper functions
15947330f729Sjoerg   void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
15957330f729Sjoerg                           Expr *MutexExp, ProtectedOperationKind POK,
15967330f729Sjoerg                           StringRef DiagKind, SourceLocation Loc);
15977330f729Sjoerg   void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
15987330f729Sjoerg                        StringRef DiagKind);
15997330f729Sjoerg 
16007330f729Sjoerg   void checkAccess(const Expr *Exp, AccessKind AK,
16017330f729Sjoerg                    ProtectedOperationKind POK = POK_VarAccess);
16027330f729Sjoerg   void checkPtAccess(const Expr *Exp, AccessKind AK,
16037330f729Sjoerg                      ProtectedOperationKind POK = POK_VarAccess);
16047330f729Sjoerg 
16057330f729Sjoerg   void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
16067330f729Sjoerg   void examineArguments(const FunctionDecl *FD,
16077330f729Sjoerg                         CallExpr::const_arg_iterator ArgBegin,
16087330f729Sjoerg                         CallExpr::const_arg_iterator ArgEnd,
16097330f729Sjoerg                         bool SkipFirstParam = false);
16107330f729Sjoerg 
16117330f729Sjoerg public:
BuildLockset(ThreadSafetyAnalyzer * Anlzr,CFGBlockInfo & Info)16127330f729Sjoerg   BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
16137330f729Sjoerg       : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
16147330f729Sjoerg         LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
16157330f729Sjoerg 
16167330f729Sjoerg   void VisitUnaryOperator(const UnaryOperator *UO);
16177330f729Sjoerg   void VisitBinaryOperator(const BinaryOperator *BO);
16187330f729Sjoerg   void VisitCastExpr(const CastExpr *CE);
16197330f729Sjoerg   void VisitCallExpr(const CallExpr *Exp);
16207330f729Sjoerg   void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
16217330f729Sjoerg   void VisitDeclStmt(const DeclStmt *S);
16227330f729Sjoerg };
16237330f729Sjoerg 
16247330f729Sjoerg } // namespace
16257330f729Sjoerg 
16267330f729Sjoerg /// Warn if the LSet does not contain a lock sufficient to protect access
16277330f729Sjoerg /// of at least the passed in AccessKind.
warnIfMutexNotHeld(const NamedDecl * D,const Expr * Exp,AccessKind AK,Expr * MutexExp,ProtectedOperationKind POK,StringRef DiagKind,SourceLocation Loc)16287330f729Sjoerg void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
16297330f729Sjoerg                                       AccessKind AK, Expr *MutexExp,
16307330f729Sjoerg                                       ProtectedOperationKind POK,
16317330f729Sjoerg                                       StringRef DiagKind, SourceLocation Loc) {
16327330f729Sjoerg   LockKind LK = getLockKindFromAccessKind(AK);
16337330f729Sjoerg 
16347330f729Sjoerg   CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
16357330f729Sjoerg   if (Cp.isInvalid()) {
16367330f729Sjoerg     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
16377330f729Sjoerg     return;
16387330f729Sjoerg   } else if (Cp.shouldIgnore()) {
16397330f729Sjoerg     return;
16407330f729Sjoerg   }
16417330f729Sjoerg 
16427330f729Sjoerg   if (Cp.negative()) {
16437330f729Sjoerg     // Negative capabilities act like locks excluded
16447330f729Sjoerg     const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
16457330f729Sjoerg     if (LDat) {
16467330f729Sjoerg       Analyzer->Handler.handleFunExcludesLock(
16477330f729Sjoerg           DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
16487330f729Sjoerg       return;
16497330f729Sjoerg     }
16507330f729Sjoerg 
16517330f729Sjoerg     // If this does not refer to a negative capability in the same class,
16527330f729Sjoerg     // then stop here.
16537330f729Sjoerg     if (!Analyzer->inCurrentScope(Cp))
16547330f729Sjoerg       return;
16557330f729Sjoerg 
16567330f729Sjoerg     // Otherwise the negative requirement must be propagated to the caller.
16577330f729Sjoerg     LDat = FSet.findLock(Analyzer->FactMan, Cp);
16587330f729Sjoerg     if (!LDat) {
1659*e038c9c4Sjoerg       Analyzer->Handler.handleNegativeNotHeld(D, Cp.toString(), Loc);
16607330f729Sjoerg     }
16617330f729Sjoerg     return;
16627330f729Sjoerg   }
16637330f729Sjoerg 
16647330f729Sjoerg   const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
16657330f729Sjoerg   bool NoError = true;
16667330f729Sjoerg   if (!LDat) {
16677330f729Sjoerg     // No exact match found.  Look for a partial match.
16687330f729Sjoerg     LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
16697330f729Sjoerg     if (LDat) {
16707330f729Sjoerg       // Warn that there's no precise match.
16717330f729Sjoerg       std::string PartMatchStr = LDat->toString();
16727330f729Sjoerg       StringRef   PartMatchName(PartMatchStr);
16737330f729Sjoerg       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
16747330f729Sjoerg                                            LK, Loc, &PartMatchName);
16757330f729Sjoerg     } else {
16767330f729Sjoerg       // Warn that there's no match at all.
16777330f729Sjoerg       Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
16787330f729Sjoerg                                            LK, Loc);
16797330f729Sjoerg     }
16807330f729Sjoerg     NoError = false;
16817330f729Sjoerg   }
16827330f729Sjoerg   // Make sure the mutex we found is the right kind.
16837330f729Sjoerg   if (NoError && LDat && !LDat->isAtLeast(LK)) {
16847330f729Sjoerg     Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
16857330f729Sjoerg                                          LK, Loc);
16867330f729Sjoerg   }
16877330f729Sjoerg }
16887330f729Sjoerg 
16897330f729Sjoerg /// Warn if the LSet contains the given lock.
warnIfMutexHeld(const NamedDecl * D,const Expr * Exp,Expr * MutexExp,StringRef DiagKind)16907330f729Sjoerg void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
16917330f729Sjoerg                                    Expr *MutexExp, StringRef DiagKind) {
16927330f729Sjoerg   CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
16937330f729Sjoerg   if (Cp.isInvalid()) {
16947330f729Sjoerg     warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
16957330f729Sjoerg     return;
16967330f729Sjoerg   } else if (Cp.shouldIgnore()) {
16977330f729Sjoerg     return;
16987330f729Sjoerg   }
16997330f729Sjoerg 
17007330f729Sjoerg   const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
17017330f729Sjoerg   if (LDat) {
17027330f729Sjoerg     Analyzer->Handler.handleFunExcludesLock(
17037330f729Sjoerg         DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
17047330f729Sjoerg   }
17057330f729Sjoerg }
17067330f729Sjoerg 
17077330f729Sjoerg /// Checks guarded_by and pt_guarded_by attributes.
17087330f729Sjoerg /// Whenever we identify an access (read or write) to a DeclRefExpr that is
17097330f729Sjoerg /// marked with guarded_by, we must ensure the appropriate mutexes are held.
17107330f729Sjoerg /// Similarly, we check if the access is to an expression that dereferences
17117330f729Sjoerg /// a pointer marked with pt_guarded_by.
checkAccess(const Expr * Exp,AccessKind AK,ProtectedOperationKind POK)17127330f729Sjoerg void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
17137330f729Sjoerg                                ProtectedOperationKind POK) {
17147330f729Sjoerg   Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
17157330f729Sjoerg 
17167330f729Sjoerg   SourceLocation Loc = Exp->getExprLoc();
17177330f729Sjoerg 
17187330f729Sjoerg   // Local variables of reference type cannot be re-assigned;
17197330f729Sjoerg   // map them to their initializer.
17207330f729Sjoerg   while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
17217330f729Sjoerg     const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
17227330f729Sjoerg     if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
17237330f729Sjoerg       if (const auto *E = VD->getInit()) {
17247330f729Sjoerg         // Guard against self-initialization. e.g., int &i = i;
17257330f729Sjoerg         if (E == Exp)
17267330f729Sjoerg           break;
17277330f729Sjoerg         Exp = E;
17287330f729Sjoerg         continue;
17297330f729Sjoerg       }
17307330f729Sjoerg     }
17317330f729Sjoerg     break;
17327330f729Sjoerg   }
17337330f729Sjoerg 
17347330f729Sjoerg   if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
17357330f729Sjoerg     // For dereferences
17367330f729Sjoerg     if (UO->getOpcode() == UO_Deref)
17377330f729Sjoerg       checkPtAccess(UO->getSubExpr(), AK, POK);
17387330f729Sjoerg     return;
17397330f729Sjoerg   }
17407330f729Sjoerg 
17417330f729Sjoerg   if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
17427330f729Sjoerg     checkPtAccess(AE->getLHS(), AK, POK);
17437330f729Sjoerg     return;
17447330f729Sjoerg   }
17457330f729Sjoerg 
17467330f729Sjoerg   if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
17477330f729Sjoerg     if (ME->isArrow())
17487330f729Sjoerg       checkPtAccess(ME->getBase(), AK, POK);
17497330f729Sjoerg     else
17507330f729Sjoerg       checkAccess(ME->getBase(), AK, POK);
17517330f729Sjoerg   }
17527330f729Sjoerg 
17537330f729Sjoerg   const ValueDecl *D = getValueDecl(Exp);
17547330f729Sjoerg   if (!D || !D->hasAttrs())
17557330f729Sjoerg     return;
17567330f729Sjoerg 
17577330f729Sjoerg   if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
17587330f729Sjoerg     Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
17597330f729Sjoerg   }
17607330f729Sjoerg 
17617330f729Sjoerg   for (const auto *I : D->specific_attrs<GuardedByAttr>())
17627330f729Sjoerg     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
17637330f729Sjoerg                        ClassifyDiagnostic(I), Loc);
17647330f729Sjoerg }
17657330f729Sjoerg 
17667330f729Sjoerg /// Checks pt_guarded_by and pt_guarded_var attributes.
17677330f729Sjoerg /// POK is the same  operationKind that was passed to checkAccess.
checkPtAccess(const Expr * Exp,AccessKind AK,ProtectedOperationKind POK)17687330f729Sjoerg void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
17697330f729Sjoerg                                  ProtectedOperationKind POK) {
17707330f729Sjoerg   while (true) {
17717330f729Sjoerg     if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
17727330f729Sjoerg       Exp = PE->getSubExpr();
17737330f729Sjoerg       continue;
17747330f729Sjoerg     }
17757330f729Sjoerg     if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
17767330f729Sjoerg       if (CE->getCastKind() == CK_ArrayToPointerDecay) {
17777330f729Sjoerg         // If it's an actual array, and not a pointer, then it's elements
17787330f729Sjoerg         // are protected by GUARDED_BY, not PT_GUARDED_BY;
17797330f729Sjoerg         checkAccess(CE->getSubExpr(), AK, POK);
17807330f729Sjoerg         return;
17817330f729Sjoerg       }
17827330f729Sjoerg       Exp = CE->getSubExpr();
17837330f729Sjoerg       continue;
17847330f729Sjoerg     }
17857330f729Sjoerg     break;
17867330f729Sjoerg   }
17877330f729Sjoerg 
17887330f729Sjoerg   // Pass by reference warnings are under a different flag.
17897330f729Sjoerg   ProtectedOperationKind PtPOK = POK_VarDereference;
17907330f729Sjoerg   if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
17917330f729Sjoerg 
17927330f729Sjoerg   const ValueDecl *D = getValueDecl(Exp);
17937330f729Sjoerg   if (!D || !D->hasAttrs())
17947330f729Sjoerg     return;
17957330f729Sjoerg 
17967330f729Sjoerg   if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
17977330f729Sjoerg     Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
17987330f729Sjoerg                                         Exp->getExprLoc());
17997330f729Sjoerg 
18007330f729Sjoerg   for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
18017330f729Sjoerg     warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
18027330f729Sjoerg                        ClassifyDiagnostic(I), Exp->getExprLoc());
18037330f729Sjoerg }
18047330f729Sjoerg 
18057330f729Sjoerg /// Process a function call, method call, constructor call,
18067330f729Sjoerg /// or destructor call.  This involves looking at the attributes on the
18077330f729Sjoerg /// corresponding function/method/constructor/destructor, issuing warnings,
18087330f729Sjoerg /// and updating the locksets accordingly.
18097330f729Sjoerg ///
18107330f729Sjoerg /// FIXME: For classes annotated with one of the guarded annotations, we need
18117330f729Sjoerg /// to treat const method calls as reads and non-const method calls as writes,
18127330f729Sjoerg /// and check that the appropriate locks are held. Non-const method calls with
18137330f729Sjoerg /// the same signature as const method calls can be also treated as reads.
18147330f729Sjoerg ///
handleCall(const Expr * Exp,const NamedDecl * D,VarDecl * VD)18157330f729Sjoerg void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
18167330f729Sjoerg                               VarDecl *VD) {
18177330f729Sjoerg   SourceLocation Loc = Exp->getExprLoc();
18187330f729Sjoerg   CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
18197330f729Sjoerg   CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1820*e038c9c4Sjoerg   CapExprSet ScopedReqsAndExcludes;
18217330f729Sjoerg   StringRef CapDiagKind = "mutex";
18227330f729Sjoerg 
18237330f729Sjoerg   // Figure out if we're constructing an object of scoped lockable class
18247330f729Sjoerg   bool isScopedVar = false;
18257330f729Sjoerg   if (VD) {
18267330f729Sjoerg     if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
18277330f729Sjoerg       const CXXRecordDecl* PD = CD->getParent();
18287330f729Sjoerg       if (PD && PD->hasAttr<ScopedLockableAttr>())
18297330f729Sjoerg         isScopedVar = true;
18307330f729Sjoerg     }
18317330f729Sjoerg   }
18327330f729Sjoerg 
18337330f729Sjoerg   for(const Attr *At : D->attrs()) {
18347330f729Sjoerg     switch (At->getKind()) {
18357330f729Sjoerg       // When we encounter a lock function, we need to add the lock to our
18367330f729Sjoerg       // lockset.
18377330f729Sjoerg       case attr::AcquireCapability: {
18387330f729Sjoerg         const auto *A = cast<AcquireCapabilityAttr>(At);
18397330f729Sjoerg         Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
18407330f729Sjoerg                                             : ExclusiveLocksToAdd,
18417330f729Sjoerg                               A, Exp, D, VD);
18427330f729Sjoerg 
18437330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
18447330f729Sjoerg         break;
18457330f729Sjoerg       }
18467330f729Sjoerg 
18477330f729Sjoerg       // An assert will add a lock to the lockset, but will not generate
18487330f729Sjoerg       // a warning if it is already there, and will not generate a warning
18497330f729Sjoerg       // if it is not removed.
18507330f729Sjoerg       case attr::AssertExclusiveLock: {
18517330f729Sjoerg         const auto *A = cast<AssertExclusiveLockAttr>(At);
18527330f729Sjoerg 
18537330f729Sjoerg         CapExprSet AssertLocks;
18547330f729Sjoerg         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
18557330f729Sjoerg         for (const auto &AssertLock : AssertLocks)
1856*e038c9c4Sjoerg           Analyzer->addLock(
1857*e038c9c4Sjoerg               FSet,
1858*e038c9c4Sjoerg               std::make_unique<LockableFactEntry>(AssertLock, LK_Exclusive, Loc,
1859*e038c9c4Sjoerg                                                   FactEntry::Asserted),
18607330f729Sjoerg               ClassifyDiagnostic(A));
18617330f729Sjoerg         break;
18627330f729Sjoerg       }
18637330f729Sjoerg       case attr::AssertSharedLock: {
18647330f729Sjoerg         const auto *A = cast<AssertSharedLockAttr>(At);
18657330f729Sjoerg 
18667330f729Sjoerg         CapExprSet AssertLocks;
18677330f729Sjoerg         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
18687330f729Sjoerg         for (const auto &AssertLock : AssertLocks)
1869*e038c9c4Sjoerg           Analyzer->addLock(
1870*e038c9c4Sjoerg               FSet,
1871*e038c9c4Sjoerg               std::make_unique<LockableFactEntry>(AssertLock, LK_Shared, Loc,
1872*e038c9c4Sjoerg                                                   FactEntry::Asserted),
18737330f729Sjoerg               ClassifyDiagnostic(A));
18747330f729Sjoerg         break;
18757330f729Sjoerg       }
18767330f729Sjoerg 
18777330f729Sjoerg       case attr::AssertCapability: {
18787330f729Sjoerg         const auto *A = cast<AssertCapabilityAttr>(At);
18797330f729Sjoerg         CapExprSet AssertLocks;
18807330f729Sjoerg         Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
18817330f729Sjoerg         for (const auto &AssertLock : AssertLocks)
18827330f729Sjoerg           Analyzer->addLock(FSet,
18837330f729Sjoerg                             std::make_unique<LockableFactEntry>(
18847330f729Sjoerg                                 AssertLock,
18857330f729Sjoerg                                 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1886*e038c9c4Sjoerg                                 FactEntry::Asserted),
18877330f729Sjoerg                             ClassifyDiagnostic(A));
18887330f729Sjoerg         break;
18897330f729Sjoerg       }
18907330f729Sjoerg 
18917330f729Sjoerg       // When we encounter an unlock function, we need to remove unlocked
18927330f729Sjoerg       // mutexes from the lockset, and flag a warning if they are not there.
18937330f729Sjoerg       case attr::ReleaseCapability: {
18947330f729Sjoerg         const auto *A = cast<ReleaseCapabilityAttr>(At);
18957330f729Sjoerg         if (A->isGeneric())
18967330f729Sjoerg           Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
18977330f729Sjoerg         else if (A->isShared())
18987330f729Sjoerg           Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
18997330f729Sjoerg         else
19007330f729Sjoerg           Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
19017330f729Sjoerg 
19027330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
19037330f729Sjoerg         break;
19047330f729Sjoerg       }
19057330f729Sjoerg 
19067330f729Sjoerg       case attr::RequiresCapability: {
19077330f729Sjoerg         const auto *A = cast<RequiresCapabilityAttr>(At);
19087330f729Sjoerg         for (auto *Arg : A->args()) {
19097330f729Sjoerg           warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
19107330f729Sjoerg                              POK_FunctionCall, ClassifyDiagnostic(A),
19117330f729Sjoerg                              Exp->getExprLoc());
19127330f729Sjoerg           // use for adopting a lock
1913*e038c9c4Sjoerg           if (isScopedVar)
1914*e038c9c4Sjoerg             Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD);
19157330f729Sjoerg         }
19167330f729Sjoerg         break;
19177330f729Sjoerg       }
19187330f729Sjoerg 
19197330f729Sjoerg       case attr::LocksExcluded: {
19207330f729Sjoerg         const auto *A = cast<LocksExcludedAttr>(At);
1921*e038c9c4Sjoerg         for (auto *Arg : A->args()) {
19227330f729Sjoerg           warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
1923*e038c9c4Sjoerg           // use for deferring a lock
1924*e038c9c4Sjoerg           if (isScopedVar)
1925*e038c9c4Sjoerg             Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD);
1926*e038c9c4Sjoerg         }
19277330f729Sjoerg         break;
19287330f729Sjoerg       }
19297330f729Sjoerg 
19307330f729Sjoerg       // Ignore attributes unrelated to thread-safety
19317330f729Sjoerg       default:
19327330f729Sjoerg         break;
19337330f729Sjoerg     }
19347330f729Sjoerg   }
19357330f729Sjoerg 
19367330f729Sjoerg   // Remove locks first to allow lock upgrading/downgrading.
19377330f729Sjoerg   // FIXME -- should only fully remove if the attribute refers to 'this'.
19387330f729Sjoerg   bool Dtor = isa<CXXDestructorDecl>(D);
19397330f729Sjoerg   for (const auto &M : ExclusiveLocksToRemove)
19407330f729Sjoerg     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
19417330f729Sjoerg   for (const auto &M : SharedLocksToRemove)
19427330f729Sjoerg     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
19437330f729Sjoerg   for (const auto &M : GenericLocksToRemove)
19447330f729Sjoerg     Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
19457330f729Sjoerg 
19467330f729Sjoerg   // Add locks.
1947*e038c9c4Sjoerg   FactEntry::SourceKind Source =
1948*e038c9c4Sjoerg       isScopedVar ? FactEntry::Managed : FactEntry::Acquired;
19497330f729Sjoerg   for (const auto &M : ExclusiveLocksToAdd)
1950*e038c9c4Sjoerg     Analyzer->addLock(
1951*e038c9c4Sjoerg         FSet, std::make_unique<LockableFactEntry>(M, LK_Exclusive, Loc, Source),
19527330f729Sjoerg         CapDiagKind);
19537330f729Sjoerg   for (const auto &M : SharedLocksToAdd)
1954*e038c9c4Sjoerg     Analyzer->addLock(
1955*e038c9c4Sjoerg         FSet, std::make_unique<LockableFactEntry>(M, LK_Shared, Loc, Source),
19567330f729Sjoerg         CapDiagKind);
19577330f729Sjoerg 
19587330f729Sjoerg   if (isScopedVar) {
19597330f729Sjoerg     // Add the managing object as a dummy mutex, mapped to the underlying mutex.
19607330f729Sjoerg     SourceLocation MLoc = VD->getLocation();
19617330f729Sjoerg     DeclRefExpr DRE(VD->getASTContext(), VD, false, VD->getType(), VK_LValue,
19627330f729Sjoerg                     VD->getLocation());
19637330f729Sjoerg     // FIXME: does this store a pointer to DRE?
19647330f729Sjoerg     CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
19657330f729Sjoerg 
19667330f729Sjoerg     auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, MLoc);
19677330f729Sjoerg     for (const auto &M : ExclusiveLocksToAdd)
1968*e038c9c4Sjoerg       ScopedEntry->addLock(M);
19697330f729Sjoerg     for (const auto &M : SharedLocksToAdd)
1970*e038c9c4Sjoerg       ScopedEntry->addLock(M);
1971*e038c9c4Sjoerg     for (const auto &M : ScopedReqsAndExcludes)
1972*e038c9c4Sjoerg       ScopedEntry->addLock(M);
19737330f729Sjoerg     for (const auto &M : ExclusiveLocksToRemove)
19747330f729Sjoerg       ScopedEntry->addExclusiveUnlock(M);
19757330f729Sjoerg     for (const auto &M : SharedLocksToRemove)
19767330f729Sjoerg       ScopedEntry->addSharedUnlock(M);
19777330f729Sjoerg     Analyzer->addLock(FSet, std::move(ScopedEntry), CapDiagKind);
19787330f729Sjoerg   }
19797330f729Sjoerg }
19807330f729Sjoerg 
19817330f729Sjoerg /// For unary operations which read and write a variable, we need to
19827330f729Sjoerg /// check whether we hold any required mutexes. Reads are checked in
19837330f729Sjoerg /// VisitCastExpr.
VisitUnaryOperator(const UnaryOperator * UO)19847330f729Sjoerg void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
19857330f729Sjoerg   switch (UO->getOpcode()) {
19867330f729Sjoerg     case UO_PostDec:
19877330f729Sjoerg     case UO_PostInc:
19887330f729Sjoerg     case UO_PreDec:
19897330f729Sjoerg     case UO_PreInc:
19907330f729Sjoerg       checkAccess(UO->getSubExpr(), AK_Written);
19917330f729Sjoerg       break;
19927330f729Sjoerg     default:
19937330f729Sjoerg       break;
19947330f729Sjoerg   }
19957330f729Sjoerg }
19967330f729Sjoerg 
19977330f729Sjoerg /// For binary operations which assign to a variable (writes), we need to check
19987330f729Sjoerg /// whether we hold any required mutexes.
19997330f729Sjoerg /// FIXME: Deal with non-primitive types.
VisitBinaryOperator(const BinaryOperator * BO)20007330f729Sjoerg void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
20017330f729Sjoerg   if (!BO->isAssignmentOp())
20027330f729Sjoerg     return;
20037330f729Sjoerg 
20047330f729Sjoerg   // adjust the context
20057330f729Sjoerg   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
20067330f729Sjoerg 
20077330f729Sjoerg   checkAccess(BO->getLHS(), AK_Written);
20087330f729Sjoerg }
20097330f729Sjoerg 
20107330f729Sjoerg /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
20117330f729Sjoerg /// need to ensure we hold any required mutexes.
20127330f729Sjoerg /// FIXME: Deal with non-primitive types.
VisitCastExpr(const CastExpr * CE)20137330f729Sjoerg void BuildLockset::VisitCastExpr(const CastExpr *CE) {
20147330f729Sjoerg   if (CE->getCastKind() != CK_LValueToRValue)
20157330f729Sjoerg     return;
20167330f729Sjoerg   checkAccess(CE->getSubExpr(), AK_Read);
20177330f729Sjoerg }
20187330f729Sjoerg 
examineArguments(const FunctionDecl * FD,CallExpr::const_arg_iterator ArgBegin,CallExpr::const_arg_iterator ArgEnd,bool SkipFirstParam)20197330f729Sjoerg void BuildLockset::examineArguments(const FunctionDecl *FD,
20207330f729Sjoerg                                     CallExpr::const_arg_iterator ArgBegin,
20217330f729Sjoerg                                     CallExpr::const_arg_iterator ArgEnd,
20227330f729Sjoerg                                     bool SkipFirstParam) {
20237330f729Sjoerg   // Currently we can't do anything if we don't know the function declaration.
20247330f729Sjoerg   if (!FD)
20257330f729Sjoerg     return;
20267330f729Sjoerg 
20277330f729Sjoerg   // NO_THREAD_SAFETY_ANALYSIS does double duty here.  Normally it
20287330f729Sjoerg   // only turns off checking within the body of a function, but we also
20297330f729Sjoerg   // use it to turn off checking in arguments to the function.  This
20307330f729Sjoerg   // could result in some false negatives, but the alternative is to
20317330f729Sjoerg   // create yet another attribute.
20327330f729Sjoerg   if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
20337330f729Sjoerg     return;
20347330f729Sjoerg 
20357330f729Sjoerg   const ArrayRef<ParmVarDecl *> Params = FD->parameters();
20367330f729Sjoerg   auto Param = Params.begin();
20377330f729Sjoerg   if (SkipFirstParam)
20387330f729Sjoerg     ++Param;
20397330f729Sjoerg 
20407330f729Sjoerg   // There can be default arguments, so we stop when one iterator is at end().
20417330f729Sjoerg   for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd;
20427330f729Sjoerg        ++Param, ++Arg) {
20437330f729Sjoerg     QualType Qt = (*Param)->getType();
20447330f729Sjoerg     if (Qt->isReferenceType())
20457330f729Sjoerg       checkAccess(*Arg, AK_Read, POK_PassByRef);
20467330f729Sjoerg   }
20477330f729Sjoerg }
20487330f729Sjoerg 
VisitCallExpr(const CallExpr * Exp)20497330f729Sjoerg void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
20507330f729Sjoerg   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
20517330f729Sjoerg     const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
20527330f729Sjoerg     // ME can be null when calling a method pointer
20537330f729Sjoerg     const CXXMethodDecl *MD = CE->getMethodDecl();
20547330f729Sjoerg 
20557330f729Sjoerg     if (ME && MD) {
20567330f729Sjoerg       if (ME->isArrow()) {
2057*e038c9c4Sjoerg         // Should perhaps be AK_Written if !MD->isConst().
20587330f729Sjoerg         checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
20597330f729Sjoerg       } else {
2060*e038c9c4Sjoerg         // Should perhaps be AK_Written if !MD->isConst().
20617330f729Sjoerg         checkAccess(CE->getImplicitObjectArgument(), AK_Read);
20627330f729Sjoerg       }
20637330f729Sjoerg     }
20647330f729Sjoerg 
20657330f729Sjoerg     examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
20667330f729Sjoerg   } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
20677330f729Sjoerg     auto OEop = OE->getOperator();
20687330f729Sjoerg     switch (OEop) {
20697330f729Sjoerg       case OO_Equal: {
20707330f729Sjoerg         const Expr *Target = OE->getArg(0);
20717330f729Sjoerg         const Expr *Source = OE->getArg(1);
20727330f729Sjoerg         checkAccess(Target, AK_Written);
20737330f729Sjoerg         checkAccess(Source, AK_Read);
20747330f729Sjoerg         break;
20757330f729Sjoerg       }
20767330f729Sjoerg       case OO_Star:
20777330f729Sjoerg       case OO_Arrow:
20787330f729Sjoerg       case OO_Subscript:
20797330f729Sjoerg         if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
20807330f729Sjoerg           // Grrr.  operator* can be multiplication...
20817330f729Sjoerg           checkPtAccess(OE->getArg(0), AK_Read);
20827330f729Sjoerg         }
20837330f729Sjoerg         LLVM_FALLTHROUGH;
20847330f729Sjoerg       default: {
20857330f729Sjoerg         // TODO: get rid of this, and rely on pass-by-ref instead.
20867330f729Sjoerg         const Expr *Obj = OE->getArg(0);
20877330f729Sjoerg         checkAccess(Obj, AK_Read);
20887330f729Sjoerg         // Check the remaining arguments. For method operators, the first
20897330f729Sjoerg         // argument is the implicit self argument, and doesn't appear in the
20907330f729Sjoerg         // FunctionDecl, but for non-methods it does.
20917330f729Sjoerg         const FunctionDecl *FD = OE->getDirectCallee();
20927330f729Sjoerg         examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
20937330f729Sjoerg                          /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
20947330f729Sjoerg         break;
20957330f729Sjoerg       }
20967330f729Sjoerg     }
20977330f729Sjoerg   } else {
20987330f729Sjoerg     examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
20997330f729Sjoerg   }
21007330f729Sjoerg 
21017330f729Sjoerg   auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
21027330f729Sjoerg   if(!D || !D->hasAttrs())
21037330f729Sjoerg     return;
21047330f729Sjoerg   handleCall(Exp, D);
21057330f729Sjoerg }
21067330f729Sjoerg 
VisitCXXConstructExpr(const CXXConstructExpr * Exp)21077330f729Sjoerg void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
21087330f729Sjoerg   const CXXConstructorDecl *D = Exp->getConstructor();
21097330f729Sjoerg   if (D && D->isCopyConstructor()) {
21107330f729Sjoerg     const Expr* Source = Exp->getArg(0);
21117330f729Sjoerg     checkAccess(Source, AK_Read);
21127330f729Sjoerg   } else {
21137330f729Sjoerg     examineArguments(D, Exp->arg_begin(), Exp->arg_end());
21147330f729Sjoerg   }
21157330f729Sjoerg }
21167330f729Sjoerg 
21177330f729Sjoerg static CXXConstructorDecl *
findConstructorForByValueReturn(const CXXRecordDecl * RD)21187330f729Sjoerg findConstructorForByValueReturn(const CXXRecordDecl *RD) {
21197330f729Sjoerg   // Prefer a move constructor over a copy constructor. If there's more than
21207330f729Sjoerg   // one copy constructor or more than one move constructor, we arbitrarily
21217330f729Sjoerg   // pick the first declared such constructor rather than trying to guess which
21227330f729Sjoerg   // one is more appropriate.
21237330f729Sjoerg   CXXConstructorDecl *CopyCtor = nullptr;
21247330f729Sjoerg   for (auto *Ctor : RD->ctors()) {
21257330f729Sjoerg     if (Ctor->isDeleted())
21267330f729Sjoerg       continue;
21277330f729Sjoerg     if (Ctor->isMoveConstructor())
21287330f729Sjoerg       return Ctor;
21297330f729Sjoerg     if (!CopyCtor && Ctor->isCopyConstructor())
21307330f729Sjoerg       CopyCtor = Ctor;
21317330f729Sjoerg   }
21327330f729Sjoerg   return CopyCtor;
21337330f729Sjoerg }
21347330f729Sjoerg 
buildFakeCtorCall(CXXConstructorDecl * CD,ArrayRef<Expr * > Args,SourceLocation Loc)21357330f729Sjoerg static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
21367330f729Sjoerg                                SourceLocation Loc) {
21377330f729Sjoerg   ASTContext &Ctx = CD->getASTContext();
21387330f729Sjoerg   return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
21397330f729Sjoerg                                   CD, true, Args, false, false, false, false,
21407330f729Sjoerg                                   CXXConstructExpr::CK_Complete,
21417330f729Sjoerg                                   SourceRange(Loc, Loc));
21427330f729Sjoerg }
21437330f729Sjoerg 
VisitDeclStmt(const DeclStmt * S)21447330f729Sjoerg void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
21457330f729Sjoerg   // adjust the context
21467330f729Sjoerg   LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
21477330f729Sjoerg 
21487330f729Sjoerg   for (auto *D : S->getDeclGroup()) {
21497330f729Sjoerg     if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
21507330f729Sjoerg       Expr *E = VD->getInit();
21517330f729Sjoerg       if (!E)
21527330f729Sjoerg         continue;
21537330f729Sjoerg       E = E->IgnoreParens();
21547330f729Sjoerg 
21557330f729Sjoerg       // handle constructors that involve temporaries
21567330f729Sjoerg       if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2157*e038c9c4Sjoerg         E = EWC->getSubExpr()->IgnoreParens();
2158*e038c9c4Sjoerg       if (auto *CE = dyn_cast<CastExpr>(E))
2159*e038c9c4Sjoerg         if (CE->getCastKind() == CK_NoOp ||
2160*e038c9c4Sjoerg             CE->getCastKind() == CK_ConstructorConversion ||
2161*e038c9c4Sjoerg             CE->getCastKind() == CK_UserDefinedConversion)
2162*e038c9c4Sjoerg           E = CE->getSubExpr()->IgnoreParens();
21637330f729Sjoerg       if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2164*e038c9c4Sjoerg         E = BTE->getSubExpr()->IgnoreParens();
21657330f729Sjoerg 
21667330f729Sjoerg       if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
21677330f729Sjoerg         const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
21687330f729Sjoerg         if (!CtorD || !CtorD->hasAttrs())
21697330f729Sjoerg           continue;
21707330f729Sjoerg         handleCall(E, CtorD, VD);
21717330f729Sjoerg       } else if (isa<CallExpr>(E) && E->isRValue()) {
21727330f729Sjoerg         // If the object is initialized by a function call that returns a
21737330f729Sjoerg         // scoped lockable by value, use the attributes on the copy or move
21747330f729Sjoerg         // constructor to figure out what effect that should have on the
21757330f729Sjoerg         // lockset.
21767330f729Sjoerg         // FIXME: Is this really the best way to handle this situation?
21777330f729Sjoerg         auto *RD = E->getType()->getAsCXXRecordDecl();
21787330f729Sjoerg         if (!RD || !RD->hasAttr<ScopedLockableAttr>())
21797330f729Sjoerg           continue;
21807330f729Sjoerg         CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
21817330f729Sjoerg         if (!CtorD || !CtorD->hasAttrs())
21827330f729Sjoerg           continue;
21837330f729Sjoerg         handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
21847330f729Sjoerg       }
21857330f729Sjoerg     }
21867330f729Sjoerg   }
21877330f729Sjoerg }
21887330f729Sjoerg 
21897330f729Sjoerg /// Compute the intersection of two locksets and issue warnings for any
21907330f729Sjoerg /// locks in the symmetric difference.
21917330f729Sjoerg ///
21927330f729Sjoerg /// This function is used at a merge point in the CFG when comparing the lockset
21937330f729Sjoerg /// of each branch being merged. For example, given the following sequence:
21947330f729Sjoerg /// A; if () then B; else C; D; we need to check that the lockset after B and C
21957330f729Sjoerg /// are the same. In the event of a difference, we use the intersection of these
21967330f729Sjoerg /// two locksets at the start of D.
21977330f729Sjoerg ///
21987330f729Sjoerg /// \param FSet1 The first lockset.
21997330f729Sjoerg /// \param FSet2 The second lockset.
22007330f729Sjoerg /// \param JoinLoc The location of the join point for error reporting
22017330f729Sjoerg /// \param LEK1 The error message to report if a mutex is missing from LSet1
22027330f729Sjoerg /// \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)22037330f729Sjoerg void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
22047330f729Sjoerg                                             const FactSet &FSet2,
22057330f729Sjoerg                                             SourceLocation JoinLoc,
22067330f729Sjoerg                                             LockErrorKind LEK1,
2207*e038c9c4Sjoerg                                             LockErrorKind LEK2) {
22087330f729Sjoerg   FactSet FSet1Orig = FSet1;
22097330f729Sjoerg 
22107330f729Sjoerg   // Find locks in FSet2 that conflict or are not in FSet1, and warn.
22117330f729Sjoerg   for (const auto &Fact : FSet2) {
2212*e038c9c4Sjoerg     const FactEntry &LDat2 = FactMan[Fact];
22137330f729Sjoerg 
2214*e038c9c4Sjoerg     FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, LDat2);
2215*e038c9c4Sjoerg     if (Iter1 != FSet1.end()) {
2216*e038c9c4Sjoerg       const FactEntry &LDat1 = FactMan[*Iter1];
2217*e038c9c4Sjoerg       if (LDat1.kind() != LDat2.kind()) {
2218*e038c9c4Sjoerg         Handler.handleExclusiveAndShared("mutex", LDat2.toString(), LDat2.loc(),
2219*e038c9c4Sjoerg                                          LDat1.loc());
2220*e038c9c4Sjoerg         if (LEK1 == LEK_LockedSomePredecessors &&
2221*e038c9c4Sjoerg             LDat1.kind() != LK_Exclusive) {
22227330f729Sjoerg           // Take the exclusive lock, which is the one in FSet2.
22237330f729Sjoerg           *Iter1 = Fact;
22247330f729Sjoerg         }
2225*e038c9c4Sjoerg       } else if (LEK1 == LEK_LockedSomePredecessors && LDat1.asserted() &&
2226*e038c9c4Sjoerg                  !LDat2.asserted()) {
22277330f729Sjoerg         // The non-asserted lock in FSet2 is the one we want to track.
22287330f729Sjoerg         *Iter1 = Fact;
22297330f729Sjoerg       }
22307330f729Sjoerg     } else {
2231*e038c9c4Sjoerg       LDat2.handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
22327330f729Sjoerg                                           Handler);
22337330f729Sjoerg     }
22347330f729Sjoerg   }
22357330f729Sjoerg 
22367330f729Sjoerg   // Find locks in FSet1 that are not in FSet2, and remove them.
22377330f729Sjoerg   for (const auto &Fact : FSet1Orig) {
22387330f729Sjoerg     const FactEntry *LDat1 = &FactMan[Fact];
22397330f729Sjoerg     const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
22407330f729Sjoerg 
22417330f729Sjoerg     if (!LDat2) {
22427330f729Sjoerg       LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
22437330f729Sjoerg                                            Handler);
2244*e038c9c4Sjoerg       if (LEK2 == LEK_LockedSomePredecessors)
22457330f729Sjoerg         FSet1.removeLock(FactMan, *LDat1);
22467330f729Sjoerg     }
22477330f729Sjoerg   }
22487330f729Sjoerg }
22497330f729Sjoerg 
22507330f729Sjoerg // Return true if block B never continues to its successors.
neverReturns(const CFGBlock * B)22517330f729Sjoerg static bool neverReturns(const CFGBlock *B) {
22527330f729Sjoerg   if (B->hasNoReturnElement())
22537330f729Sjoerg     return true;
22547330f729Sjoerg   if (B->empty())
22557330f729Sjoerg     return false;
22567330f729Sjoerg 
22577330f729Sjoerg   CFGElement Last = B->back();
22587330f729Sjoerg   if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
22597330f729Sjoerg     if (isa<CXXThrowExpr>(S->getStmt()))
22607330f729Sjoerg       return true;
22617330f729Sjoerg   }
22627330f729Sjoerg   return false;
22637330f729Sjoerg }
22647330f729Sjoerg 
22657330f729Sjoerg /// Check a function's CFG for thread-safety violations.
22667330f729Sjoerg ///
22677330f729Sjoerg /// We traverse the blocks in the CFG, compute the set of mutexes that are held
22687330f729Sjoerg /// at the end of each block, and issue warnings for thread safety violations.
22697330f729Sjoerg /// Each block in the CFG is traversed exactly once.
runAnalysis(AnalysisDeclContext & AC)22707330f729Sjoerg void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
22717330f729Sjoerg   // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
22727330f729Sjoerg   // For now, we just use the walker to set things up.
22737330f729Sjoerg   threadSafety::CFGWalker walker;
22747330f729Sjoerg   if (!walker.init(AC))
22757330f729Sjoerg     return;
22767330f729Sjoerg 
22777330f729Sjoerg   // AC.dumpCFG(true);
22787330f729Sjoerg   // threadSafety::printSCFG(walker);
22797330f729Sjoerg 
22807330f729Sjoerg   CFG *CFGraph = walker.getGraph();
22817330f729Sjoerg   const NamedDecl *D = walker.getDecl();
22827330f729Sjoerg   const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
22837330f729Sjoerg   CurrentMethod = dyn_cast<CXXMethodDecl>(D);
22847330f729Sjoerg 
22857330f729Sjoerg   if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
22867330f729Sjoerg     return;
22877330f729Sjoerg 
22887330f729Sjoerg   // FIXME: Do something a bit more intelligent inside constructor and
22897330f729Sjoerg   // destructor code.  Constructors and destructors must assume unique access
22907330f729Sjoerg   // to 'this', so checks on member variable access is disabled, but we should
22917330f729Sjoerg   // still enable checks on other objects.
22927330f729Sjoerg   if (isa<CXXConstructorDecl>(D))
22937330f729Sjoerg     return;  // Don't check inside constructors.
22947330f729Sjoerg   if (isa<CXXDestructorDecl>(D))
22957330f729Sjoerg     return;  // Don't check inside destructors.
22967330f729Sjoerg 
22977330f729Sjoerg   Handler.enterFunction(CurrentFunction);
22987330f729Sjoerg 
22997330f729Sjoerg   BlockInfo.resize(CFGraph->getNumBlockIDs(),
23007330f729Sjoerg     CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
23017330f729Sjoerg 
23027330f729Sjoerg   // We need to explore the CFG via a "topological" ordering.
23037330f729Sjoerg   // That way, we will be guaranteed to have information about required
23047330f729Sjoerg   // predecessor locksets when exploring a new block.
23057330f729Sjoerg   const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
23067330f729Sjoerg   PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
23077330f729Sjoerg 
23087330f729Sjoerg   // Mark entry block as reachable
23097330f729Sjoerg   BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
23107330f729Sjoerg 
23117330f729Sjoerg   // Compute SSA names for local variables
23127330f729Sjoerg   LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
23137330f729Sjoerg 
23147330f729Sjoerg   // Fill in source locations for all CFGBlocks.
23157330f729Sjoerg   findBlockLocations(CFGraph, SortedGraph, BlockInfo);
23167330f729Sjoerg 
23177330f729Sjoerg   CapExprSet ExclusiveLocksAcquired;
23187330f729Sjoerg   CapExprSet SharedLocksAcquired;
23197330f729Sjoerg   CapExprSet LocksReleased;
23207330f729Sjoerg 
23217330f729Sjoerg   // Add locks from exclusive_locks_required and shared_locks_required
23227330f729Sjoerg   // to initial lockset. Also turn off checking for lock and unlock functions.
23237330f729Sjoerg   // FIXME: is there a more intelligent way to check lock/unlock functions?
23247330f729Sjoerg   if (!SortedGraph->empty() && D->hasAttrs()) {
23257330f729Sjoerg     const CFGBlock *FirstBlock = *SortedGraph->begin();
23267330f729Sjoerg     FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
23277330f729Sjoerg 
23287330f729Sjoerg     CapExprSet ExclusiveLocksToAdd;
23297330f729Sjoerg     CapExprSet SharedLocksToAdd;
23307330f729Sjoerg     StringRef CapDiagKind = "mutex";
23317330f729Sjoerg 
23327330f729Sjoerg     SourceLocation Loc = D->getLocation();
23337330f729Sjoerg     for (const auto *Attr : D->attrs()) {
23347330f729Sjoerg       Loc = Attr->getLocation();
23357330f729Sjoerg       if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
23367330f729Sjoerg         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
23377330f729Sjoerg                     nullptr, D);
23387330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
23397330f729Sjoerg       } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
23407330f729Sjoerg         // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
23417330f729Sjoerg         // We must ignore such methods.
23427330f729Sjoerg         if (A->args_size() == 0)
23437330f729Sjoerg           return;
23447330f729Sjoerg         getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
23457330f729Sjoerg                     nullptr, D);
23467330f729Sjoerg         getMutexIDs(LocksReleased, A, nullptr, D);
23477330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
23487330f729Sjoerg       } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
23497330f729Sjoerg         if (A->args_size() == 0)
23507330f729Sjoerg           return;
23517330f729Sjoerg         getMutexIDs(A->isShared() ? SharedLocksAcquired
23527330f729Sjoerg                                   : ExclusiveLocksAcquired,
23537330f729Sjoerg                     A, nullptr, D);
23547330f729Sjoerg         CapDiagKind = ClassifyDiagnostic(A);
23557330f729Sjoerg       } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
23567330f729Sjoerg         // Don't try to check trylock functions for now.
23577330f729Sjoerg         return;
23587330f729Sjoerg       } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
23597330f729Sjoerg         // Don't try to check trylock functions for now.
23607330f729Sjoerg         return;
23617330f729Sjoerg       } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
23627330f729Sjoerg         // Don't try to check trylock functions for now.
23637330f729Sjoerg         return;
23647330f729Sjoerg       }
23657330f729Sjoerg     }
23667330f729Sjoerg 
23677330f729Sjoerg     // FIXME -- Loc can be wrong here.
23687330f729Sjoerg     for (const auto &Mu : ExclusiveLocksToAdd) {
2369*e038c9c4Sjoerg       auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc,
2370*e038c9c4Sjoerg                                                        FactEntry::Declared);
23717330f729Sjoerg       addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
23727330f729Sjoerg     }
23737330f729Sjoerg     for (const auto &Mu : SharedLocksToAdd) {
2374*e038c9c4Sjoerg       auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc,
2375*e038c9c4Sjoerg                                                        FactEntry::Declared);
23767330f729Sjoerg       addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
23777330f729Sjoerg     }
23787330f729Sjoerg   }
23797330f729Sjoerg 
23807330f729Sjoerg   for (const auto *CurrBlock : *SortedGraph) {
23817330f729Sjoerg     unsigned CurrBlockID = CurrBlock->getBlockID();
23827330f729Sjoerg     CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
23837330f729Sjoerg 
23847330f729Sjoerg     // Use the default initial lockset in case there are no predecessors.
23857330f729Sjoerg     VisitedBlocks.insert(CurrBlock);
23867330f729Sjoerg 
23877330f729Sjoerg     // Iterate through the predecessor blocks and warn if the lockset for all
23887330f729Sjoerg     // predecessors is not the same. We take the entry lockset of the current
23897330f729Sjoerg     // block to be the intersection of all previous locksets.
23907330f729Sjoerg     // FIXME: By keeping the intersection, we may output more errors in future
23917330f729Sjoerg     // for a lock which is not in the intersection, but was in the union. We
23927330f729Sjoerg     // may want to also keep the union in future. As an example, let's say
23937330f729Sjoerg     // the intersection contains Mutex L, and the union contains L and M.
23947330f729Sjoerg     // Later we unlock M. At this point, we would output an error because we
23957330f729Sjoerg     // never locked M; although the real error is probably that we forgot to
23967330f729Sjoerg     // lock M on all code paths. Conversely, let's say that later we lock M.
23977330f729Sjoerg     // In this case, we should compare against the intersection instead of the
23987330f729Sjoerg     // union because the real error is probably that we forgot to unlock M on
23997330f729Sjoerg     // all code paths.
24007330f729Sjoerg     bool LocksetInitialized = false;
24017330f729Sjoerg     SmallVector<CFGBlock *, 8> SpecialBlocks;
24027330f729Sjoerg     for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
24037330f729Sjoerg          PE  = CurrBlock->pred_end(); PI != PE; ++PI) {
24047330f729Sjoerg       // if *PI -> CurrBlock is a back edge
24057330f729Sjoerg       if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
24067330f729Sjoerg         continue;
24077330f729Sjoerg 
24087330f729Sjoerg       unsigned PrevBlockID = (*PI)->getBlockID();
24097330f729Sjoerg       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
24107330f729Sjoerg 
24117330f729Sjoerg       // Ignore edges from blocks that can't return.
24127330f729Sjoerg       if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
24137330f729Sjoerg         continue;
24147330f729Sjoerg 
24157330f729Sjoerg       // Okay, we can reach this block from the entry.
24167330f729Sjoerg       CurrBlockInfo->Reachable = true;
24177330f729Sjoerg 
24187330f729Sjoerg       // If the previous block ended in a 'continue' or 'break' statement, then
24197330f729Sjoerg       // a difference in locksets is probably due to a bug in that block, rather
24207330f729Sjoerg       // than in some other predecessor. In that case, keep the other
24217330f729Sjoerg       // predecessor's lockset.
24227330f729Sjoerg       if (const Stmt *Terminator = (*PI)->getTerminatorStmt()) {
24237330f729Sjoerg         if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
24247330f729Sjoerg           SpecialBlocks.push_back(*PI);
24257330f729Sjoerg           continue;
24267330f729Sjoerg         }
24277330f729Sjoerg       }
24287330f729Sjoerg 
24297330f729Sjoerg       FactSet PrevLockset;
24307330f729Sjoerg       getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
24317330f729Sjoerg 
24327330f729Sjoerg       if (!LocksetInitialized) {
24337330f729Sjoerg         CurrBlockInfo->EntrySet = PrevLockset;
24347330f729Sjoerg         LocksetInitialized = true;
24357330f729Sjoerg       } else {
24367330f729Sjoerg         intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
24377330f729Sjoerg                          CurrBlockInfo->EntryLoc,
24387330f729Sjoerg                          LEK_LockedSomePredecessors);
24397330f729Sjoerg       }
24407330f729Sjoerg     }
24417330f729Sjoerg 
24427330f729Sjoerg     // Skip rest of block if it's not reachable.
24437330f729Sjoerg     if (!CurrBlockInfo->Reachable)
24447330f729Sjoerg       continue;
24457330f729Sjoerg 
24467330f729Sjoerg     // Process continue and break blocks. Assume that the lockset for the
24477330f729Sjoerg     // resulting block is unaffected by any discrepancies in them.
24487330f729Sjoerg     for (const auto *PrevBlock : SpecialBlocks) {
24497330f729Sjoerg       unsigned PrevBlockID = PrevBlock->getBlockID();
24507330f729Sjoerg       CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
24517330f729Sjoerg 
24527330f729Sjoerg       if (!LocksetInitialized) {
24537330f729Sjoerg         CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
24547330f729Sjoerg         LocksetInitialized = true;
24557330f729Sjoerg       } else {
24567330f729Sjoerg         // Determine whether this edge is a loop terminator for diagnostic
24577330f729Sjoerg         // purposes. FIXME: A 'break' statement might be a loop terminator, but
24587330f729Sjoerg         // it might also be part of a switch. Also, a subsequent destructor
24597330f729Sjoerg         // might add to the lockset, in which case the real issue might be a
24607330f729Sjoerg         // double lock on the other path.
24617330f729Sjoerg         const Stmt *Terminator = PrevBlock->getTerminatorStmt();
24627330f729Sjoerg         bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
24637330f729Sjoerg 
24647330f729Sjoerg         FactSet PrevLockset;
24657330f729Sjoerg         getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
24667330f729Sjoerg                        PrevBlock, CurrBlock);
24677330f729Sjoerg 
24687330f729Sjoerg         // Do not update EntrySet.
2469*e038c9c4Sjoerg         intersectAndWarn(
2470*e038c9c4Sjoerg             CurrBlockInfo->EntrySet, PrevLockset, PrevBlockInfo->ExitLoc,
2471*e038c9c4Sjoerg             IsLoop ? LEK_LockedSomeLoopIterations : LEK_LockedSomePredecessors);
24727330f729Sjoerg       }
24737330f729Sjoerg     }
24747330f729Sjoerg 
24757330f729Sjoerg     BuildLockset LocksetBuilder(this, *CurrBlockInfo);
24767330f729Sjoerg 
24777330f729Sjoerg     // Visit all the statements in the basic block.
24787330f729Sjoerg     for (const auto &BI : *CurrBlock) {
24797330f729Sjoerg       switch (BI.getKind()) {
24807330f729Sjoerg         case CFGElement::Statement: {
24817330f729Sjoerg           CFGStmt CS = BI.castAs<CFGStmt>();
24827330f729Sjoerg           LocksetBuilder.Visit(CS.getStmt());
24837330f729Sjoerg           break;
24847330f729Sjoerg         }
24857330f729Sjoerg         // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
24867330f729Sjoerg         case CFGElement::AutomaticObjectDtor: {
24877330f729Sjoerg           CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
24887330f729Sjoerg           const auto *DD = AD.getDestructorDecl(AC.getASTContext());
24897330f729Sjoerg           if (!DD->hasAttrs())
24907330f729Sjoerg             break;
24917330f729Sjoerg 
24927330f729Sjoerg           // Create a dummy expression,
24937330f729Sjoerg           auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
24947330f729Sjoerg           DeclRefExpr DRE(VD->getASTContext(), VD, false,
24957330f729Sjoerg                           VD->getType().getNonReferenceType(), VK_LValue,
24967330f729Sjoerg                           AD.getTriggerStmt()->getEndLoc());
24977330f729Sjoerg           LocksetBuilder.handleCall(&DRE, DD);
24987330f729Sjoerg           break;
24997330f729Sjoerg         }
25007330f729Sjoerg         default:
25017330f729Sjoerg           break;
25027330f729Sjoerg       }
25037330f729Sjoerg     }
25047330f729Sjoerg     CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
25057330f729Sjoerg 
25067330f729Sjoerg     // For every back edge from CurrBlock (the end of the loop) to another block
25077330f729Sjoerg     // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
25087330f729Sjoerg     // the one held at the beginning of FirstLoopBlock. We can look up the
25097330f729Sjoerg     // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
25107330f729Sjoerg     for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
25117330f729Sjoerg          SE  = CurrBlock->succ_end(); SI != SE; ++SI) {
25127330f729Sjoerg       // if CurrBlock -> *SI is *not* a back edge
25137330f729Sjoerg       if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
25147330f729Sjoerg         continue;
25157330f729Sjoerg 
25167330f729Sjoerg       CFGBlock *FirstLoopBlock = *SI;
25177330f729Sjoerg       CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
25187330f729Sjoerg       CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2519*e038c9c4Sjoerg       intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet, PreLoop->EntryLoc,
2520*e038c9c4Sjoerg                        LEK_LockedSomeLoopIterations);
25217330f729Sjoerg     }
25227330f729Sjoerg   }
25237330f729Sjoerg 
25247330f729Sjoerg   CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
25257330f729Sjoerg   CFGBlockInfo *Final   = &BlockInfo[CFGraph->getExit().getBlockID()];
25267330f729Sjoerg 
25277330f729Sjoerg   // Skip the final check if the exit block is unreachable.
25287330f729Sjoerg   if (!Final->Reachable)
25297330f729Sjoerg     return;
25307330f729Sjoerg 
25317330f729Sjoerg   // By default, we expect all locks held on entry to be held on exit.
25327330f729Sjoerg   FactSet ExpectedExitSet = Initial->EntrySet;
25337330f729Sjoerg 
25347330f729Sjoerg   // Adjust the expected exit set by adding or removing locks, as declared
25357330f729Sjoerg   // by *-LOCK_FUNCTION and UNLOCK_FUNCTION.  The intersect below will then
25367330f729Sjoerg   // issue the appropriate warning.
25377330f729Sjoerg   // FIXME: the location here is not quite right.
25387330f729Sjoerg   for (const auto &Lock : ExclusiveLocksAcquired)
25397330f729Sjoerg     ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
25407330f729Sjoerg                                          Lock, LK_Exclusive, D->getLocation()));
25417330f729Sjoerg   for (const auto &Lock : SharedLocksAcquired)
25427330f729Sjoerg     ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
25437330f729Sjoerg                                          Lock, LK_Shared, D->getLocation()));
25447330f729Sjoerg   for (const auto &Lock : LocksReleased)
25457330f729Sjoerg     ExpectedExitSet.removeLock(FactMan, Lock);
25467330f729Sjoerg 
25477330f729Sjoerg   // FIXME: Should we call this function for all blocks which exit the function?
2548*e038c9c4Sjoerg   intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
2549*e038c9c4Sjoerg                    LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction);
25507330f729Sjoerg 
25517330f729Sjoerg   Handler.leaveFunction(CurrentFunction);
25527330f729Sjoerg }
25537330f729Sjoerg 
25547330f729Sjoerg /// Check a function's CFG for thread-safety violations.
25557330f729Sjoerg ///
25567330f729Sjoerg /// We traverse the blocks in the CFG, compute the set of mutexes that are held
25577330f729Sjoerg /// at the end of each block, and issue warnings for thread safety violations.
25587330f729Sjoerg /// Each block in the CFG is traversed exactly once.
runThreadSafetyAnalysis(AnalysisDeclContext & AC,ThreadSafetyHandler & Handler,BeforeSet ** BSet)25597330f729Sjoerg void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
25607330f729Sjoerg                                            ThreadSafetyHandler &Handler,
25617330f729Sjoerg                                            BeforeSet **BSet) {
25627330f729Sjoerg   if (!*BSet)
25637330f729Sjoerg     *BSet = new BeforeSet;
25647330f729Sjoerg   ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
25657330f729Sjoerg   Analyzer.runAnalysis(AC);
25667330f729Sjoerg }
25677330f729Sjoerg 
threadSafetyCleanup(BeforeSet * Cache)25687330f729Sjoerg void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
25697330f729Sjoerg 
25707330f729Sjoerg /// Helper function that returns a LockKind required for the given level
25717330f729Sjoerg /// of access.
getLockKindFromAccessKind(AccessKind AK)25727330f729Sjoerg LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
25737330f729Sjoerg   switch (AK) {
25747330f729Sjoerg     case AK_Read :
25757330f729Sjoerg       return LK_Shared;
25767330f729Sjoerg     case AK_Written :
25777330f729Sjoerg       return LK_Exclusive;
25787330f729Sjoerg   }
25797330f729Sjoerg   llvm_unreachable("Unknown AccessKind");
25807330f729Sjoerg }
2581