10b57cec5SDimitry Andric //===- ThreadSafety.cpp ---------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric // 90b57cec5SDimitry Andric // A intra-procedural analysis for thread safety (e.g. deadlocks and race 100b57cec5SDimitry Andric // conditions), based off of an annotation system. 110b57cec5SDimitry Andric // 120b57cec5SDimitry Andric // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html 130b57cec5SDimitry Andric // for more information. 140b57cec5SDimitry Andric // 150b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 160b57cec5SDimitry Andric 170b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafety.h" 180b57cec5SDimitry Andric #include "clang/AST/Attr.h" 190b57cec5SDimitry Andric #include "clang/AST/Decl.h" 200b57cec5SDimitry Andric #include "clang/AST/DeclCXX.h" 210b57cec5SDimitry Andric #include "clang/AST/DeclGroup.h" 220b57cec5SDimitry Andric #include "clang/AST/Expr.h" 230b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h" 240b57cec5SDimitry Andric #include "clang/AST/OperationKinds.h" 250b57cec5SDimitry Andric #include "clang/AST/Stmt.h" 260b57cec5SDimitry Andric #include "clang/AST/StmtVisitor.h" 270b57cec5SDimitry Andric #include "clang/AST/Type.h" 280b57cec5SDimitry Andric #include "clang/Analysis/Analyses/PostOrderCFGView.h" 290b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyCommon.h" 300b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyTIL.h" 310b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h" 320b57cec5SDimitry Andric #include "clang/Analysis/Analyses/ThreadSafetyUtil.h" 330b57cec5SDimitry Andric #include "clang/Analysis/AnalysisDeclContext.h" 340b57cec5SDimitry Andric #include "clang/Analysis/CFG.h" 350b57cec5SDimitry Andric #include "clang/Basic/Builtins.h" 360b57cec5SDimitry Andric #include "clang/Basic/LLVM.h" 370b57cec5SDimitry Andric #include "clang/Basic/OperatorKinds.h" 380b57cec5SDimitry Andric #include "clang/Basic/SourceLocation.h" 390b57cec5SDimitry Andric #include "clang/Basic/Specifiers.h" 400b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h" 410b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h" 420b57cec5SDimitry Andric #include "llvm/ADT/ImmutableMap.h" 430b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 440b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h" 450b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h" 460b57cec5SDimitry Andric #include "llvm/Support/Allocator.h" 470b57cec5SDimitry Andric #include "llvm/Support/Casting.h" 480b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 490b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 500b57cec5SDimitry Andric #include <algorithm> 510b57cec5SDimitry Andric #include <cassert> 520b57cec5SDimitry Andric #include <functional> 530b57cec5SDimitry Andric #include <iterator> 540b57cec5SDimitry Andric #include <memory> 55bdd1243dSDimitry Andric #include <optional> 560b57cec5SDimitry Andric #include <string> 570b57cec5SDimitry Andric #include <type_traits> 580b57cec5SDimitry Andric #include <utility> 590b57cec5SDimitry Andric #include <vector> 600b57cec5SDimitry Andric 610b57cec5SDimitry Andric using namespace clang; 620b57cec5SDimitry Andric using namespace threadSafety; 630b57cec5SDimitry Andric 640b57cec5SDimitry Andric // Key method definition 650b57cec5SDimitry Andric ThreadSafetyHandler::~ThreadSafetyHandler() = default; 660b57cec5SDimitry Andric 670b57cec5SDimitry Andric /// Issue a warning about an invalid lock expression 680b57cec5SDimitry Andric static void warnInvalidLock(ThreadSafetyHandler &Handler, 690b57cec5SDimitry Andric const Expr *MutexExp, const NamedDecl *D, 700b57cec5SDimitry Andric const Expr *DeclExp, StringRef Kind) { 710b57cec5SDimitry Andric SourceLocation Loc; 720b57cec5SDimitry Andric if (DeclExp) 730b57cec5SDimitry Andric Loc = DeclExp->getExprLoc(); 740b57cec5SDimitry Andric 750b57cec5SDimitry Andric // FIXME: add a note about the attribute location in MutexExp or D 760b57cec5SDimitry Andric if (Loc.isValid()) 7781ad6265SDimitry Andric Handler.handleInvalidLockExp(Loc); 780b57cec5SDimitry Andric } 790b57cec5SDimitry Andric 800b57cec5SDimitry Andric namespace { 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric /// A set of CapabilityExpr objects, which are compiled from thread safety 830b57cec5SDimitry Andric /// attributes on a function. 840b57cec5SDimitry Andric class CapExprSet : public SmallVector<CapabilityExpr, 4> { 850b57cec5SDimitry Andric public: 860b57cec5SDimitry Andric /// Push M onto list, but discard duplicates. 870b57cec5SDimitry Andric void push_back_nodup(const CapabilityExpr &CapE) { 88349cc55cSDimitry Andric if (llvm::none_of(*this, [=](const CapabilityExpr &CapE2) { 890b57cec5SDimitry Andric return CapE.equals(CapE2); 90349cc55cSDimitry Andric })) 910b57cec5SDimitry Andric push_back(CapE); 920b57cec5SDimitry Andric } 930b57cec5SDimitry Andric }; 940b57cec5SDimitry Andric 950b57cec5SDimitry Andric class FactManager; 960b57cec5SDimitry Andric class FactSet; 970b57cec5SDimitry Andric 980b57cec5SDimitry Andric /// This is a helper class that stores a fact that is known at a 990b57cec5SDimitry Andric /// particular point in program execution. Currently, a fact is a capability, 1000b57cec5SDimitry Andric /// along with additional information, such as where it was acquired, whether 1010b57cec5SDimitry Andric /// it is exclusive or shared, etc. 1020b57cec5SDimitry Andric /// 1030b57cec5SDimitry Andric /// FIXME: this analysis does not currently support re-entrant locking. 1040b57cec5SDimitry Andric class FactEntry : public CapabilityExpr { 105fe6060f1SDimitry Andric public: 106fe6060f1SDimitry Andric /// Where a fact comes from. 107fe6060f1SDimitry Andric enum SourceKind { 108fe6060f1SDimitry Andric Acquired, ///< The fact has been directly acquired. 109fe6060f1SDimitry Andric Asserted, ///< The fact has been asserted to be held. 110fe6060f1SDimitry Andric Declared, ///< The fact is assumed to be held by callers. 111fe6060f1SDimitry Andric Managed, ///< The fact has been acquired through a scoped capability. 112fe6060f1SDimitry Andric }; 113fe6060f1SDimitry Andric 1140b57cec5SDimitry Andric private: 1150b57cec5SDimitry Andric /// Exclusive or shared. 116fe6060f1SDimitry Andric LockKind LKind : 8; 117fe6060f1SDimitry Andric 118fe6060f1SDimitry Andric // How it was acquired. 119fe6060f1SDimitry Andric SourceKind Source : 8; 1200b57cec5SDimitry Andric 1210b57cec5SDimitry Andric /// Where it was acquired. 1220b57cec5SDimitry Andric SourceLocation AcquireLoc; 1230b57cec5SDimitry Andric 1240b57cec5SDimitry Andric public: 1250b57cec5SDimitry Andric FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc, 126fe6060f1SDimitry Andric SourceKind Src) 127fe6060f1SDimitry Andric : CapabilityExpr(CE), LKind(LK), Source(Src), AcquireLoc(Loc) {} 1280b57cec5SDimitry Andric virtual ~FactEntry() = default; 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric LockKind kind() const { return LKind; } 1310b57cec5SDimitry Andric SourceLocation loc() const { return AcquireLoc; } 1320b57cec5SDimitry Andric 133fe6060f1SDimitry Andric bool asserted() const { return Source == Asserted; } 134fe6060f1SDimitry Andric bool declared() const { return Source == Declared; } 135fe6060f1SDimitry Andric bool managed() const { return Source == Managed; } 1360b57cec5SDimitry Andric 1370b57cec5SDimitry Andric virtual void 1380b57cec5SDimitry Andric handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 1390b57cec5SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK, 1400b57cec5SDimitry Andric ThreadSafetyHandler &Handler) const = 0; 1410b57cec5SDimitry Andric virtual void handleLock(FactSet &FSet, FactManager &FactMan, 14281ad6265SDimitry Andric const FactEntry &entry, 14381ad6265SDimitry Andric ThreadSafetyHandler &Handler) const = 0; 1440b57cec5SDimitry Andric virtual void handleUnlock(FactSet &FSet, FactManager &FactMan, 1450b57cec5SDimitry Andric const CapabilityExpr &Cp, SourceLocation UnlockLoc, 14681ad6265SDimitry Andric bool FullyRemove, 14781ad6265SDimitry Andric ThreadSafetyHandler &Handler) const = 0; 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric // Return true if LKind >= LK, where exclusive > shared 1500b57cec5SDimitry Andric bool isAtLeast(LockKind LK) const { 1510b57cec5SDimitry Andric return (LKind == LK_Exclusive) || (LK == LK_Shared); 1520b57cec5SDimitry Andric } 1530b57cec5SDimitry Andric }; 1540b57cec5SDimitry Andric 1550b57cec5SDimitry Andric using FactID = unsigned short; 1560b57cec5SDimitry Andric 1570b57cec5SDimitry Andric /// FactManager manages the memory for all facts that are created during 1580b57cec5SDimitry Andric /// the analysis of a single routine. 1590b57cec5SDimitry Andric class FactManager { 1600b57cec5SDimitry Andric private: 1610b57cec5SDimitry Andric std::vector<std::unique_ptr<const FactEntry>> Facts; 1620b57cec5SDimitry Andric 1630b57cec5SDimitry Andric public: 1640b57cec5SDimitry Andric FactID newFact(std::unique_ptr<FactEntry> Entry) { 1650b57cec5SDimitry Andric Facts.push_back(std::move(Entry)); 1660b57cec5SDimitry Andric return static_cast<unsigned short>(Facts.size() - 1); 1670b57cec5SDimitry Andric } 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric const FactEntry &operator[](FactID F) const { return *Facts[F]; } 1700b57cec5SDimitry Andric }; 1710b57cec5SDimitry Andric 1720b57cec5SDimitry Andric /// A FactSet is the set of facts that are known to be true at a 1730b57cec5SDimitry Andric /// particular program point. FactSets must be small, because they are 1740b57cec5SDimitry Andric /// frequently copied, and are thus implemented as a set of indices into a 1750b57cec5SDimitry Andric /// table maintained by a FactManager. A typical FactSet only holds 1 or 2 1760b57cec5SDimitry Andric /// locks, so we can get away with doing a linear search for lookup. Note 1770b57cec5SDimitry Andric /// that a hashtable or map is inappropriate in this case, because lookups 1780b57cec5SDimitry Andric /// may involve partial pattern matches, rather than exact matches. 1790b57cec5SDimitry Andric class FactSet { 1800b57cec5SDimitry Andric private: 1810b57cec5SDimitry Andric using FactVec = SmallVector<FactID, 4>; 1820b57cec5SDimitry Andric 1830b57cec5SDimitry Andric FactVec FactIDs; 1840b57cec5SDimitry Andric 1850b57cec5SDimitry Andric public: 1860b57cec5SDimitry Andric using iterator = FactVec::iterator; 1870b57cec5SDimitry Andric using const_iterator = FactVec::const_iterator; 1880b57cec5SDimitry Andric 1890b57cec5SDimitry Andric iterator begin() { return FactIDs.begin(); } 1900b57cec5SDimitry Andric const_iterator begin() const { return FactIDs.begin(); } 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric iterator end() { return FactIDs.end(); } 1930b57cec5SDimitry Andric const_iterator end() const { return FactIDs.end(); } 1940b57cec5SDimitry Andric 1950b57cec5SDimitry Andric bool isEmpty() const { return FactIDs.size() == 0; } 1960b57cec5SDimitry Andric 1970b57cec5SDimitry Andric // Return true if the set contains only negative facts 1980b57cec5SDimitry Andric bool isEmpty(FactManager &FactMan) const { 1990b57cec5SDimitry Andric for (const auto FID : *this) { 2000b57cec5SDimitry Andric if (!FactMan[FID].negative()) 2010b57cec5SDimitry Andric return false; 2020b57cec5SDimitry Andric } 2030b57cec5SDimitry Andric return true; 2040b57cec5SDimitry Andric } 2050b57cec5SDimitry Andric 2060b57cec5SDimitry Andric void addLockByID(FactID ID) { FactIDs.push_back(ID); } 2070b57cec5SDimitry Andric 2080b57cec5SDimitry Andric FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) { 2090b57cec5SDimitry Andric FactID F = FM.newFact(std::move(Entry)); 2100b57cec5SDimitry Andric FactIDs.push_back(F); 2110b57cec5SDimitry Andric return F; 2120b57cec5SDimitry Andric } 2130b57cec5SDimitry Andric 2140b57cec5SDimitry Andric bool removeLock(FactManager& FM, const CapabilityExpr &CapE) { 2150b57cec5SDimitry Andric unsigned n = FactIDs.size(); 2160b57cec5SDimitry Andric if (n == 0) 2170b57cec5SDimitry Andric return false; 2180b57cec5SDimitry Andric 2190b57cec5SDimitry Andric for (unsigned i = 0; i < n-1; ++i) { 2200b57cec5SDimitry Andric if (FM[FactIDs[i]].matches(CapE)) { 2210b57cec5SDimitry Andric FactIDs[i] = FactIDs[n-1]; 2220b57cec5SDimitry Andric FactIDs.pop_back(); 2230b57cec5SDimitry Andric return true; 2240b57cec5SDimitry Andric } 2250b57cec5SDimitry Andric } 2260b57cec5SDimitry Andric if (FM[FactIDs[n-1]].matches(CapE)) { 2270b57cec5SDimitry Andric FactIDs.pop_back(); 2280b57cec5SDimitry Andric return true; 2290b57cec5SDimitry Andric } 2300b57cec5SDimitry Andric return false; 2310b57cec5SDimitry Andric } 2320b57cec5SDimitry Andric 2330b57cec5SDimitry Andric iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) { 2340b57cec5SDimitry Andric return std::find_if(begin(), end(), [&](FactID ID) { 2350b57cec5SDimitry Andric return FM[ID].matches(CapE); 2360b57cec5SDimitry Andric }); 2370b57cec5SDimitry Andric } 2380b57cec5SDimitry Andric 2390b57cec5SDimitry Andric const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const { 2400b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) { 2410b57cec5SDimitry Andric return FM[ID].matches(CapE); 2420b57cec5SDimitry Andric }); 2430b57cec5SDimitry Andric return I != end() ? &FM[*I] : nullptr; 2440b57cec5SDimitry Andric } 2450b57cec5SDimitry Andric 2460b57cec5SDimitry Andric const FactEntry *findLockUniv(FactManager &FM, 2470b57cec5SDimitry Andric const CapabilityExpr &CapE) const { 2480b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 2490b57cec5SDimitry Andric return FM[ID].matchesUniv(CapE); 2500b57cec5SDimitry Andric }); 2510b57cec5SDimitry Andric return I != end() ? &FM[*I] : nullptr; 2520b57cec5SDimitry Andric } 2530b57cec5SDimitry Andric 2540b57cec5SDimitry Andric const FactEntry *findPartialMatch(FactManager &FM, 2550b57cec5SDimitry Andric const CapabilityExpr &CapE) const { 2560b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 2570b57cec5SDimitry Andric return FM[ID].partiallyMatches(CapE); 2580b57cec5SDimitry Andric }); 2590b57cec5SDimitry Andric return I != end() ? &FM[*I] : nullptr; 2600b57cec5SDimitry Andric } 2610b57cec5SDimitry Andric 2620b57cec5SDimitry Andric bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const { 2630b57cec5SDimitry Andric auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool { 2640b57cec5SDimitry Andric return FM[ID].valueDecl() == Vd; 2650b57cec5SDimitry Andric }); 2660b57cec5SDimitry Andric return I != end(); 2670b57cec5SDimitry Andric } 2680b57cec5SDimitry Andric }; 2690b57cec5SDimitry Andric 2700b57cec5SDimitry Andric class ThreadSafetyAnalyzer; 2710b57cec5SDimitry Andric 2720b57cec5SDimitry Andric } // namespace 2730b57cec5SDimitry Andric 2740b57cec5SDimitry Andric namespace clang { 2750b57cec5SDimitry Andric namespace threadSafety { 2760b57cec5SDimitry Andric 2770b57cec5SDimitry Andric class BeforeSet { 2780b57cec5SDimitry Andric private: 2790b57cec5SDimitry Andric using BeforeVect = SmallVector<const ValueDecl *, 4>; 2800b57cec5SDimitry Andric 2810b57cec5SDimitry Andric struct BeforeInfo { 2820b57cec5SDimitry Andric BeforeVect Vect; 2830b57cec5SDimitry Andric int Visited = 0; 2840b57cec5SDimitry Andric 2850b57cec5SDimitry Andric BeforeInfo() = default; 2860b57cec5SDimitry Andric BeforeInfo(BeforeInfo &&) = default; 2870b57cec5SDimitry Andric }; 2880b57cec5SDimitry Andric 2890b57cec5SDimitry Andric using BeforeMap = 2900b57cec5SDimitry Andric llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>; 2910b57cec5SDimitry Andric using CycleMap = llvm::DenseMap<const ValueDecl *, bool>; 2920b57cec5SDimitry Andric 2930b57cec5SDimitry Andric public: 2940b57cec5SDimitry Andric BeforeSet() = default; 2950b57cec5SDimitry Andric 2960b57cec5SDimitry Andric BeforeInfo* insertAttrExprs(const ValueDecl* Vd, 2970b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer); 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd, 3000b57cec5SDimitry Andric ThreadSafetyAnalyzer &Analyzer); 3010b57cec5SDimitry Andric 3020b57cec5SDimitry Andric void checkBeforeAfter(const ValueDecl* Vd, 3030b57cec5SDimitry Andric const FactSet& FSet, 3040b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer, 3050b57cec5SDimitry Andric SourceLocation Loc, StringRef CapKind); 3060b57cec5SDimitry Andric 3070b57cec5SDimitry Andric private: 3080b57cec5SDimitry Andric BeforeMap BMap; 3090b57cec5SDimitry Andric CycleMap CycMap; 3100b57cec5SDimitry Andric }; 3110b57cec5SDimitry Andric 3120b57cec5SDimitry Andric } // namespace threadSafety 3130b57cec5SDimitry Andric } // namespace clang 3140b57cec5SDimitry Andric 3150b57cec5SDimitry Andric namespace { 3160b57cec5SDimitry Andric 3170b57cec5SDimitry Andric class LocalVariableMap; 3180b57cec5SDimitry Andric 3190b57cec5SDimitry Andric using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>; 3200b57cec5SDimitry Andric 3210b57cec5SDimitry Andric /// A side (entry or exit) of a CFG node. 3220b57cec5SDimitry Andric enum CFGBlockSide { CBS_Entry, CBS_Exit }; 3230b57cec5SDimitry Andric 3240b57cec5SDimitry Andric /// CFGBlockInfo is a struct which contains all the information that is 3250b57cec5SDimitry Andric /// maintained for each block in the CFG. See LocalVariableMap for more 3260b57cec5SDimitry Andric /// information about the contexts. 3270b57cec5SDimitry Andric struct CFGBlockInfo { 3280b57cec5SDimitry Andric // Lockset held at entry to block 3290b57cec5SDimitry Andric FactSet EntrySet; 3300b57cec5SDimitry Andric 3310b57cec5SDimitry Andric // Lockset held at exit from block 3320b57cec5SDimitry Andric FactSet ExitSet; 3330b57cec5SDimitry Andric 3340b57cec5SDimitry Andric // Context held at entry to block 3350b57cec5SDimitry Andric LocalVarContext EntryContext; 3360b57cec5SDimitry Andric 3370b57cec5SDimitry Andric // Context held at exit from block 3380b57cec5SDimitry Andric LocalVarContext ExitContext; 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric // Location of first statement in block 3410b57cec5SDimitry Andric SourceLocation EntryLoc; 3420b57cec5SDimitry Andric 3430b57cec5SDimitry Andric // Location of last statement in block. 3440b57cec5SDimitry Andric SourceLocation ExitLoc; 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric // Used to replay contexts later 3470b57cec5SDimitry Andric unsigned EntryIndex; 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric // Is this block reachable? 3500b57cec5SDimitry Andric bool Reachable = false; 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric const FactSet &getSet(CFGBlockSide Side) const { 3530b57cec5SDimitry Andric return Side == CBS_Entry ? EntrySet : ExitSet; 3540b57cec5SDimitry Andric } 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric SourceLocation getLocation(CFGBlockSide Side) const { 3570b57cec5SDimitry Andric return Side == CBS_Entry ? EntryLoc : ExitLoc; 3580b57cec5SDimitry Andric } 3590b57cec5SDimitry Andric 3600b57cec5SDimitry Andric private: 3610b57cec5SDimitry Andric CFGBlockInfo(LocalVarContext EmptyCtx) 3620b57cec5SDimitry Andric : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {} 3630b57cec5SDimitry Andric 3640b57cec5SDimitry Andric public: 3650b57cec5SDimitry Andric static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M); 3660b57cec5SDimitry Andric }; 3670b57cec5SDimitry Andric 3680b57cec5SDimitry Andric // A LocalVariableMap maintains a map from local variables to their currently 3690b57cec5SDimitry Andric // valid definitions. It provides SSA-like functionality when traversing the 3700b57cec5SDimitry Andric // CFG. Like SSA, each definition or assignment to a variable is assigned a 3710b57cec5SDimitry Andric // unique name (an integer), which acts as the SSA name for that definition. 3720b57cec5SDimitry Andric // The total set of names is shared among all CFG basic blocks. 3730b57cec5SDimitry Andric // Unlike SSA, we do not rewrite expressions to replace local variables declrefs 3740b57cec5SDimitry Andric // with their SSA-names. Instead, we compute a Context for each point in the 3750b57cec5SDimitry Andric // code, which maps local variables to the appropriate SSA-name. This map 3760b57cec5SDimitry Andric // changes with each assignment. 3770b57cec5SDimitry Andric // 3780b57cec5SDimitry Andric // The map is computed in a single pass over the CFG. Subsequent analyses can 3790b57cec5SDimitry Andric // then query the map to find the appropriate Context for a statement, and use 3800b57cec5SDimitry Andric // that Context to look up the definitions of variables. 3810b57cec5SDimitry Andric class LocalVariableMap { 3820b57cec5SDimitry Andric public: 3830b57cec5SDimitry Andric using Context = LocalVarContext; 3840b57cec5SDimitry Andric 3850b57cec5SDimitry Andric /// A VarDefinition consists of an expression, representing the value of the 3860b57cec5SDimitry Andric /// variable, along with the context in which that expression should be 3870b57cec5SDimitry Andric /// interpreted. A reference VarDefinition does not itself contain this 3880b57cec5SDimitry Andric /// information, but instead contains a pointer to a previous VarDefinition. 3890b57cec5SDimitry Andric struct VarDefinition { 3900b57cec5SDimitry Andric public: 3910b57cec5SDimitry Andric friend class LocalVariableMap; 3920b57cec5SDimitry Andric 3930b57cec5SDimitry Andric // The original declaration for this variable. 3940b57cec5SDimitry Andric const NamedDecl *Dec; 3950b57cec5SDimitry Andric 3960b57cec5SDimitry Andric // The expression for this variable, OR 3970b57cec5SDimitry Andric const Expr *Exp = nullptr; 3980b57cec5SDimitry Andric 3990b57cec5SDimitry Andric // Reference to another VarDefinition 4000b57cec5SDimitry Andric unsigned Ref = 0; 4010b57cec5SDimitry Andric 4020b57cec5SDimitry Andric // The map with which Exp should be interpreted. 4030b57cec5SDimitry Andric Context Ctx; 4040b57cec5SDimitry Andric 40506c3fb27SDimitry Andric bool isReference() const { return !Exp; } 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric private: 4080b57cec5SDimitry Andric // Create ordinary variable definition 4090b57cec5SDimitry Andric VarDefinition(const NamedDecl *D, const Expr *E, Context C) 4100b57cec5SDimitry Andric : Dec(D), Exp(E), Ctx(C) {} 4110b57cec5SDimitry Andric 4120b57cec5SDimitry Andric // Create reference to previous definition 4130b57cec5SDimitry Andric VarDefinition(const NamedDecl *D, unsigned R, Context C) 4140b57cec5SDimitry Andric : Dec(D), Ref(R), Ctx(C) {} 4150b57cec5SDimitry Andric }; 4160b57cec5SDimitry Andric 4170b57cec5SDimitry Andric private: 4180b57cec5SDimitry Andric Context::Factory ContextFactory; 4190b57cec5SDimitry Andric std::vector<VarDefinition> VarDefinitions; 4200b57cec5SDimitry Andric std::vector<std::pair<const Stmt *, Context>> SavedContexts; 4210b57cec5SDimitry Andric 4220b57cec5SDimitry Andric public: 4230b57cec5SDimitry Andric LocalVariableMap() { 4240b57cec5SDimitry Andric // index 0 is a placeholder for undefined variables (aka phi-nodes). 4250b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext())); 4260b57cec5SDimitry Andric } 4270b57cec5SDimitry Andric 4280b57cec5SDimitry Andric /// Look up a definition, within the given context. 4290b57cec5SDimitry Andric const VarDefinition* lookup(const NamedDecl *D, Context Ctx) { 4300b57cec5SDimitry Andric const unsigned *i = Ctx.lookup(D); 4310b57cec5SDimitry Andric if (!i) 4320b57cec5SDimitry Andric return nullptr; 4330b57cec5SDimitry Andric assert(*i < VarDefinitions.size()); 4340b57cec5SDimitry Andric return &VarDefinitions[*i]; 4350b57cec5SDimitry Andric } 4360b57cec5SDimitry Andric 4370b57cec5SDimitry Andric /// Look up the definition for D within the given context. Returns 4380b57cec5SDimitry Andric /// NULL if the expression is not statically known. If successful, also 4390b57cec5SDimitry Andric /// modifies Ctx to hold the context of the return Expr. 4400b57cec5SDimitry Andric const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) { 4410b57cec5SDimitry Andric const unsigned *P = Ctx.lookup(D); 4420b57cec5SDimitry Andric if (!P) 4430b57cec5SDimitry Andric return nullptr; 4440b57cec5SDimitry Andric 4450b57cec5SDimitry Andric unsigned i = *P; 4460b57cec5SDimitry Andric while (i > 0) { 4470b57cec5SDimitry Andric if (VarDefinitions[i].Exp) { 4480b57cec5SDimitry Andric Ctx = VarDefinitions[i].Ctx; 4490b57cec5SDimitry Andric return VarDefinitions[i].Exp; 4500b57cec5SDimitry Andric } 4510b57cec5SDimitry Andric i = VarDefinitions[i].Ref; 4520b57cec5SDimitry Andric } 4530b57cec5SDimitry Andric return nullptr; 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric Context getEmptyContext() { return ContextFactory.getEmptyMap(); } 4570b57cec5SDimitry Andric 4580b57cec5SDimitry Andric /// Return the next context after processing S. This function is used by 4590b57cec5SDimitry Andric /// clients of the class to get the appropriate context when traversing the 4600b57cec5SDimitry Andric /// CFG. It must be called for every assignment or DeclStmt. 4610b57cec5SDimitry Andric Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) { 4620b57cec5SDimitry Andric if (SavedContexts[CtxIndex+1].first == S) { 4630b57cec5SDimitry Andric CtxIndex++; 4640b57cec5SDimitry Andric Context Result = SavedContexts[CtxIndex].second; 4650b57cec5SDimitry Andric return Result; 4660b57cec5SDimitry Andric } 4670b57cec5SDimitry Andric return C; 4680b57cec5SDimitry Andric } 4690b57cec5SDimitry Andric 4700b57cec5SDimitry Andric void dumpVarDefinitionName(unsigned i) { 4710b57cec5SDimitry Andric if (i == 0) { 4720b57cec5SDimitry Andric llvm::errs() << "Undefined"; 4730b57cec5SDimitry Andric return; 4740b57cec5SDimitry Andric } 4750b57cec5SDimitry Andric const NamedDecl *Dec = VarDefinitions[i].Dec; 4760b57cec5SDimitry Andric if (!Dec) { 4770b57cec5SDimitry Andric llvm::errs() << "<<NULL>>"; 4780b57cec5SDimitry Andric return; 4790b57cec5SDimitry Andric } 4800b57cec5SDimitry Andric Dec->printName(llvm::errs()); 4810b57cec5SDimitry Andric llvm::errs() << "." << i << " " << ((const void*) Dec); 4820b57cec5SDimitry Andric } 4830b57cec5SDimitry Andric 4840b57cec5SDimitry Andric /// Dumps an ASCII representation of the variable map to llvm::errs() 4850b57cec5SDimitry Andric void dump() { 4860b57cec5SDimitry Andric for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) { 4870b57cec5SDimitry Andric const Expr *Exp = VarDefinitions[i].Exp; 4880b57cec5SDimitry Andric unsigned Ref = VarDefinitions[i].Ref; 4890b57cec5SDimitry Andric 4900b57cec5SDimitry Andric dumpVarDefinitionName(i); 4910b57cec5SDimitry Andric llvm::errs() << " = "; 4920b57cec5SDimitry Andric if (Exp) Exp->dump(); 4930b57cec5SDimitry Andric else { 4940b57cec5SDimitry Andric dumpVarDefinitionName(Ref); 4950b57cec5SDimitry Andric llvm::errs() << "\n"; 4960b57cec5SDimitry Andric } 4970b57cec5SDimitry Andric } 4980b57cec5SDimitry Andric } 4990b57cec5SDimitry Andric 5000b57cec5SDimitry Andric /// Dumps an ASCII representation of a Context to llvm::errs() 5010b57cec5SDimitry Andric void dumpContext(Context C) { 5020b57cec5SDimitry Andric for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) { 5030b57cec5SDimitry Andric const NamedDecl *D = I.getKey(); 5040b57cec5SDimitry Andric D->printName(llvm::errs()); 5050b57cec5SDimitry Andric llvm::errs() << " -> "; 50606c3fb27SDimitry Andric dumpVarDefinitionName(I.getData()); 5070b57cec5SDimitry Andric llvm::errs() << "\n"; 5080b57cec5SDimitry Andric } 5090b57cec5SDimitry Andric } 5100b57cec5SDimitry Andric 5110b57cec5SDimitry Andric /// Builds the variable map. 5120b57cec5SDimitry Andric void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph, 5130b57cec5SDimitry Andric std::vector<CFGBlockInfo> &BlockInfo); 5140b57cec5SDimitry Andric 5150b57cec5SDimitry Andric protected: 5160b57cec5SDimitry Andric friend class VarMapBuilder; 5170b57cec5SDimitry Andric 5180b57cec5SDimitry Andric // Get the current context index 5190b57cec5SDimitry Andric unsigned getContextIndex() { return SavedContexts.size()-1; } 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric // Save the current context for later replay 5220b57cec5SDimitry Andric void saveContext(const Stmt *S, Context C) { 5230b57cec5SDimitry Andric SavedContexts.push_back(std::make_pair(S, C)); 5240b57cec5SDimitry Andric } 5250b57cec5SDimitry Andric 5260b57cec5SDimitry Andric // Adds a new definition to the given context, and returns a new context. 5270b57cec5SDimitry Andric // This method should be called when declaring a new variable. 5280b57cec5SDimitry Andric Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) { 5290b57cec5SDimitry Andric assert(!Ctx.contains(D)); 5300b57cec5SDimitry Andric unsigned newID = VarDefinitions.size(); 5310b57cec5SDimitry Andric Context NewCtx = ContextFactory.add(Ctx, D, newID); 5320b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 5330b57cec5SDimitry Andric return NewCtx; 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric 5360b57cec5SDimitry Andric // Add a new reference to an existing definition. 5370b57cec5SDimitry Andric Context addReference(const NamedDecl *D, unsigned i, Context Ctx) { 5380b57cec5SDimitry Andric unsigned newID = VarDefinitions.size(); 5390b57cec5SDimitry Andric Context NewCtx = ContextFactory.add(Ctx, D, newID); 5400b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(D, i, Ctx)); 5410b57cec5SDimitry Andric return NewCtx; 5420b57cec5SDimitry Andric } 5430b57cec5SDimitry Andric 5440b57cec5SDimitry Andric // Updates a definition only if that definition is already in the map. 5450b57cec5SDimitry Andric // This method should be called when assigning to an existing variable. 5460b57cec5SDimitry Andric Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) { 5470b57cec5SDimitry Andric if (Ctx.contains(D)) { 5480b57cec5SDimitry Andric unsigned newID = VarDefinitions.size(); 5490b57cec5SDimitry Andric Context NewCtx = ContextFactory.remove(Ctx, D); 5500b57cec5SDimitry Andric NewCtx = ContextFactory.add(NewCtx, D, newID); 5510b57cec5SDimitry Andric VarDefinitions.push_back(VarDefinition(D, Exp, Ctx)); 5520b57cec5SDimitry Andric return NewCtx; 5530b57cec5SDimitry Andric } 5540b57cec5SDimitry Andric return Ctx; 5550b57cec5SDimitry Andric } 5560b57cec5SDimitry Andric 5570b57cec5SDimitry Andric // Removes a definition from the context, but keeps the variable name 5580b57cec5SDimitry Andric // as a valid variable. The index 0 is a placeholder for cleared definitions. 5590b57cec5SDimitry Andric Context clearDefinition(const NamedDecl *D, Context Ctx) { 5600b57cec5SDimitry Andric Context NewCtx = Ctx; 5610b57cec5SDimitry Andric if (NewCtx.contains(D)) { 5620b57cec5SDimitry Andric NewCtx = ContextFactory.remove(NewCtx, D); 5630b57cec5SDimitry Andric NewCtx = ContextFactory.add(NewCtx, D, 0); 5640b57cec5SDimitry Andric } 5650b57cec5SDimitry Andric return NewCtx; 5660b57cec5SDimitry Andric } 5670b57cec5SDimitry Andric 5680b57cec5SDimitry Andric // Remove a definition entirely frmo the context. 5690b57cec5SDimitry Andric Context removeDefinition(const NamedDecl *D, Context Ctx) { 5700b57cec5SDimitry Andric Context NewCtx = Ctx; 5710b57cec5SDimitry Andric if (NewCtx.contains(D)) { 5720b57cec5SDimitry Andric NewCtx = ContextFactory.remove(NewCtx, D); 5730b57cec5SDimitry Andric } 5740b57cec5SDimitry Andric return NewCtx; 5750b57cec5SDimitry Andric } 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric Context intersectContexts(Context C1, Context C2); 5780b57cec5SDimitry Andric Context createReferenceContext(Context C); 5790b57cec5SDimitry Andric void intersectBackEdge(Context C1, Context C2); 5800b57cec5SDimitry Andric }; 5810b57cec5SDimitry Andric 5820b57cec5SDimitry Andric } // namespace 5830b57cec5SDimitry Andric 5840b57cec5SDimitry Andric // This has to be defined after LocalVariableMap. 5850b57cec5SDimitry Andric CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) { 5860b57cec5SDimitry Andric return CFGBlockInfo(M.getEmptyContext()); 5870b57cec5SDimitry Andric } 5880b57cec5SDimitry Andric 5890b57cec5SDimitry Andric namespace { 5900b57cec5SDimitry Andric 5910b57cec5SDimitry Andric /// Visitor which builds a LocalVariableMap 5920b57cec5SDimitry Andric class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> { 5930b57cec5SDimitry Andric public: 5940b57cec5SDimitry Andric LocalVariableMap* VMap; 5950b57cec5SDimitry Andric LocalVariableMap::Context Ctx; 5960b57cec5SDimitry Andric 5970b57cec5SDimitry Andric VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C) 5980b57cec5SDimitry Andric : VMap(VM), Ctx(C) {} 5990b57cec5SDimitry Andric 6000b57cec5SDimitry Andric void VisitDeclStmt(const DeclStmt *S); 6010b57cec5SDimitry Andric void VisitBinaryOperator(const BinaryOperator *BO); 6020b57cec5SDimitry Andric }; 6030b57cec5SDimitry Andric 6040b57cec5SDimitry Andric } // namespace 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric // Add new local variables to the variable map 6070b57cec5SDimitry Andric void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) { 6080b57cec5SDimitry Andric bool modifiedCtx = false; 6090b57cec5SDimitry Andric const DeclGroupRef DGrp = S->getDeclGroup(); 6100b57cec5SDimitry Andric for (const auto *D : DGrp) { 6110b57cec5SDimitry Andric if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) { 6120b57cec5SDimitry Andric const Expr *E = VD->getInit(); 6130b57cec5SDimitry Andric 6140b57cec5SDimitry Andric // Add local variables with trivial type to the variable map 6150b57cec5SDimitry Andric QualType T = VD->getType(); 6160b57cec5SDimitry Andric if (T.isTrivialType(VD->getASTContext())) { 6170b57cec5SDimitry Andric Ctx = VMap->addDefinition(VD, E, Ctx); 6180b57cec5SDimitry Andric modifiedCtx = true; 6190b57cec5SDimitry Andric } 6200b57cec5SDimitry Andric } 6210b57cec5SDimitry Andric } 6220b57cec5SDimitry Andric if (modifiedCtx) 6230b57cec5SDimitry Andric VMap->saveContext(S, Ctx); 6240b57cec5SDimitry Andric } 6250b57cec5SDimitry Andric 6260b57cec5SDimitry Andric // Update local variable definitions in variable map 6270b57cec5SDimitry Andric void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) { 6280b57cec5SDimitry Andric if (!BO->isAssignmentOp()) 6290b57cec5SDimitry Andric return; 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric Expr *LHSExp = BO->getLHS()->IgnoreParenCasts(); 6320b57cec5SDimitry Andric 6330b57cec5SDimitry Andric // Update the variable map and current context. 6340b57cec5SDimitry Andric if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) { 6350b57cec5SDimitry Andric const ValueDecl *VDec = DRE->getDecl(); 6360b57cec5SDimitry Andric if (Ctx.lookup(VDec)) { 6370b57cec5SDimitry Andric if (BO->getOpcode() == BO_Assign) 6380b57cec5SDimitry Andric Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx); 6390b57cec5SDimitry Andric else 6400b57cec5SDimitry Andric // FIXME -- handle compound assignment operators 6410b57cec5SDimitry Andric Ctx = VMap->clearDefinition(VDec, Ctx); 6420b57cec5SDimitry Andric VMap->saveContext(BO, Ctx); 6430b57cec5SDimitry Andric } 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric } 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric // Computes the intersection of two contexts. The intersection is the 6480b57cec5SDimitry Andric // set of variables which have the same definition in both contexts; 6490b57cec5SDimitry Andric // variables with different definitions are discarded. 6500b57cec5SDimitry Andric LocalVariableMap::Context 6510b57cec5SDimitry Andric LocalVariableMap::intersectContexts(Context C1, Context C2) { 6520b57cec5SDimitry Andric Context Result = C1; 6530b57cec5SDimitry Andric for (const auto &P : C1) { 6540b57cec5SDimitry Andric const NamedDecl *Dec = P.first; 6550b57cec5SDimitry Andric const unsigned *i2 = C2.lookup(Dec); 6560b57cec5SDimitry Andric if (!i2) // variable doesn't exist on second path 6570b57cec5SDimitry Andric Result = removeDefinition(Dec, Result); 6580b57cec5SDimitry Andric else if (*i2 != P.second) // variable exists, but has different definition 6590b57cec5SDimitry Andric Result = clearDefinition(Dec, Result); 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric return Result; 6620b57cec5SDimitry Andric } 6630b57cec5SDimitry Andric 6640b57cec5SDimitry Andric // For every variable in C, create a new variable that refers to the 6650b57cec5SDimitry Andric // definition in C. Return a new context that contains these new variables. 6660b57cec5SDimitry Andric // (We use this for a naive implementation of SSA on loop back-edges.) 6670b57cec5SDimitry Andric LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) { 6680b57cec5SDimitry Andric Context Result = getEmptyContext(); 6690b57cec5SDimitry Andric for (const auto &P : C) 6700b57cec5SDimitry Andric Result = addReference(P.first, P.second, Result); 6710b57cec5SDimitry Andric return Result; 6720b57cec5SDimitry Andric } 6730b57cec5SDimitry Andric 6740b57cec5SDimitry Andric // This routine also takes the intersection of C1 and C2, but it does so by 6750b57cec5SDimitry Andric // altering the VarDefinitions. C1 must be the result of an earlier call to 6760b57cec5SDimitry Andric // createReferenceContext. 6770b57cec5SDimitry Andric void LocalVariableMap::intersectBackEdge(Context C1, Context C2) { 6780b57cec5SDimitry Andric for (const auto &P : C1) { 6790b57cec5SDimitry Andric unsigned i1 = P.second; 6800b57cec5SDimitry Andric VarDefinition *VDef = &VarDefinitions[i1]; 6810b57cec5SDimitry Andric assert(VDef->isReference()); 6820b57cec5SDimitry Andric 6830b57cec5SDimitry Andric const unsigned *i2 = C2.lookup(P.first); 6840b57cec5SDimitry Andric if (!i2 || (*i2 != i1)) 6850b57cec5SDimitry Andric VDef->Ref = 0; // Mark this variable as undefined 6860b57cec5SDimitry Andric } 6870b57cec5SDimitry Andric } 6880b57cec5SDimitry Andric 6890b57cec5SDimitry Andric // Traverse the CFG in topological order, so all predecessors of a block 6900b57cec5SDimitry Andric // (excluding back-edges) are visited before the block itself. At 6910b57cec5SDimitry Andric // each point in the code, we calculate a Context, which holds the set of 6920b57cec5SDimitry Andric // variable definitions which are visible at that point in execution. 6930b57cec5SDimitry Andric // Visible variables are mapped to their definitions using an array that 6940b57cec5SDimitry Andric // contains all definitions. 6950b57cec5SDimitry Andric // 6960b57cec5SDimitry Andric // At join points in the CFG, the set is computed as the intersection of 6970b57cec5SDimitry Andric // the incoming sets along each edge, E.g. 6980b57cec5SDimitry Andric // 6990b57cec5SDimitry Andric // { Context | VarDefinitions } 7000b57cec5SDimitry Andric // int x = 0; { x -> x1 | x1 = 0 } 7010b57cec5SDimitry Andric // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 7020b57cec5SDimitry Andric // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... } 7030b57cec5SDimitry Andric // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... } 7040b57cec5SDimitry Andric // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... } 7050b57cec5SDimitry Andric // 7060b57cec5SDimitry Andric // This is essentially a simpler and more naive version of the standard SSA 7070b57cec5SDimitry Andric // algorithm. Those definitions that remain in the intersection are from blocks 7080b57cec5SDimitry Andric // that strictly dominate the current block. We do not bother to insert proper 7090b57cec5SDimitry Andric // phi nodes, because they are not used in our analysis; instead, wherever 7100b57cec5SDimitry Andric // a phi node would be required, we simply remove that definition from the 7110b57cec5SDimitry Andric // context (E.g. x above). 7120b57cec5SDimitry Andric // 7130b57cec5SDimitry Andric // The initial traversal does not capture back-edges, so those need to be 7140b57cec5SDimitry Andric // handled on a separate pass. Whenever the first pass encounters an 7150b57cec5SDimitry Andric // incoming back edge, it duplicates the context, creating new definitions 7160b57cec5SDimitry Andric // that refer back to the originals. (These correspond to places where SSA 7170b57cec5SDimitry Andric // might have to insert a phi node.) On the second pass, these definitions are 7180b57cec5SDimitry Andric // set to NULL if the variable has changed on the back-edge (i.e. a phi 7190b57cec5SDimitry Andric // node was actually required.) E.g. 7200b57cec5SDimitry Andric // 7210b57cec5SDimitry Andric // { Context | VarDefinitions } 7220b57cec5SDimitry Andric // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 } 7230b57cec5SDimitry Andric // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; } 7240b57cec5SDimitry Andric // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... } 7250b57cec5SDimitry Andric // ... { y -> y1 | x3 = 2, x2 = 1, ... } 7260b57cec5SDimitry Andric void LocalVariableMap::traverseCFG(CFG *CFGraph, 7270b57cec5SDimitry Andric const PostOrderCFGView *SortedGraph, 7280b57cec5SDimitry Andric std::vector<CFGBlockInfo> &BlockInfo) { 7290b57cec5SDimitry Andric PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 7300b57cec5SDimitry Andric 7310b57cec5SDimitry Andric for (const auto *CurrBlock : *SortedGraph) { 7320b57cec5SDimitry Andric unsigned CurrBlockID = CurrBlock->getBlockID(); 7330b57cec5SDimitry Andric CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 7340b57cec5SDimitry Andric 7350b57cec5SDimitry Andric VisitedBlocks.insert(CurrBlock); 7360b57cec5SDimitry Andric 7370b57cec5SDimitry Andric // Calculate the entry context for the current block 7380b57cec5SDimitry Andric bool HasBackEdges = false; 7390b57cec5SDimitry Andric bool CtxInit = true; 7400b57cec5SDimitry Andric for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 7410b57cec5SDimitry Andric PE = CurrBlock->pred_end(); PI != PE; ++PI) { 7420b57cec5SDimitry Andric // if *PI -> CurrBlock is a back edge, so skip it 7430b57cec5SDimitry Andric if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) { 7440b57cec5SDimitry Andric HasBackEdges = true; 7450b57cec5SDimitry Andric continue; 7460b57cec5SDimitry Andric } 7470b57cec5SDimitry Andric 7480b57cec5SDimitry Andric unsigned PrevBlockID = (*PI)->getBlockID(); 7490b57cec5SDimitry Andric CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 7500b57cec5SDimitry Andric 7510b57cec5SDimitry Andric if (CtxInit) { 7520b57cec5SDimitry Andric CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext; 7530b57cec5SDimitry Andric CtxInit = false; 7540b57cec5SDimitry Andric } 7550b57cec5SDimitry Andric else { 7560b57cec5SDimitry Andric CurrBlockInfo->EntryContext = 7570b57cec5SDimitry Andric intersectContexts(CurrBlockInfo->EntryContext, 7580b57cec5SDimitry Andric PrevBlockInfo->ExitContext); 7590b57cec5SDimitry Andric } 7600b57cec5SDimitry Andric } 7610b57cec5SDimitry Andric 7620b57cec5SDimitry Andric // Duplicate the context if we have back-edges, so we can call 7630b57cec5SDimitry Andric // intersectBackEdges later. 7640b57cec5SDimitry Andric if (HasBackEdges) 7650b57cec5SDimitry Andric CurrBlockInfo->EntryContext = 7660b57cec5SDimitry Andric createReferenceContext(CurrBlockInfo->EntryContext); 7670b57cec5SDimitry Andric 7680b57cec5SDimitry Andric // Create a starting context index for the current block 7690b57cec5SDimitry Andric saveContext(nullptr, CurrBlockInfo->EntryContext); 7700b57cec5SDimitry Andric CurrBlockInfo->EntryIndex = getContextIndex(); 7710b57cec5SDimitry Andric 7720b57cec5SDimitry Andric // Visit all the statements in the basic block. 7730b57cec5SDimitry Andric VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext); 7740b57cec5SDimitry Andric for (const auto &BI : *CurrBlock) { 7750b57cec5SDimitry Andric switch (BI.getKind()) { 7760b57cec5SDimitry Andric case CFGElement::Statement: { 7770b57cec5SDimitry Andric CFGStmt CS = BI.castAs<CFGStmt>(); 7780b57cec5SDimitry Andric VMapBuilder.Visit(CS.getStmt()); 7790b57cec5SDimitry Andric break; 7800b57cec5SDimitry Andric } 7810b57cec5SDimitry Andric default: 7820b57cec5SDimitry Andric break; 7830b57cec5SDimitry Andric } 7840b57cec5SDimitry Andric } 7850b57cec5SDimitry Andric CurrBlockInfo->ExitContext = VMapBuilder.Ctx; 7860b57cec5SDimitry Andric 7870b57cec5SDimitry Andric // Mark variables on back edges as "unknown" if they've been changed. 7880b57cec5SDimitry Andric for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 7890b57cec5SDimitry Andric SE = CurrBlock->succ_end(); SI != SE; ++SI) { 7900b57cec5SDimitry Andric // if CurrBlock -> *SI is *not* a back edge 7910b57cec5SDimitry Andric if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI)) 7920b57cec5SDimitry Andric continue; 7930b57cec5SDimitry Andric 7940b57cec5SDimitry Andric CFGBlock *FirstLoopBlock = *SI; 7950b57cec5SDimitry Andric Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext; 7960b57cec5SDimitry Andric Context LoopEnd = CurrBlockInfo->ExitContext; 7970b57cec5SDimitry Andric intersectBackEdge(LoopBegin, LoopEnd); 7980b57cec5SDimitry Andric } 7990b57cec5SDimitry Andric } 8000b57cec5SDimitry Andric 8010b57cec5SDimitry Andric // Put an extra entry at the end of the indexed context array 8020b57cec5SDimitry Andric unsigned exitID = CFGraph->getExit().getBlockID(); 8030b57cec5SDimitry Andric saveContext(nullptr, BlockInfo[exitID].ExitContext); 8040b57cec5SDimitry Andric } 8050b57cec5SDimitry Andric 8060b57cec5SDimitry Andric /// Find the appropriate source locations to use when producing diagnostics for 8070b57cec5SDimitry Andric /// each block in the CFG. 8080b57cec5SDimitry Andric static void findBlockLocations(CFG *CFGraph, 8090b57cec5SDimitry Andric const PostOrderCFGView *SortedGraph, 8100b57cec5SDimitry Andric std::vector<CFGBlockInfo> &BlockInfo) { 8110b57cec5SDimitry Andric for (const auto *CurrBlock : *SortedGraph) { 8120b57cec5SDimitry Andric CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()]; 8130b57cec5SDimitry Andric 8140b57cec5SDimitry Andric // Find the source location of the last statement in the block, if the 8150b57cec5SDimitry Andric // block is not empty. 8160b57cec5SDimitry Andric if (const Stmt *S = CurrBlock->getTerminatorStmt()) { 8170b57cec5SDimitry Andric CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc(); 8180b57cec5SDimitry Andric } else { 8190b57cec5SDimitry Andric for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(), 8200b57cec5SDimitry Andric BE = CurrBlock->rend(); BI != BE; ++BI) { 8210b57cec5SDimitry Andric // FIXME: Handle other CFGElement kinds. 822bdd1243dSDimitry Andric if (std::optional<CFGStmt> CS = BI->getAs<CFGStmt>()) { 8230b57cec5SDimitry Andric CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc(); 8240b57cec5SDimitry Andric break; 8250b57cec5SDimitry Andric } 8260b57cec5SDimitry Andric } 8270b57cec5SDimitry Andric } 8280b57cec5SDimitry Andric 8290b57cec5SDimitry Andric if (CurrBlockInfo->ExitLoc.isValid()) { 8300b57cec5SDimitry Andric // This block contains at least one statement. Find the source location 8310b57cec5SDimitry Andric // of the first statement in the block. 8320b57cec5SDimitry Andric for (const auto &BI : *CurrBlock) { 8330b57cec5SDimitry Andric // FIXME: Handle other CFGElement kinds. 834bdd1243dSDimitry Andric if (std::optional<CFGStmt> CS = BI.getAs<CFGStmt>()) { 8350b57cec5SDimitry Andric CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc(); 8360b57cec5SDimitry Andric break; 8370b57cec5SDimitry Andric } 8380b57cec5SDimitry Andric } 8390b57cec5SDimitry Andric } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() && 8400b57cec5SDimitry Andric CurrBlock != &CFGraph->getExit()) { 8410b57cec5SDimitry Andric // The block is empty, and has a single predecessor. Use its exit 8420b57cec5SDimitry Andric // location. 8430b57cec5SDimitry Andric CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = 8440b57cec5SDimitry Andric BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc; 845349cc55cSDimitry Andric } else if (CurrBlock->succ_size() == 1 && *CurrBlock->succ_begin()) { 846349cc55cSDimitry Andric // The block is empty, and has a single successor. Use its entry 847349cc55cSDimitry Andric // location. 848349cc55cSDimitry Andric CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = 849349cc55cSDimitry Andric BlockInfo[(*CurrBlock->succ_begin())->getBlockID()].EntryLoc; 8500b57cec5SDimitry Andric } 8510b57cec5SDimitry Andric } 8520b57cec5SDimitry Andric } 8530b57cec5SDimitry Andric 8540b57cec5SDimitry Andric namespace { 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric class LockableFactEntry : public FactEntry { 8570b57cec5SDimitry Andric public: 8580b57cec5SDimitry Andric LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc, 859fe6060f1SDimitry Andric SourceKind Src = Acquired) 860fe6060f1SDimitry Andric : FactEntry(CE, LK, Loc, Src) {} 8610b57cec5SDimitry Andric 8620b57cec5SDimitry Andric void 8630b57cec5SDimitry Andric handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 8640b57cec5SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK, 8650b57cec5SDimitry Andric ThreadSafetyHandler &Handler) const override { 866fe6060f1SDimitry Andric if (!asserted() && !negative() && !isUniversal()) { 86781ad6265SDimitry Andric Handler.handleMutexHeldEndOfScope(getKind(), toString(), loc(), JoinLoc, 8680b57cec5SDimitry Andric LEK); 8690b57cec5SDimitry Andric } 8700b57cec5SDimitry Andric } 8710b57cec5SDimitry Andric 8720b57cec5SDimitry Andric void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry, 87381ad6265SDimitry Andric ThreadSafetyHandler &Handler) const override { 87481ad6265SDimitry Andric Handler.handleDoubleLock(entry.getKind(), entry.toString(), loc(), 87581ad6265SDimitry Andric entry.loc()); 8760b57cec5SDimitry Andric } 8770b57cec5SDimitry Andric 8780b57cec5SDimitry Andric void handleUnlock(FactSet &FSet, FactManager &FactMan, 8790b57cec5SDimitry Andric const CapabilityExpr &Cp, SourceLocation UnlockLoc, 88081ad6265SDimitry Andric bool FullyRemove, 88181ad6265SDimitry Andric ThreadSafetyHandler &Handler) const override { 8820b57cec5SDimitry Andric FSet.removeLock(FactMan, Cp); 8830b57cec5SDimitry Andric if (!Cp.negative()) { 884a7dea167SDimitry Andric FSet.addLock(FactMan, std::make_unique<LockableFactEntry>( 8850b57cec5SDimitry Andric !Cp, LK_Exclusive, UnlockLoc)); 8860b57cec5SDimitry Andric } 8870b57cec5SDimitry Andric } 8880b57cec5SDimitry Andric }; 8890b57cec5SDimitry Andric 8900b57cec5SDimitry Andric class ScopedLockableFactEntry : public FactEntry { 8910b57cec5SDimitry Andric private: 8920b57cec5SDimitry Andric enum UnderlyingCapabilityKind { 8930b57cec5SDimitry Andric UCK_Acquired, ///< Any kind of acquired capability. 8940b57cec5SDimitry Andric UCK_ReleasedShared, ///< Shared capability that was released. 8950b57cec5SDimitry Andric UCK_ReleasedExclusive, ///< Exclusive capability that was released. 8960b57cec5SDimitry Andric }; 8970b57cec5SDimitry Andric 89881ad6265SDimitry Andric struct UnderlyingCapability { 89981ad6265SDimitry Andric CapabilityExpr Cap; 90081ad6265SDimitry Andric UnderlyingCapabilityKind Kind; 90181ad6265SDimitry Andric }; 9020b57cec5SDimitry Andric 90381ad6265SDimitry Andric SmallVector<UnderlyingCapability, 2> UnderlyingMutexes; 9040b57cec5SDimitry Andric 9050b57cec5SDimitry Andric public: 9060b57cec5SDimitry Andric ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc) 907fe6060f1SDimitry Andric : FactEntry(CE, LK_Exclusive, Loc, Acquired) {} 9080b57cec5SDimitry Andric 9095ffd83dbSDimitry Andric void addLock(const CapabilityExpr &M) { 91081ad6265SDimitry Andric UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_Acquired}); 9110b57cec5SDimitry Andric } 9120b57cec5SDimitry Andric 9130b57cec5SDimitry Andric void addExclusiveUnlock(const CapabilityExpr &M) { 91481ad6265SDimitry Andric UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedExclusive}); 9150b57cec5SDimitry Andric } 9160b57cec5SDimitry Andric 9170b57cec5SDimitry Andric void addSharedUnlock(const CapabilityExpr &M) { 91881ad6265SDimitry Andric UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedShared}); 9190b57cec5SDimitry Andric } 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric void 9220b57cec5SDimitry Andric handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan, 9230b57cec5SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK, 9240b57cec5SDimitry Andric ThreadSafetyHandler &Handler) const override { 9250b57cec5SDimitry Andric for (const auto &UnderlyingMutex : UnderlyingMutexes) { 92681ad6265SDimitry Andric const auto *Entry = FSet.findLock(FactMan, UnderlyingMutex.Cap); 92781ad6265SDimitry Andric if ((UnderlyingMutex.Kind == UCK_Acquired && Entry) || 92881ad6265SDimitry Andric (UnderlyingMutex.Kind != UCK_Acquired && !Entry)) { 9290b57cec5SDimitry Andric // If this scoped lock manages another mutex, and if the underlying 9300b57cec5SDimitry Andric // mutex is still/not held, then warn about the underlying mutex. 93181ad6265SDimitry Andric Handler.handleMutexHeldEndOfScope(UnderlyingMutex.Cap.getKind(), 93281ad6265SDimitry Andric UnderlyingMutex.Cap.toString(), loc(), 93381ad6265SDimitry Andric JoinLoc, LEK); 9340b57cec5SDimitry Andric } 9350b57cec5SDimitry Andric } 9360b57cec5SDimitry Andric } 9370b57cec5SDimitry Andric 9380b57cec5SDimitry Andric void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry, 93981ad6265SDimitry Andric ThreadSafetyHandler &Handler) const override { 9400b57cec5SDimitry Andric for (const auto &UnderlyingMutex : UnderlyingMutexes) { 94181ad6265SDimitry Andric if (UnderlyingMutex.Kind == UCK_Acquired) 94281ad6265SDimitry Andric lock(FSet, FactMan, UnderlyingMutex.Cap, entry.kind(), entry.loc(), 94381ad6265SDimitry Andric &Handler); 9440b57cec5SDimitry Andric else 94581ad6265SDimitry Andric unlock(FSet, FactMan, UnderlyingMutex.Cap, entry.loc(), &Handler); 9460b57cec5SDimitry Andric } 9470b57cec5SDimitry Andric } 9480b57cec5SDimitry Andric 9490b57cec5SDimitry Andric void handleUnlock(FactSet &FSet, FactManager &FactMan, 9500b57cec5SDimitry Andric const CapabilityExpr &Cp, SourceLocation UnlockLoc, 95181ad6265SDimitry Andric bool FullyRemove, 95281ad6265SDimitry Andric ThreadSafetyHandler &Handler) const override { 9530b57cec5SDimitry Andric assert(!Cp.negative() && "Managing object cannot be negative."); 9540b57cec5SDimitry Andric for (const auto &UnderlyingMutex : UnderlyingMutexes) { 9550b57cec5SDimitry Andric // Remove/lock the underlying mutex if it exists/is still unlocked; warn 9560b57cec5SDimitry Andric // on double unlocking/locking if we're not destroying the scoped object. 9570b57cec5SDimitry Andric ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler; 95881ad6265SDimitry Andric if (UnderlyingMutex.Kind == UCK_Acquired) { 95981ad6265SDimitry Andric unlock(FSet, FactMan, UnderlyingMutex.Cap, UnlockLoc, TSHandler); 9600b57cec5SDimitry Andric } else { 96181ad6265SDimitry Andric LockKind kind = UnderlyingMutex.Kind == UCK_ReleasedShared 9620b57cec5SDimitry Andric ? LK_Shared 9630b57cec5SDimitry Andric : LK_Exclusive; 96481ad6265SDimitry Andric lock(FSet, FactMan, UnderlyingMutex.Cap, kind, UnlockLoc, TSHandler); 9650b57cec5SDimitry Andric } 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric if (FullyRemove) 9680b57cec5SDimitry Andric FSet.removeLock(FactMan, Cp); 9690b57cec5SDimitry Andric } 9700b57cec5SDimitry Andric 9710b57cec5SDimitry Andric private: 9720b57cec5SDimitry Andric void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp, 97381ad6265SDimitry Andric LockKind kind, SourceLocation loc, 97481ad6265SDimitry Andric ThreadSafetyHandler *Handler) const { 9750b57cec5SDimitry Andric if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) { 9760b57cec5SDimitry Andric if (Handler) 97781ad6265SDimitry Andric Handler->handleDoubleLock(Cp.getKind(), Cp.toString(), Fact->loc(), 97881ad6265SDimitry Andric loc); 9790b57cec5SDimitry Andric } else { 9800b57cec5SDimitry Andric FSet.removeLock(FactMan, !Cp); 9810b57cec5SDimitry Andric FSet.addLock(FactMan, 982fe6060f1SDimitry Andric std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed)); 9830b57cec5SDimitry Andric } 9840b57cec5SDimitry Andric } 9850b57cec5SDimitry Andric 9860b57cec5SDimitry Andric void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp, 98781ad6265SDimitry Andric SourceLocation loc, ThreadSafetyHandler *Handler) const { 9880b57cec5SDimitry Andric if (FSet.findLock(FactMan, Cp)) { 9890b57cec5SDimitry Andric FSet.removeLock(FactMan, Cp); 990a7dea167SDimitry Andric FSet.addLock(FactMan, std::make_unique<LockableFactEntry>( 9910b57cec5SDimitry Andric !Cp, LK_Exclusive, loc)); 9920b57cec5SDimitry Andric } else if (Handler) { 9935ffd83dbSDimitry Andric SourceLocation PrevLoc; 9945ffd83dbSDimitry Andric if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp)) 9955ffd83dbSDimitry Andric PrevLoc = Neg->loc(); 99681ad6265SDimitry Andric Handler->handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), loc, PrevLoc); 9970b57cec5SDimitry Andric } 9980b57cec5SDimitry Andric } 9990b57cec5SDimitry Andric }; 10000b57cec5SDimitry Andric 10010b57cec5SDimitry Andric /// Class which implements the core thread safety analysis routines. 10020b57cec5SDimitry Andric class ThreadSafetyAnalyzer { 10030b57cec5SDimitry Andric friend class BuildLockset; 10040b57cec5SDimitry Andric friend class threadSafety::BeforeSet; 10050b57cec5SDimitry Andric 10060b57cec5SDimitry Andric llvm::BumpPtrAllocator Bpa; 10070b57cec5SDimitry Andric threadSafety::til::MemRegionRef Arena; 10080b57cec5SDimitry Andric threadSafety::SExprBuilder SxBuilder; 10090b57cec5SDimitry Andric 10100b57cec5SDimitry Andric ThreadSafetyHandler &Handler; 1011*5f757f3fSDimitry Andric const FunctionDecl *CurrentFunction; 10120b57cec5SDimitry Andric LocalVariableMap LocalVarMap; 1013*5f757f3fSDimitry Andric // Maps constructed objects to `this` placeholder prior to initialization. 1014*5f757f3fSDimitry Andric llvm::SmallDenseMap<const Expr *, til::LiteralPtr *> ConstructedObjects; 10150b57cec5SDimitry Andric FactManager FactMan; 10160b57cec5SDimitry Andric std::vector<CFGBlockInfo> BlockInfo; 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric BeforeSet *GlobalBeforeSet; 10190b57cec5SDimitry Andric 10200b57cec5SDimitry Andric public: 10210b57cec5SDimitry Andric ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset) 10220b57cec5SDimitry Andric : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {} 10230b57cec5SDimitry Andric 10240b57cec5SDimitry Andric bool inCurrentScope(const CapabilityExpr &CapE); 10250b57cec5SDimitry Andric 10260b57cec5SDimitry Andric void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry, 102781ad6265SDimitry Andric bool ReqAttr = false); 10280b57cec5SDimitry Andric void removeLock(FactSet &FSet, const CapabilityExpr &CapE, 102981ad6265SDimitry Andric SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind); 10300b57cec5SDimitry Andric 10310b57cec5SDimitry Andric template <typename AttrType> 10320b57cec5SDimitry Andric void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp, 1033bdd1243dSDimitry Andric const NamedDecl *D, til::SExpr *Self = nullptr); 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric template <class AttrType> 10360b57cec5SDimitry Andric void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp, 10370b57cec5SDimitry Andric const NamedDecl *D, 10380b57cec5SDimitry Andric const CFGBlock *PredBlock, const CFGBlock *CurrBlock, 10390b57cec5SDimitry Andric Expr *BrE, bool Neg); 10400b57cec5SDimitry Andric 10410b57cec5SDimitry Andric const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C, 10420b57cec5SDimitry Andric bool &Negate); 10430b57cec5SDimitry Andric 10440b57cec5SDimitry Andric void getEdgeLockset(FactSet &Result, const FactSet &ExitSet, 10450b57cec5SDimitry Andric const CFGBlock* PredBlock, 10460b57cec5SDimitry Andric const CFGBlock *CurrBlock); 10470b57cec5SDimitry Andric 104828a41182SDimitry Andric bool join(const FactEntry &a, const FactEntry &b, bool CanModify); 10490b57cec5SDimitry Andric 1050fe6060f1SDimitry Andric void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet, 1051fe6060f1SDimitry Andric SourceLocation JoinLoc, LockErrorKind EntryLEK, 1052fe6060f1SDimitry Andric LockErrorKind ExitLEK); 1053fe6060f1SDimitry Andric 1054fe6060f1SDimitry Andric void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet, 1055fe6060f1SDimitry Andric SourceLocation JoinLoc, LockErrorKind LEK) { 1056fe6060f1SDimitry Andric intersectAndWarn(EntrySet, ExitSet, JoinLoc, LEK, LEK); 10570b57cec5SDimitry Andric } 10580b57cec5SDimitry Andric 10590b57cec5SDimitry Andric void runAnalysis(AnalysisDeclContext &AC); 1060*5f757f3fSDimitry Andric 1061*5f757f3fSDimitry Andric void warnIfMutexNotHeld(const FactSet &FSet, const NamedDecl *D, 1062*5f757f3fSDimitry Andric const Expr *Exp, AccessKind AK, Expr *MutexExp, 1063*5f757f3fSDimitry Andric ProtectedOperationKind POK, til::LiteralPtr *Self, 1064*5f757f3fSDimitry Andric SourceLocation Loc); 1065*5f757f3fSDimitry Andric void warnIfMutexHeld(const FactSet &FSet, const NamedDecl *D, const Expr *Exp, 1066*5f757f3fSDimitry Andric Expr *MutexExp, til::LiteralPtr *Self, 1067*5f757f3fSDimitry Andric SourceLocation Loc); 1068*5f757f3fSDimitry Andric 1069*5f757f3fSDimitry Andric void checkAccess(const FactSet &FSet, const Expr *Exp, AccessKind AK, 1070*5f757f3fSDimitry Andric ProtectedOperationKind POK); 1071*5f757f3fSDimitry Andric void checkPtAccess(const FactSet &FSet, const Expr *Exp, AccessKind AK, 1072*5f757f3fSDimitry Andric ProtectedOperationKind POK); 10730b57cec5SDimitry Andric }; 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric } // namespace 10760b57cec5SDimitry Andric 10770b57cec5SDimitry Andric /// Process acquired_before and acquired_after attributes on Vd. 10780b57cec5SDimitry Andric BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd, 10790b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer) { 10800b57cec5SDimitry Andric // Create a new entry for Vd. 10810b57cec5SDimitry Andric BeforeInfo *Info = nullptr; 10820b57cec5SDimitry Andric { 10830b57cec5SDimitry Andric // Keep InfoPtr in its own scope in case BMap is modified later and the 10840b57cec5SDimitry Andric // reference becomes invalid. 10850b57cec5SDimitry Andric std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd]; 10860b57cec5SDimitry Andric if (!InfoPtr) 10870b57cec5SDimitry Andric InfoPtr.reset(new BeforeInfo()); 10880b57cec5SDimitry Andric Info = InfoPtr.get(); 10890b57cec5SDimitry Andric } 10900b57cec5SDimitry Andric 10910b57cec5SDimitry Andric for (const auto *At : Vd->attrs()) { 10920b57cec5SDimitry Andric switch (At->getKind()) { 10930b57cec5SDimitry Andric case attr::AcquiredBefore: { 10940b57cec5SDimitry Andric const auto *A = cast<AcquiredBeforeAttr>(At); 10950b57cec5SDimitry Andric 10960b57cec5SDimitry Andric // Read exprs from the attribute, and add them to BeforeVect. 10970b57cec5SDimitry Andric for (const auto *Arg : A->args()) { 10980b57cec5SDimitry Andric CapabilityExpr Cp = 10990b57cec5SDimitry Andric Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr); 11000b57cec5SDimitry Andric if (const ValueDecl *Cpvd = Cp.valueDecl()) { 11010b57cec5SDimitry Andric Info->Vect.push_back(Cpvd); 11020b57cec5SDimitry Andric const auto It = BMap.find(Cpvd); 11030b57cec5SDimitry Andric if (It == BMap.end()) 11040b57cec5SDimitry Andric insertAttrExprs(Cpvd, Analyzer); 11050b57cec5SDimitry Andric } 11060b57cec5SDimitry Andric } 11070b57cec5SDimitry Andric break; 11080b57cec5SDimitry Andric } 11090b57cec5SDimitry Andric case attr::AcquiredAfter: { 11100b57cec5SDimitry Andric const auto *A = cast<AcquiredAfterAttr>(At); 11110b57cec5SDimitry Andric 11120b57cec5SDimitry Andric // Read exprs from the attribute, and add them to BeforeVect. 11130b57cec5SDimitry Andric for (const auto *Arg : A->args()) { 11140b57cec5SDimitry Andric CapabilityExpr Cp = 11150b57cec5SDimitry Andric Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr); 11160b57cec5SDimitry Andric if (const ValueDecl *ArgVd = Cp.valueDecl()) { 11170b57cec5SDimitry Andric // Get entry for mutex listed in attribute 11180b57cec5SDimitry Andric BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer); 11190b57cec5SDimitry Andric ArgInfo->Vect.push_back(Vd); 11200b57cec5SDimitry Andric } 11210b57cec5SDimitry Andric } 11220b57cec5SDimitry Andric break; 11230b57cec5SDimitry Andric } 11240b57cec5SDimitry Andric default: 11250b57cec5SDimitry Andric break; 11260b57cec5SDimitry Andric } 11270b57cec5SDimitry Andric } 11280b57cec5SDimitry Andric 11290b57cec5SDimitry Andric return Info; 11300b57cec5SDimitry Andric } 11310b57cec5SDimitry Andric 11320b57cec5SDimitry Andric BeforeSet::BeforeInfo * 11330b57cec5SDimitry Andric BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd, 11340b57cec5SDimitry Andric ThreadSafetyAnalyzer &Analyzer) { 11350b57cec5SDimitry Andric auto It = BMap.find(Vd); 11360b57cec5SDimitry Andric BeforeInfo *Info = nullptr; 11370b57cec5SDimitry Andric if (It == BMap.end()) 11380b57cec5SDimitry Andric Info = insertAttrExprs(Vd, Analyzer); 11390b57cec5SDimitry Andric else 11400b57cec5SDimitry Andric Info = It->second.get(); 11410b57cec5SDimitry Andric assert(Info && "BMap contained nullptr?"); 11420b57cec5SDimitry Andric return Info; 11430b57cec5SDimitry Andric } 11440b57cec5SDimitry Andric 11450b57cec5SDimitry Andric /// Return true if any mutexes in FSet are in the acquired_before set of Vd. 11460b57cec5SDimitry Andric void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd, 11470b57cec5SDimitry Andric const FactSet& FSet, 11480b57cec5SDimitry Andric ThreadSafetyAnalyzer& Analyzer, 11490b57cec5SDimitry Andric SourceLocation Loc, StringRef CapKind) { 11500b57cec5SDimitry Andric SmallVector<BeforeInfo*, 8> InfoVect; 11510b57cec5SDimitry Andric 11520b57cec5SDimitry Andric // Do a depth-first traversal of Vd. 11530b57cec5SDimitry Andric // Return true if there are cycles. 11540b57cec5SDimitry Andric std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) { 11550b57cec5SDimitry Andric if (!Vd) 11560b57cec5SDimitry Andric return false; 11570b57cec5SDimitry Andric 11580b57cec5SDimitry Andric BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer); 11590b57cec5SDimitry Andric 11600b57cec5SDimitry Andric if (Info->Visited == 1) 11610b57cec5SDimitry Andric return true; 11620b57cec5SDimitry Andric 11630b57cec5SDimitry Andric if (Info->Visited == 2) 11640b57cec5SDimitry Andric return false; 11650b57cec5SDimitry Andric 11660b57cec5SDimitry Andric if (Info->Vect.empty()) 11670b57cec5SDimitry Andric return false; 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric InfoVect.push_back(Info); 11700b57cec5SDimitry Andric Info->Visited = 1; 11710b57cec5SDimitry Andric for (const auto *Vdb : Info->Vect) { 11720b57cec5SDimitry Andric // Exclude mutexes in our immediate before set. 11730b57cec5SDimitry Andric if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) { 11740b57cec5SDimitry Andric StringRef L1 = StartVd->getName(); 11750b57cec5SDimitry Andric StringRef L2 = Vdb->getName(); 11760b57cec5SDimitry Andric Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc); 11770b57cec5SDimitry Andric } 11780b57cec5SDimitry Andric // Transitively search other before sets, and warn on cycles. 11790b57cec5SDimitry Andric if (traverse(Vdb)) { 118006c3fb27SDimitry Andric if (!CycMap.contains(Vd)) { 11810b57cec5SDimitry Andric CycMap.insert(std::make_pair(Vd, true)); 11820b57cec5SDimitry Andric StringRef L1 = Vd->getName(); 11830b57cec5SDimitry Andric Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation()); 11840b57cec5SDimitry Andric } 11850b57cec5SDimitry Andric } 11860b57cec5SDimitry Andric } 11870b57cec5SDimitry Andric Info->Visited = 2; 11880b57cec5SDimitry Andric return false; 11890b57cec5SDimitry Andric }; 11900b57cec5SDimitry Andric 11910b57cec5SDimitry Andric traverse(StartVd); 11920b57cec5SDimitry Andric 11930b57cec5SDimitry Andric for (auto *Info : InfoVect) 11940b57cec5SDimitry Andric Info->Visited = 0; 11950b57cec5SDimitry Andric } 11960b57cec5SDimitry Andric 11970b57cec5SDimitry Andric /// Gets the value decl pointer from DeclRefExprs or MemberExprs. 11980b57cec5SDimitry Andric static const ValueDecl *getValueDecl(const Expr *Exp) { 11990b57cec5SDimitry Andric if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp)) 12000b57cec5SDimitry Andric return getValueDecl(CE->getSubExpr()); 12010b57cec5SDimitry Andric 12020b57cec5SDimitry Andric if (const auto *DR = dyn_cast<DeclRefExpr>(Exp)) 12030b57cec5SDimitry Andric return DR->getDecl(); 12040b57cec5SDimitry Andric 12050b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(Exp)) 12060b57cec5SDimitry Andric return ME->getMemberDecl(); 12070b57cec5SDimitry Andric 12080b57cec5SDimitry Andric return nullptr; 12090b57cec5SDimitry Andric } 12100b57cec5SDimitry Andric 12110b57cec5SDimitry Andric namespace { 12120b57cec5SDimitry Andric 12130b57cec5SDimitry Andric template <typename Ty> 12140b57cec5SDimitry Andric class has_arg_iterator_range { 12150b57cec5SDimitry Andric using yes = char[1]; 12160b57cec5SDimitry Andric using no = char[2]; 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric template <typename Inner> 12190b57cec5SDimitry Andric static yes& test(Inner *I, decltype(I->args()) * = nullptr); 12200b57cec5SDimitry Andric 12210b57cec5SDimitry Andric template <typename> 12220b57cec5SDimitry Andric static no& test(...); 12230b57cec5SDimitry Andric 12240b57cec5SDimitry Andric public: 12250b57cec5SDimitry Andric static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes); 12260b57cec5SDimitry Andric }; 12270b57cec5SDimitry Andric 12280b57cec5SDimitry Andric } // namespace 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) { 1231e8d8bef9SDimitry Andric const threadSafety::til::SExpr *SExp = CapE.sexpr(); 1232e8d8bef9SDimitry Andric assert(SExp && "Null expressions should be ignored"); 1233e8d8bef9SDimitry Andric 1234e8d8bef9SDimitry Andric if (const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) { 1235e8d8bef9SDimitry Andric const ValueDecl *VD = LP->clangDecl(); 1236e8d8bef9SDimitry Andric // Variables defined in a function are always inaccessible. 1237bdd1243dSDimitry Andric if (!VD || !VD->isDefinedOutsideFunctionOrMethod()) 1238e8d8bef9SDimitry Andric return false; 1239e8d8bef9SDimitry Andric // For now we consider static class members to be inaccessible. 1240e8d8bef9SDimitry Andric if (isa<CXXRecordDecl>(VD->getDeclContext())) 1241e8d8bef9SDimitry Andric return false; 1242e8d8bef9SDimitry Andric // Global variables are always in scope. 1243e8d8bef9SDimitry Andric return true; 1244e8d8bef9SDimitry Andric } 1245e8d8bef9SDimitry Andric 1246e8d8bef9SDimitry Andric // Members are in scope from methods of the same class. 1247e8d8bef9SDimitry Andric if (const auto *P = dyn_cast<til::Project>(SExp)) { 1248*5f757f3fSDimitry Andric if (!isa_and_nonnull<CXXMethodDecl>(CurrentFunction)) 12490b57cec5SDimitry Andric return false; 1250e8d8bef9SDimitry Andric const ValueDecl *VD = P->clangDecl(); 1251*5f757f3fSDimitry Andric return VD->getDeclContext() == CurrentFunction->getDeclContext(); 12520b57cec5SDimitry Andric } 1253e8d8bef9SDimitry Andric 12540b57cec5SDimitry Andric return false; 12550b57cec5SDimitry Andric } 12560b57cec5SDimitry Andric 12570b57cec5SDimitry Andric /// Add a new lock to the lockset, warning if the lock is already there. 12580b57cec5SDimitry Andric /// \param ReqAttr -- true if this is part of an initial Requires attribute. 12590b57cec5SDimitry Andric void ThreadSafetyAnalyzer::addLock(FactSet &FSet, 12600b57cec5SDimitry Andric std::unique_ptr<FactEntry> Entry, 126181ad6265SDimitry Andric bool ReqAttr) { 12620b57cec5SDimitry Andric if (Entry->shouldIgnore()) 12630b57cec5SDimitry Andric return; 12640b57cec5SDimitry Andric 12650b57cec5SDimitry Andric if (!ReqAttr && !Entry->negative()) { 12660b57cec5SDimitry Andric // look for the negative capability, and remove it from the fact set. 12670b57cec5SDimitry Andric CapabilityExpr NegC = !*Entry; 12680b57cec5SDimitry Andric const FactEntry *Nen = FSet.findLock(FactMan, NegC); 12690b57cec5SDimitry Andric if (Nen) { 12700b57cec5SDimitry Andric FSet.removeLock(FactMan, NegC); 12710b57cec5SDimitry Andric } 12720b57cec5SDimitry Andric else { 12730b57cec5SDimitry Andric if (inCurrentScope(*Entry) && !Entry->asserted()) 127481ad6265SDimitry Andric Handler.handleNegativeNotHeld(Entry->getKind(), Entry->toString(), 12750b57cec5SDimitry Andric NegC.toString(), Entry->loc()); 12760b57cec5SDimitry Andric } 12770b57cec5SDimitry Andric } 12780b57cec5SDimitry Andric 12790b57cec5SDimitry Andric // Check before/after constraints 12800b57cec5SDimitry Andric if (Handler.issueBetaWarnings() && 12810b57cec5SDimitry Andric !Entry->asserted() && !Entry->declared()) { 12820b57cec5SDimitry Andric GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this, 128381ad6265SDimitry Andric Entry->loc(), Entry->getKind()); 12840b57cec5SDimitry Andric } 12850b57cec5SDimitry Andric 12860b57cec5SDimitry Andric // FIXME: Don't always warn when we have support for reentrant locks. 12870b57cec5SDimitry Andric if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) { 12880b57cec5SDimitry Andric if (!Entry->asserted()) 128981ad6265SDimitry Andric Cp->handleLock(FSet, FactMan, *Entry, Handler); 12900b57cec5SDimitry Andric } else { 12910b57cec5SDimitry Andric FSet.addLock(FactMan, std::move(Entry)); 12920b57cec5SDimitry Andric } 12930b57cec5SDimitry Andric } 12940b57cec5SDimitry Andric 12950b57cec5SDimitry Andric /// Remove a lock from the lockset, warning if the lock is not there. 12960b57cec5SDimitry Andric /// \param UnlockLoc The source location of the unlock (only used in error msg) 12970b57cec5SDimitry Andric void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp, 12980b57cec5SDimitry Andric SourceLocation UnlockLoc, 129981ad6265SDimitry Andric bool FullyRemove, LockKind ReceivedKind) { 13000b57cec5SDimitry Andric if (Cp.shouldIgnore()) 13010b57cec5SDimitry Andric return; 13020b57cec5SDimitry Andric 13030b57cec5SDimitry Andric const FactEntry *LDat = FSet.findLock(FactMan, Cp); 13040b57cec5SDimitry Andric if (!LDat) { 13055ffd83dbSDimitry Andric SourceLocation PrevLoc; 13065ffd83dbSDimitry Andric if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp)) 13075ffd83dbSDimitry Andric PrevLoc = Neg->loc(); 130881ad6265SDimitry Andric Handler.handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), UnlockLoc, 130981ad6265SDimitry Andric PrevLoc); 13100b57cec5SDimitry Andric return; 13110b57cec5SDimitry Andric } 13120b57cec5SDimitry Andric 13130b57cec5SDimitry Andric // Generic lock removal doesn't care about lock kind mismatches, but 13140b57cec5SDimitry Andric // otherwise diagnose when the lock kinds are mismatched. 13150b57cec5SDimitry Andric if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) { 131681ad6265SDimitry Andric Handler.handleIncorrectUnlockKind(Cp.getKind(), Cp.toString(), LDat->kind(), 13170b57cec5SDimitry Andric ReceivedKind, LDat->loc(), UnlockLoc); 13180b57cec5SDimitry Andric } 13190b57cec5SDimitry Andric 132081ad6265SDimitry Andric LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler); 13210b57cec5SDimitry Andric } 13220b57cec5SDimitry Andric 13230b57cec5SDimitry Andric /// Extract the list of mutexIDs from the attribute on an expression, 13240b57cec5SDimitry Andric /// and push them onto Mtxs, discarding any duplicates. 13250b57cec5SDimitry Andric template <typename AttrType> 13260b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, 13270b57cec5SDimitry Andric const Expr *Exp, const NamedDecl *D, 1328bdd1243dSDimitry Andric til::SExpr *Self) { 13290b57cec5SDimitry Andric if (Attr->args_size() == 0) { 13300b57cec5SDimitry Andric // The mutex held is the "this" object. 1331bdd1243dSDimitry Andric CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, Self); 13320b57cec5SDimitry Andric if (Cp.isInvalid()) { 133381ad6265SDimitry Andric warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind()); 13340b57cec5SDimitry Andric return; 13350b57cec5SDimitry Andric } 13360b57cec5SDimitry Andric //else 13370b57cec5SDimitry Andric if (!Cp.shouldIgnore()) 13380b57cec5SDimitry Andric Mtxs.push_back_nodup(Cp); 13390b57cec5SDimitry Andric return; 13400b57cec5SDimitry Andric } 13410b57cec5SDimitry Andric 13420b57cec5SDimitry Andric for (const auto *Arg : Attr->args()) { 1343bdd1243dSDimitry Andric CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, Self); 13440b57cec5SDimitry Andric if (Cp.isInvalid()) { 134581ad6265SDimitry Andric warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind()); 13460b57cec5SDimitry Andric continue; 13470b57cec5SDimitry Andric } 13480b57cec5SDimitry Andric //else 13490b57cec5SDimitry Andric if (!Cp.shouldIgnore()) 13500b57cec5SDimitry Andric Mtxs.push_back_nodup(Cp); 13510b57cec5SDimitry Andric } 13520b57cec5SDimitry Andric } 13530b57cec5SDimitry Andric 13540b57cec5SDimitry Andric /// Extract the list of mutexIDs from a trylock attribute. If the 13550b57cec5SDimitry Andric /// trylock applies to the given edge, then push them onto Mtxs, discarding 13560b57cec5SDimitry Andric /// any duplicates. 13570b57cec5SDimitry Andric template <class AttrType> 13580b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, 13590b57cec5SDimitry Andric const Expr *Exp, const NamedDecl *D, 13600b57cec5SDimitry Andric const CFGBlock *PredBlock, 13610b57cec5SDimitry Andric const CFGBlock *CurrBlock, 13620b57cec5SDimitry Andric Expr *BrE, bool Neg) { 13630b57cec5SDimitry Andric // Find out which branch has the lock 13640b57cec5SDimitry Andric bool branch = false; 13650b57cec5SDimitry Andric if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE)) 13660b57cec5SDimitry Andric branch = BLE->getValue(); 13670b57cec5SDimitry Andric else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE)) 13680b57cec5SDimitry Andric branch = ILE->getValue().getBoolValue(); 13690b57cec5SDimitry Andric 13700b57cec5SDimitry Andric int branchnum = branch ? 0 : 1; 13710b57cec5SDimitry Andric if (Neg) 13720b57cec5SDimitry Andric branchnum = !branchnum; 13730b57cec5SDimitry Andric 13740b57cec5SDimitry Andric // If we've taken the trylock branch, then add the lock 13750b57cec5SDimitry Andric int i = 0; 13760b57cec5SDimitry Andric for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(), 13770b57cec5SDimitry Andric SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) { 13780b57cec5SDimitry Andric if (*SI == CurrBlock && i == branchnum) 13790b57cec5SDimitry Andric getMutexIDs(Mtxs, Attr, Exp, D); 13800b57cec5SDimitry Andric } 13810b57cec5SDimitry Andric } 13820b57cec5SDimitry Andric 13830b57cec5SDimitry Andric static bool getStaticBooleanValue(Expr *E, bool &TCond) { 13840b57cec5SDimitry Andric if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) { 13850b57cec5SDimitry Andric TCond = false; 13860b57cec5SDimitry Andric return true; 13870b57cec5SDimitry Andric } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) { 13880b57cec5SDimitry Andric TCond = BLE->getValue(); 13890b57cec5SDimitry Andric return true; 13900b57cec5SDimitry Andric } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) { 13910b57cec5SDimitry Andric TCond = ILE->getValue().getBoolValue(); 13920b57cec5SDimitry Andric return true; 13930b57cec5SDimitry Andric } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E)) 13940b57cec5SDimitry Andric return getStaticBooleanValue(CE->getSubExpr(), TCond); 13950b57cec5SDimitry Andric return false; 13960b57cec5SDimitry Andric } 13970b57cec5SDimitry Andric 13980b57cec5SDimitry Andric // If Cond can be traced back to a function call, return the call expression. 13990b57cec5SDimitry Andric // The negate variable should be called with false, and will be set to true 14000b57cec5SDimitry Andric // if the function call is negated, e.g. if (!mu.tryLock(...)) 14010b57cec5SDimitry Andric const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond, 14020b57cec5SDimitry Andric LocalVarContext C, 14030b57cec5SDimitry Andric bool &Negate) { 14040b57cec5SDimitry Andric if (!Cond) 14050b57cec5SDimitry Andric return nullptr; 14060b57cec5SDimitry Andric 14070b57cec5SDimitry Andric if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) { 14080b57cec5SDimitry Andric if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect) 14090b57cec5SDimitry Andric return getTrylockCallExpr(CallExp->getArg(0), C, Negate); 14100b57cec5SDimitry Andric return CallExp; 14110b57cec5SDimitry Andric } 14120b57cec5SDimitry Andric else if (const auto *PE = dyn_cast<ParenExpr>(Cond)) 14130b57cec5SDimitry Andric return getTrylockCallExpr(PE->getSubExpr(), C, Negate); 14140b57cec5SDimitry Andric else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond)) 14150b57cec5SDimitry Andric return getTrylockCallExpr(CE->getSubExpr(), C, Negate); 14160b57cec5SDimitry Andric else if (const auto *FE = dyn_cast<FullExpr>(Cond)) 14170b57cec5SDimitry Andric return getTrylockCallExpr(FE->getSubExpr(), C, Negate); 14180b57cec5SDimitry Andric else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) { 14190b57cec5SDimitry Andric const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C); 14200b57cec5SDimitry Andric return getTrylockCallExpr(E, C, Negate); 14210b57cec5SDimitry Andric } 14220b57cec5SDimitry Andric else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) { 14230b57cec5SDimitry Andric if (UOP->getOpcode() == UO_LNot) { 14240b57cec5SDimitry Andric Negate = !Negate; 14250b57cec5SDimitry Andric return getTrylockCallExpr(UOP->getSubExpr(), C, Negate); 14260b57cec5SDimitry Andric } 14270b57cec5SDimitry Andric return nullptr; 14280b57cec5SDimitry Andric } 14290b57cec5SDimitry Andric else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) { 14300b57cec5SDimitry Andric if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) { 14310b57cec5SDimitry Andric if (BOP->getOpcode() == BO_NE) 14320b57cec5SDimitry Andric Negate = !Negate; 14330b57cec5SDimitry Andric 14340b57cec5SDimitry Andric bool TCond = false; 14350b57cec5SDimitry Andric if (getStaticBooleanValue(BOP->getRHS(), TCond)) { 14360b57cec5SDimitry Andric if (!TCond) Negate = !Negate; 14370b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getLHS(), C, Negate); 14380b57cec5SDimitry Andric } 14390b57cec5SDimitry Andric TCond = false; 14400b57cec5SDimitry Andric if (getStaticBooleanValue(BOP->getLHS(), TCond)) { 14410b57cec5SDimitry Andric if (!TCond) Negate = !Negate; 14420b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getRHS(), C, Negate); 14430b57cec5SDimitry Andric } 14440b57cec5SDimitry Andric return nullptr; 14450b57cec5SDimitry Andric } 14460b57cec5SDimitry Andric if (BOP->getOpcode() == BO_LAnd) { 14470b57cec5SDimitry Andric // LHS must have been evaluated in a different block. 14480b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getRHS(), C, Negate); 14490b57cec5SDimitry Andric } 14500b57cec5SDimitry Andric if (BOP->getOpcode() == BO_LOr) 14510b57cec5SDimitry Andric return getTrylockCallExpr(BOP->getRHS(), C, Negate); 14520b57cec5SDimitry Andric return nullptr; 14530b57cec5SDimitry Andric } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) { 14540b57cec5SDimitry Andric bool TCond, FCond; 14550b57cec5SDimitry Andric if (getStaticBooleanValue(COP->getTrueExpr(), TCond) && 14560b57cec5SDimitry Andric getStaticBooleanValue(COP->getFalseExpr(), FCond)) { 14570b57cec5SDimitry Andric if (TCond && !FCond) 14580b57cec5SDimitry Andric return getTrylockCallExpr(COP->getCond(), C, Negate); 14590b57cec5SDimitry Andric if (!TCond && FCond) { 14600b57cec5SDimitry Andric Negate = !Negate; 14610b57cec5SDimitry Andric return getTrylockCallExpr(COP->getCond(), C, Negate); 14620b57cec5SDimitry Andric } 14630b57cec5SDimitry Andric } 14640b57cec5SDimitry Andric } 14650b57cec5SDimitry Andric return nullptr; 14660b57cec5SDimitry Andric } 14670b57cec5SDimitry Andric 14680b57cec5SDimitry Andric /// Find the lockset that holds on the edge between PredBlock 14690b57cec5SDimitry Andric /// and CurrBlock. The edge set is the exit set of PredBlock (passed 14700b57cec5SDimitry Andric /// as the ExitSet parameter) plus any trylocks, which are conditionally held. 14710b57cec5SDimitry Andric void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result, 14720b57cec5SDimitry Andric const FactSet &ExitSet, 14730b57cec5SDimitry Andric const CFGBlock *PredBlock, 14740b57cec5SDimitry Andric const CFGBlock *CurrBlock) { 14750b57cec5SDimitry Andric Result = ExitSet; 14760b57cec5SDimitry Andric 14770b57cec5SDimitry Andric const Stmt *Cond = PredBlock->getTerminatorCondition(); 14780b57cec5SDimitry Andric // We don't acquire try-locks on ?: branches, only when its result is used. 14790b57cec5SDimitry Andric if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminatorStmt())) 14800b57cec5SDimitry Andric return; 14810b57cec5SDimitry Andric 14820b57cec5SDimitry Andric bool Negate = false; 14830b57cec5SDimitry Andric const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()]; 14840b57cec5SDimitry Andric const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext; 14850b57cec5SDimitry Andric 14860b57cec5SDimitry Andric const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate); 14870b57cec5SDimitry Andric if (!Exp) 14880b57cec5SDimitry Andric return; 14890b57cec5SDimitry Andric 14900b57cec5SDimitry Andric auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 14910b57cec5SDimitry Andric if(!FunDecl || !FunDecl->hasAttrs()) 14920b57cec5SDimitry Andric return; 14930b57cec5SDimitry Andric 14940b57cec5SDimitry Andric CapExprSet ExclusiveLocksToAdd; 14950b57cec5SDimitry Andric CapExprSet SharedLocksToAdd; 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric // If the condition is a call to a Trylock function, then grab the attributes 14980b57cec5SDimitry Andric for (const auto *Attr : FunDecl->attrs()) { 14990b57cec5SDimitry Andric switch (Attr->getKind()) { 15000b57cec5SDimitry Andric case attr::TryAcquireCapability: { 15010b57cec5SDimitry Andric auto *A = cast<TryAcquireCapabilityAttr>(Attr); 15020b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 15030b57cec5SDimitry Andric Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(), 15040b57cec5SDimitry Andric Negate); 15050b57cec5SDimitry Andric break; 15060b57cec5SDimitry Andric }; 15070b57cec5SDimitry Andric case attr::ExclusiveTrylockFunction: { 15080b57cec5SDimitry Andric const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr); 150981ad6265SDimitry Andric getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock, 151081ad6265SDimitry Andric A->getSuccessValue(), Negate); 15110b57cec5SDimitry Andric break; 15120b57cec5SDimitry Andric } 15130b57cec5SDimitry Andric case attr::SharedTrylockFunction: { 15140b57cec5SDimitry Andric const auto *A = cast<SharedTrylockFunctionAttr>(Attr); 151581ad6265SDimitry Andric getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock, 151681ad6265SDimitry Andric A->getSuccessValue(), Negate); 15170b57cec5SDimitry Andric break; 15180b57cec5SDimitry Andric } 15190b57cec5SDimitry Andric default: 15200b57cec5SDimitry Andric break; 15210b57cec5SDimitry Andric } 15220b57cec5SDimitry Andric } 15230b57cec5SDimitry Andric 15240b57cec5SDimitry Andric // Add and remove locks. 15250b57cec5SDimitry Andric SourceLocation Loc = Exp->getExprLoc(); 15260b57cec5SDimitry Andric for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd) 1527a7dea167SDimitry Andric addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd, 152881ad6265SDimitry Andric LK_Exclusive, Loc)); 15290b57cec5SDimitry Andric for (const auto &SharedLockToAdd : SharedLocksToAdd) 1530a7dea167SDimitry Andric addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd, 153181ad6265SDimitry Andric LK_Shared, Loc)); 15320b57cec5SDimitry Andric } 15330b57cec5SDimitry Andric 15340b57cec5SDimitry Andric namespace { 15350b57cec5SDimitry Andric 15360b57cec5SDimitry Andric /// We use this class to visit different types of expressions in 15370b57cec5SDimitry Andric /// CFGBlocks, and build up the lockset. 15380b57cec5SDimitry Andric /// An expression may cause us to add or remove locks from the lockset, or else 15390b57cec5SDimitry Andric /// output error messages related to missing locks. 15400b57cec5SDimitry Andric /// FIXME: In future, we may be able to not inherit from a visitor. 15410b57cec5SDimitry Andric class BuildLockset : public ConstStmtVisitor<BuildLockset> { 15420b57cec5SDimitry Andric friend class ThreadSafetyAnalyzer; 15430b57cec5SDimitry Andric 15440b57cec5SDimitry Andric ThreadSafetyAnalyzer *Analyzer; 15450b57cec5SDimitry Andric FactSet FSet; 1546*5f757f3fSDimitry Andric // The fact set for the function on exit. 1547*5f757f3fSDimitry Andric const FactSet &FunctionExitFSet; 15480b57cec5SDimitry Andric LocalVariableMap::Context LVarCtx; 15490b57cec5SDimitry Andric unsigned CtxIndex; 15500b57cec5SDimitry Andric 15510b57cec5SDimitry Andric // helper functions 15520b57cec5SDimitry Andric 15530b57cec5SDimitry Andric void checkAccess(const Expr *Exp, AccessKind AK, 1554*5f757f3fSDimitry Andric ProtectedOperationKind POK = POK_VarAccess) { 1555*5f757f3fSDimitry Andric Analyzer->checkAccess(FSet, Exp, AK, POK); 1556*5f757f3fSDimitry Andric } 15570b57cec5SDimitry Andric void checkPtAccess(const Expr *Exp, AccessKind AK, 1558*5f757f3fSDimitry Andric ProtectedOperationKind POK = POK_VarAccess) { 1559*5f757f3fSDimitry Andric Analyzer->checkPtAccess(FSet, Exp, AK, POK); 1560*5f757f3fSDimitry Andric } 15610b57cec5SDimitry Andric 1562bdd1243dSDimitry Andric void handleCall(const Expr *Exp, const NamedDecl *D, 1563bdd1243dSDimitry Andric til::LiteralPtr *Self = nullptr, 1564bdd1243dSDimitry Andric SourceLocation Loc = SourceLocation()); 15650b57cec5SDimitry Andric void examineArguments(const FunctionDecl *FD, 15660b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgBegin, 15670b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgEnd, 15680b57cec5SDimitry Andric bool SkipFirstParam = false); 15690b57cec5SDimitry Andric 15700b57cec5SDimitry Andric public: 1571*5f757f3fSDimitry Andric BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info, 1572*5f757f3fSDimitry Andric const FactSet &FunctionExitFSet) 15730b57cec5SDimitry Andric : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet), 1574*5f757f3fSDimitry Andric FunctionExitFSet(FunctionExitFSet), LVarCtx(Info.EntryContext), 1575*5f757f3fSDimitry Andric CtxIndex(Info.EntryIndex) {} 15760b57cec5SDimitry Andric 15770b57cec5SDimitry Andric void VisitUnaryOperator(const UnaryOperator *UO); 15780b57cec5SDimitry Andric void VisitBinaryOperator(const BinaryOperator *BO); 15790b57cec5SDimitry Andric void VisitCastExpr(const CastExpr *CE); 15800b57cec5SDimitry Andric void VisitCallExpr(const CallExpr *Exp); 15810b57cec5SDimitry Andric void VisitCXXConstructExpr(const CXXConstructExpr *Exp); 15820b57cec5SDimitry Andric void VisitDeclStmt(const DeclStmt *S); 1583bdd1243dSDimitry Andric void VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *Exp); 1584*5f757f3fSDimitry Andric void VisitReturnStmt(const ReturnStmt *S); 15850b57cec5SDimitry Andric }; 15860b57cec5SDimitry Andric 15870b57cec5SDimitry Andric } // namespace 15880b57cec5SDimitry Andric 15890b57cec5SDimitry Andric /// Warn if the LSet does not contain a lock sufficient to protect access 15900b57cec5SDimitry Andric /// of at least the passed in AccessKind. 1591*5f757f3fSDimitry Andric void ThreadSafetyAnalyzer::warnIfMutexNotHeld( 1592*5f757f3fSDimitry Andric const FactSet &FSet, const NamedDecl *D, const Expr *Exp, AccessKind AK, 1593*5f757f3fSDimitry Andric Expr *MutexExp, ProtectedOperationKind POK, til::LiteralPtr *Self, 159481ad6265SDimitry Andric SourceLocation Loc) { 15950b57cec5SDimitry Andric LockKind LK = getLockKindFromAccessKind(AK); 1596*5f757f3fSDimitry Andric CapabilityExpr Cp = SxBuilder.translateAttrExpr(MutexExp, D, Exp, Self); 15970b57cec5SDimitry Andric if (Cp.isInvalid()) { 1598*5f757f3fSDimitry Andric warnInvalidLock(Handler, MutexExp, D, Exp, Cp.getKind()); 15990b57cec5SDimitry Andric return; 16000b57cec5SDimitry Andric } else if (Cp.shouldIgnore()) { 16010b57cec5SDimitry Andric return; 16020b57cec5SDimitry Andric } 16030b57cec5SDimitry Andric 16040b57cec5SDimitry Andric if (Cp.negative()) { 16050b57cec5SDimitry Andric // Negative capabilities act like locks excluded 1606*5f757f3fSDimitry Andric const FactEntry *LDat = FSet.findLock(FactMan, !Cp); 16070b57cec5SDimitry Andric if (LDat) { 1608*5f757f3fSDimitry Andric Handler.handleFunExcludesLock(Cp.getKind(), D->getNameAsString(), 1609*5f757f3fSDimitry Andric (!Cp).toString(), Loc); 16100b57cec5SDimitry Andric return; 16110b57cec5SDimitry Andric } 16120b57cec5SDimitry Andric 16130b57cec5SDimitry Andric // If this does not refer to a negative capability in the same class, 16140b57cec5SDimitry Andric // then stop here. 1615*5f757f3fSDimitry Andric if (!inCurrentScope(Cp)) 16160b57cec5SDimitry Andric return; 16170b57cec5SDimitry Andric 16180b57cec5SDimitry Andric // Otherwise the negative requirement must be propagated to the caller. 1619*5f757f3fSDimitry Andric LDat = FSet.findLock(FactMan, Cp); 16200b57cec5SDimitry Andric if (!LDat) { 1621*5f757f3fSDimitry Andric Handler.handleNegativeNotHeld(D, Cp.toString(), Loc); 16220b57cec5SDimitry Andric } 16230b57cec5SDimitry Andric return; 16240b57cec5SDimitry Andric } 16250b57cec5SDimitry Andric 1626*5f757f3fSDimitry Andric const FactEntry *LDat = FSet.findLockUniv(FactMan, Cp); 16270b57cec5SDimitry Andric bool NoError = true; 16280b57cec5SDimitry Andric if (!LDat) { 16290b57cec5SDimitry Andric // No exact match found. Look for a partial match. 1630*5f757f3fSDimitry Andric LDat = FSet.findPartialMatch(FactMan, Cp); 16310b57cec5SDimitry Andric if (LDat) { 16320b57cec5SDimitry Andric // Warn that there's no precise match. 16330b57cec5SDimitry Andric std::string PartMatchStr = LDat->toString(); 16340b57cec5SDimitry Andric StringRef PartMatchName(PartMatchStr); 1635*5f757f3fSDimitry Andric Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(), LK, Loc, 1636*5f757f3fSDimitry Andric &PartMatchName); 16370b57cec5SDimitry Andric } else { 16380b57cec5SDimitry Andric // Warn that there's no match at all. 1639*5f757f3fSDimitry Andric Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(), LK, Loc); 16400b57cec5SDimitry Andric } 16410b57cec5SDimitry Andric NoError = false; 16420b57cec5SDimitry Andric } 16430b57cec5SDimitry Andric // Make sure the mutex we found is the right kind. 16440b57cec5SDimitry Andric if (NoError && LDat && !LDat->isAtLeast(LK)) { 1645*5f757f3fSDimitry Andric Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(), LK, Loc); 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric } 16480b57cec5SDimitry Andric 16490b57cec5SDimitry Andric /// Warn if the LSet contains the given lock. 1650*5f757f3fSDimitry Andric void ThreadSafetyAnalyzer::warnIfMutexHeld(const FactSet &FSet, 1651*5f757f3fSDimitry Andric const NamedDecl *D, const Expr *Exp, 1652*5f757f3fSDimitry Andric Expr *MutexExp, 1653*5f757f3fSDimitry Andric til::LiteralPtr *Self, 1654bdd1243dSDimitry Andric SourceLocation Loc) { 1655*5f757f3fSDimitry Andric CapabilityExpr Cp = SxBuilder.translateAttrExpr(MutexExp, D, Exp, Self); 16560b57cec5SDimitry Andric if (Cp.isInvalid()) { 1657*5f757f3fSDimitry Andric warnInvalidLock(Handler, MutexExp, D, Exp, Cp.getKind()); 16580b57cec5SDimitry Andric return; 16590b57cec5SDimitry Andric } else if (Cp.shouldIgnore()) { 16600b57cec5SDimitry Andric return; 16610b57cec5SDimitry Andric } 16620b57cec5SDimitry Andric 1663*5f757f3fSDimitry Andric const FactEntry *LDat = FSet.findLock(FactMan, Cp); 16640b57cec5SDimitry Andric if (LDat) { 1665*5f757f3fSDimitry Andric Handler.handleFunExcludesLock(Cp.getKind(), D->getNameAsString(), 1666bdd1243dSDimitry Andric Cp.toString(), Loc); 16670b57cec5SDimitry Andric } 16680b57cec5SDimitry Andric } 16690b57cec5SDimitry Andric 16700b57cec5SDimitry Andric /// Checks guarded_by and pt_guarded_by attributes. 16710b57cec5SDimitry Andric /// Whenever we identify an access (read or write) to a DeclRefExpr that is 16720b57cec5SDimitry Andric /// marked with guarded_by, we must ensure the appropriate mutexes are held. 16730b57cec5SDimitry Andric /// Similarly, we check if the access is to an expression that dereferences 16740b57cec5SDimitry Andric /// a pointer marked with pt_guarded_by. 1675*5f757f3fSDimitry Andric void ThreadSafetyAnalyzer::checkAccess(const FactSet &FSet, const Expr *Exp, 1676*5f757f3fSDimitry Andric AccessKind AK, 16770b57cec5SDimitry Andric ProtectedOperationKind POK) { 16780b57cec5SDimitry Andric Exp = Exp->IgnoreImplicit()->IgnoreParenCasts(); 16790b57cec5SDimitry Andric 16800b57cec5SDimitry Andric SourceLocation Loc = Exp->getExprLoc(); 16810b57cec5SDimitry Andric 16820b57cec5SDimitry Andric // Local variables of reference type cannot be re-assigned; 16830b57cec5SDimitry Andric // map them to their initializer. 16840b57cec5SDimitry Andric while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) { 16850b57cec5SDimitry Andric const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl()); 16860b57cec5SDimitry Andric if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) { 16870b57cec5SDimitry Andric if (const auto *E = VD->getInit()) { 16880b57cec5SDimitry Andric // Guard against self-initialization. e.g., int &i = i; 16890b57cec5SDimitry Andric if (E == Exp) 16900b57cec5SDimitry Andric break; 16910b57cec5SDimitry Andric Exp = E; 16920b57cec5SDimitry Andric continue; 16930b57cec5SDimitry Andric } 16940b57cec5SDimitry Andric } 16950b57cec5SDimitry Andric break; 16960b57cec5SDimitry Andric } 16970b57cec5SDimitry Andric 16980b57cec5SDimitry Andric if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) { 16990b57cec5SDimitry Andric // For dereferences 17000b57cec5SDimitry Andric if (UO->getOpcode() == UO_Deref) 1701*5f757f3fSDimitry Andric checkPtAccess(FSet, UO->getSubExpr(), AK, POK); 17020b57cec5SDimitry Andric return; 17030b57cec5SDimitry Andric } 17040b57cec5SDimitry Andric 1705fcaf7f86SDimitry Andric if (const auto *BO = dyn_cast<BinaryOperator>(Exp)) { 1706fcaf7f86SDimitry Andric switch (BO->getOpcode()) { 1707fcaf7f86SDimitry Andric case BO_PtrMemD: // .* 1708*5f757f3fSDimitry Andric return checkAccess(FSet, BO->getLHS(), AK, POK); 1709fcaf7f86SDimitry Andric case BO_PtrMemI: // ->* 1710*5f757f3fSDimitry Andric return checkPtAccess(FSet, BO->getLHS(), AK, POK); 1711fcaf7f86SDimitry Andric default: 1712fcaf7f86SDimitry Andric return; 1713fcaf7f86SDimitry Andric } 1714fcaf7f86SDimitry Andric } 1715fcaf7f86SDimitry Andric 17160b57cec5SDimitry Andric if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) { 1717*5f757f3fSDimitry Andric checkPtAccess(FSet, AE->getLHS(), AK, POK); 17180b57cec5SDimitry Andric return; 17190b57cec5SDimitry Andric } 17200b57cec5SDimitry Andric 17210b57cec5SDimitry Andric if (const auto *ME = dyn_cast<MemberExpr>(Exp)) { 17220b57cec5SDimitry Andric if (ME->isArrow()) 1723*5f757f3fSDimitry Andric checkPtAccess(FSet, ME->getBase(), AK, POK); 17240b57cec5SDimitry Andric else 1725*5f757f3fSDimitry Andric checkAccess(FSet, ME->getBase(), AK, POK); 17260b57cec5SDimitry Andric } 17270b57cec5SDimitry Andric 17280b57cec5SDimitry Andric const ValueDecl *D = getValueDecl(Exp); 17290b57cec5SDimitry Andric if (!D || !D->hasAttrs()) 17300b57cec5SDimitry Andric return; 17310b57cec5SDimitry Andric 1732*5f757f3fSDimitry Andric if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(FactMan)) { 1733*5f757f3fSDimitry Andric Handler.handleNoMutexHeld(D, POK, AK, Loc); 17340b57cec5SDimitry Andric } 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric for (const auto *I : D->specific_attrs<GuardedByAttr>()) 1737*5f757f3fSDimitry Andric warnIfMutexNotHeld(FSet, D, Exp, AK, I->getArg(), POK, nullptr, Loc); 17380b57cec5SDimitry Andric } 17390b57cec5SDimitry Andric 17400b57cec5SDimitry Andric /// Checks pt_guarded_by and pt_guarded_var attributes. 17410b57cec5SDimitry Andric /// POK is the same operationKind that was passed to checkAccess. 1742*5f757f3fSDimitry Andric void ThreadSafetyAnalyzer::checkPtAccess(const FactSet &FSet, const Expr *Exp, 1743*5f757f3fSDimitry Andric AccessKind AK, 17440b57cec5SDimitry Andric ProtectedOperationKind POK) { 17450b57cec5SDimitry Andric while (true) { 17460b57cec5SDimitry Andric if (const auto *PE = dyn_cast<ParenExpr>(Exp)) { 17470b57cec5SDimitry Andric Exp = PE->getSubExpr(); 17480b57cec5SDimitry Andric continue; 17490b57cec5SDimitry Andric } 17500b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CastExpr>(Exp)) { 17510b57cec5SDimitry Andric if (CE->getCastKind() == CK_ArrayToPointerDecay) { 17520b57cec5SDimitry Andric // If it's an actual array, and not a pointer, then it's elements 17530b57cec5SDimitry Andric // are protected by GUARDED_BY, not PT_GUARDED_BY; 1754*5f757f3fSDimitry Andric checkAccess(FSet, CE->getSubExpr(), AK, POK); 17550b57cec5SDimitry Andric return; 17560b57cec5SDimitry Andric } 17570b57cec5SDimitry Andric Exp = CE->getSubExpr(); 17580b57cec5SDimitry Andric continue; 17590b57cec5SDimitry Andric } 17600b57cec5SDimitry Andric break; 17610b57cec5SDimitry Andric } 17620b57cec5SDimitry Andric 17630b57cec5SDimitry Andric // Pass by reference warnings are under a different flag. 17640b57cec5SDimitry Andric ProtectedOperationKind PtPOK = POK_VarDereference; 17650b57cec5SDimitry Andric if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef; 1766*5f757f3fSDimitry Andric if (POK == POK_ReturnByRef) 1767*5f757f3fSDimitry Andric PtPOK = POK_PtReturnByRef; 17680b57cec5SDimitry Andric 17690b57cec5SDimitry Andric const ValueDecl *D = getValueDecl(Exp); 17700b57cec5SDimitry Andric if (!D || !D->hasAttrs()) 17710b57cec5SDimitry Andric return; 17720b57cec5SDimitry Andric 1773*5f757f3fSDimitry Andric if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(FactMan)) 1774*5f757f3fSDimitry Andric Handler.handleNoMutexHeld(D, PtPOK, AK, Exp->getExprLoc()); 17750b57cec5SDimitry Andric 17760b57cec5SDimitry Andric for (auto const *I : D->specific_attrs<PtGuardedByAttr>()) 1777*5f757f3fSDimitry Andric warnIfMutexNotHeld(FSet, D, Exp, AK, I->getArg(), PtPOK, nullptr, 1778bdd1243dSDimitry Andric Exp->getExprLoc()); 17790b57cec5SDimitry Andric } 17800b57cec5SDimitry Andric 17810b57cec5SDimitry Andric /// Process a function call, method call, constructor call, 17820b57cec5SDimitry Andric /// or destructor call. This involves looking at the attributes on the 17830b57cec5SDimitry Andric /// corresponding function/method/constructor/destructor, issuing warnings, 17840b57cec5SDimitry Andric /// and updating the locksets accordingly. 17850b57cec5SDimitry Andric /// 17860b57cec5SDimitry Andric /// FIXME: For classes annotated with one of the guarded annotations, we need 17870b57cec5SDimitry Andric /// to treat const method calls as reads and non-const method calls as writes, 17880b57cec5SDimitry Andric /// and check that the appropriate locks are held. Non-const method calls with 17890b57cec5SDimitry Andric /// the same signature as const method calls can be also treated as reads. 17900b57cec5SDimitry Andric /// 1791bdd1243dSDimitry Andric /// \param Exp The call expression. 1792bdd1243dSDimitry Andric /// \param D The callee declaration. 1793*5f757f3fSDimitry Andric /// \param Self If \p Exp = nullptr, the implicit this argument or the argument 1794*5f757f3fSDimitry Andric /// of an implicitly called cleanup function. 1795bdd1243dSDimitry Andric /// \param Loc If \p Exp = nullptr, the location. 17960b57cec5SDimitry Andric void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D, 1797bdd1243dSDimitry Andric til::LiteralPtr *Self, SourceLocation Loc) { 17980b57cec5SDimitry Andric CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd; 17990b57cec5SDimitry Andric CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove; 18005ffd83dbSDimitry Andric CapExprSet ScopedReqsAndExcludes; 18010b57cec5SDimitry Andric 18020b57cec5SDimitry Andric // Figure out if we're constructing an object of scoped lockable class 1803bdd1243dSDimitry Andric CapabilityExpr Scp; 1804bdd1243dSDimitry Andric if (Exp) { 1805bdd1243dSDimitry Andric assert(!Self); 1806bdd1243dSDimitry Andric const auto *TagT = Exp->getType()->getAs<TagType>(); 1807bdd1243dSDimitry Andric if (TagT && Exp->isPRValue()) { 1808bdd1243dSDimitry Andric std::pair<til::LiteralPtr *, StringRef> Placeholder = 1809bdd1243dSDimitry Andric Analyzer->SxBuilder.createThisPlaceholder(Exp); 1810bdd1243dSDimitry Andric [[maybe_unused]] auto inserted = 1811*5f757f3fSDimitry Andric Analyzer->ConstructedObjects.insert({Exp, Placeholder.first}); 1812bdd1243dSDimitry Andric assert(inserted.second && "Are we visiting the same expression again?"); 1813bdd1243dSDimitry Andric if (isa<CXXConstructExpr>(Exp)) 1814bdd1243dSDimitry Andric Self = Placeholder.first; 1815bdd1243dSDimitry Andric if (TagT->getDecl()->hasAttr<ScopedLockableAttr>()) 1816bdd1243dSDimitry Andric Scp = CapabilityExpr(Placeholder.first, Placeholder.second, false); 18170b57cec5SDimitry Andric } 1818bdd1243dSDimitry Andric 1819bdd1243dSDimitry Andric assert(Loc.isInvalid()); 1820bdd1243dSDimitry Andric Loc = Exp->getExprLoc(); 18210b57cec5SDimitry Andric } 18220b57cec5SDimitry Andric 18230b57cec5SDimitry Andric for(const Attr *At : D->attrs()) { 18240b57cec5SDimitry Andric switch (At->getKind()) { 18250b57cec5SDimitry Andric // When we encounter a lock function, we need to add the lock to our 18260b57cec5SDimitry Andric // lockset. 18270b57cec5SDimitry Andric case attr::AcquireCapability: { 18280b57cec5SDimitry Andric const auto *A = cast<AcquireCapabilityAttr>(At); 18290b57cec5SDimitry Andric Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd 18300b57cec5SDimitry Andric : ExclusiveLocksToAdd, 1831bdd1243dSDimitry Andric A, Exp, D, Self); 18320b57cec5SDimitry Andric break; 18330b57cec5SDimitry Andric } 18340b57cec5SDimitry Andric 18350b57cec5SDimitry Andric // An assert will add a lock to the lockset, but will not generate 18360b57cec5SDimitry Andric // a warning if it is already there, and will not generate a warning 18370b57cec5SDimitry Andric // if it is not removed. 18380b57cec5SDimitry Andric case attr::AssertExclusiveLock: { 18390b57cec5SDimitry Andric const auto *A = cast<AssertExclusiveLockAttr>(At); 18400b57cec5SDimitry Andric 18410b57cec5SDimitry Andric CapExprSet AssertLocks; 1842bdd1243dSDimitry Andric Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self); 18430b57cec5SDimitry Andric for (const auto &AssertLock : AssertLocks) 1844fe6060f1SDimitry Andric Analyzer->addLock( 184581ad6265SDimitry Andric FSet, std::make_unique<LockableFactEntry>( 184681ad6265SDimitry Andric AssertLock, LK_Exclusive, Loc, FactEntry::Asserted)); 18470b57cec5SDimitry Andric break; 18480b57cec5SDimitry Andric } 18490b57cec5SDimitry Andric case attr::AssertSharedLock: { 18500b57cec5SDimitry Andric const auto *A = cast<AssertSharedLockAttr>(At); 18510b57cec5SDimitry Andric 18520b57cec5SDimitry Andric CapExprSet AssertLocks; 1853bdd1243dSDimitry Andric Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self); 18540b57cec5SDimitry Andric for (const auto &AssertLock : AssertLocks) 1855fe6060f1SDimitry Andric Analyzer->addLock( 185681ad6265SDimitry Andric FSet, std::make_unique<LockableFactEntry>( 185781ad6265SDimitry Andric AssertLock, LK_Shared, Loc, FactEntry::Asserted)); 18580b57cec5SDimitry Andric break; 18590b57cec5SDimitry Andric } 18600b57cec5SDimitry Andric 18610b57cec5SDimitry Andric case attr::AssertCapability: { 18620b57cec5SDimitry Andric const auto *A = cast<AssertCapabilityAttr>(At); 18630b57cec5SDimitry Andric CapExprSet AssertLocks; 1864bdd1243dSDimitry Andric Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self); 18650b57cec5SDimitry Andric for (const auto &AssertLock : AssertLocks) 186681ad6265SDimitry Andric Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>( 18670b57cec5SDimitry Andric AssertLock, 186881ad6265SDimitry Andric A->isShared() ? LK_Shared : LK_Exclusive, 186981ad6265SDimitry Andric Loc, FactEntry::Asserted)); 18700b57cec5SDimitry Andric break; 18710b57cec5SDimitry Andric } 18720b57cec5SDimitry Andric 18730b57cec5SDimitry Andric // When we encounter an unlock function, we need to remove unlocked 18740b57cec5SDimitry Andric // mutexes from the lockset, and flag a warning if they are not there. 18750b57cec5SDimitry Andric case attr::ReleaseCapability: { 18760b57cec5SDimitry Andric const auto *A = cast<ReleaseCapabilityAttr>(At); 18770b57cec5SDimitry Andric if (A->isGeneric()) 1878bdd1243dSDimitry Andric Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, Self); 18790b57cec5SDimitry Andric else if (A->isShared()) 1880bdd1243dSDimitry Andric Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, Self); 18810b57cec5SDimitry Andric else 1882bdd1243dSDimitry Andric Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, Self); 18830b57cec5SDimitry Andric break; 18840b57cec5SDimitry Andric } 18850b57cec5SDimitry Andric 18860b57cec5SDimitry Andric case attr::RequiresCapability: { 18870b57cec5SDimitry Andric const auto *A = cast<RequiresCapabilityAttr>(At); 18880b57cec5SDimitry Andric for (auto *Arg : A->args()) { 1889*5f757f3fSDimitry Andric Analyzer->warnIfMutexNotHeld(FSet, D, Exp, 1890*5f757f3fSDimitry Andric A->isShared() ? AK_Read : AK_Written, 1891*5f757f3fSDimitry Andric Arg, POK_FunctionCall, Self, Loc); 18920b57cec5SDimitry Andric // use for adopting a lock 1893bdd1243dSDimitry Andric if (!Scp.shouldIgnore()) 1894bdd1243dSDimitry Andric Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, Self); 18950b57cec5SDimitry Andric } 18960b57cec5SDimitry Andric break; 18970b57cec5SDimitry Andric } 18980b57cec5SDimitry Andric 18990b57cec5SDimitry Andric case attr::LocksExcluded: { 19000b57cec5SDimitry Andric const auto *A = cast<LocksExcludedAttr>(At); 19015ffd83dbSDimitry Andric for (auto *Arg : A->args()) { 1902*5f757f3fSDimitry Andric Analyzer->warnIfMutexHeld(FSet, D, Exp, Arg, Self, Loc); 19035ffd83dbSDimitry Andric // use for deferring a lock 1904bdd1243dSDimitry Andric if (!Scp.shouldIgnore()) 1905bdd1243dSDimitry Andric Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, Self); 19065ffd83dbSDimitry Andric } 19070b57cec5SDimitry Andric break; 19080b57cec5SDimitry Andric } 19090b57cec5SDimitry Andric 19100b57cec5SDimitry Andric // Ignore attributes unrelated to thread-safety 19110b57cec5SDimitry Andric default: 19120b57cec5SDimitry Andric break; 19130b57cec5SDimitry Andric } 19140b57cec5SDimitry Andric } 19150b57cec5SDimitry Andric 19160b57cec5SDimitry Andric // Remove locks first to allow lock upgrading/downgrading. 19170b57cec5SDimitry Andric // FIXME -- should only fully remove if the attribute refers to 'this'. 19180b57cec5SDimitry Andric bool Dtor = isa<CXXDestructorDecl>(D); 19190b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToRemove) 192081ad6265SDimitry Andric Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive); 19210b57cec5SDimitry Andric for (const auto &M : SharedLocksToRemove) 192281ad6265SDimitry Andric Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared); 19230b57cec5SDimitry Andric for (const auto &M : GenericLocksToRemove) 192481ad6265SDimitry Andric Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic); 19250b57cec5SDimitry Andric 19260b57cec5SDimitry Andric // Add locks. 1927fe6060f1SDimitry Andric FactEntry::SourceKind Source = 1928bdd1243dSDimitry Andric !Scp.shouldIgnore() ? FactEntry::Managed : FactEntry::Acquired; 19290b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToAdd) 193081ad6265SDimitry Andric Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(M, LK_Exclusive, 193181ad6265SDimitry Andric Loc, Source)); 19320b57cec5SDimitry Andric for (const auto &M : SharedLocksToAdd) 1933fe6060f1SDimitry Andric Analyzer->addLock( 193481ad6265SDimitry Andric FSet, std::make_unique<LockableFactEntry>(M, LK_Shared, Loc, Source)); 19350b57cec5SDimitry Andric 1936bdd1243dSDimitry Andric if (!Scp.shouldIgnore()) { 19370b57cec5SDimitry Andric // Add the managing object as a dummy mutex, mapped to the underlying mutex. 1938bdd1243dSDimitry Andric auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, Loc); 19390b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToAdd) 19405ffd83dbSDimitry Andric ScopedEntry->addLock(M); 19410b57cec5SDimitry Andric for (const auto &M : SharedLocksToAdd) 19425ffd83dbSDimitry Andric ScopedEntry->addLock(M); 19435ffd83dbSDimitry Andric for (const auto &M : ScopedReqsAndExcludes) 19445ffd83dbSDimitry Andric ScopedEntry->addLock(M); 19450b57cec5SDimitry Andric for (const auto &M : ExclusiveLocksToRemove) 19460b57cec5SDimitry Andric ScopedEntry->addExclusiveUnlock(M); 19470b57cec5SDimitry Andric for (const auto &M : SharedLocksToRemove) 19480b57cec5SDimitry Andric ScopedEntry->addSharedUnlock(M); 194981ad6265SDimitry Andric Analyzer->addLock(FSet, std::move(ScopedEntry)); 19500b57cec5SDimitry Andric } 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric /// For unary operations which read and write a variable, we need to 19540b57cec5SDimitry Andric /// check whether we hold any required mutexes. Reads are checked in 19550b57cec5SDimitry Andric /// VisitCastExpr. 19560b57cec5SDimitry Andric void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) { 19570b57cec5SDimitry Andric switch (UO->getOpcode()) { 19580b57cec5SDimitry Andric case UO_PostDec: 19590b57cec5SDimitry Andric case UO_PostInc: 19600b57cec5SDimitry Andric case UO_PreDec: 19610b57cec5SDimitry Andric case UO_PreInc: 19620b57cec5SDimitry Andric checkAccess(UO->getSubExpr(), AK_Written); 19630b57cec5SDimitry Andric break; 19640b57cec5SDimitry Andric default: 19650b57cec5SDimitry Andric break; 19660b57cec5SDimitry Andric } 19670b57cec5SDimitry Andric } 19680b57cec5SDimitry Andric 19690b57cec5SDimitry Andric /// For binary operations which assign to a variable (writes), we need to check 19700b57cec5SDimitry Andric /// whether we hold any required mutexes. 19710b57cec5SDimitry Andric /// FIXME: Deal with non-primitive types. 19720b57cec5SDimitry Andric void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) { 19730b57cec5SDimitry Andric if (!BO->isAssignmentOp()) 19740b57cec5SDimitry Andric return; 19750b57cec5SDimitry Andric 19760b57cec5SDimitry Andric // adjust the context 19770b57cec5SDimitry Andric LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx); 19780b57cec5SDimitry Andric 19790b57cec5SDimitry Andric checkAccess(BO->getLHS(), AK_Written); 19800b57cec5SDimitry Andric } 19810b57cec5SDimitry Andric 19820b57cec5SDimitry Andric /// Whenever we do an LValue to Rvalue cast, we are reading a variable and 19830b57cec5SDimitry Andric /// need to ensure we hold any required mutexes. 19840b57cec5SDimitry Andric /// FIXME: Deal with non-primitive types. 19850b57cec5SDimitry Andric void BuildLockset::VisitCastExpr(const CastExpr *CE) { 19860b57cec5SDimitry Andric if (CE->getCastKind() != CK_LValueToRValue) 19870b57cec5SDimitry Andric return; 19880b57cec5SDimitry Andric checkAccess(CE->getSubExpr(), AK_Read); 19890b57cec5SDimitry Andric } 19900b57cec5SDimitry Andric 19910b57cec5SDimitry Andric void BuildLockset::examineArguments(const FunctionDecl *FD, 19920b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgBegin, 19930b57cec5SDimitry Andric CallExpr::const_arg_iterator ArgEnd, 19940b57cec5SDimitry Andric bool SkipFirstParam) { 19950b57cec5SDimitry Andric // Currently we can't do anything if we don't know the function declaration. 19960b57cec5SDimitry Andric if (!FD) 19970b57cec5SDimitry Andric return; 19980b57cec5SDimitry Andric 19990b57cec5SDimitry Andric // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it 20000b57cec5SDimitry Andric // only turns off checking within the body of a function, but we also 20010b57cec5SDimitry Andric // use it to turn off checking in arguments to the function. This 20020b57cec5SDimitry Andric // could result in some false negatives, but the alternative is to 20030b57cec5SDimitry Andric // create yet another attribute. 20040b57cec5SDimitry Andric if (FD->hasAttr<NoThreadSafetyAnalysisAttr>()) 20050b57cec5SDimitry Andric return; 20060b57cec5SDimitry Andric 20070b57cec5SDimitry Andric const ArrayRef<ParmVarDecl *> Params = FD->parameters(); 20080b57cec5SDimitry Andric auto Param = Params.begin(); 20090b57cec5SDimitry Andric if (SkipFirstParam) 20100b57cec5SDimitry Andric ++Param; 20110b57cec5SDimitry Andric 20120b57cec5SDimitry Andric // There can be default arguments, so we stop when one iterator is at end(). 20130b57cec5SDimitry Andric for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd; 20140b57cec5SDimitry Andric ++Param, ++Arg) { 20150b57cec5SDimitry Andric QualType Qt = (*Param)->getType(); 20160b57cec5SDimitry Andric if (Qt->isReferenceType()) 20170b57cec5SDimitry Andric checkAccess(*Arg, AK_Read, POK_PassByRef); 20180b57cec5SDimitry Andric } 20190b57cec5SDimitry Andric } 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric void BuildLockset::VisitCallExpr(const CallExpr *Exp) { 20220b57cec5SDimitry Andric if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) { 20230b57cec5SDimitry Andric const auto *ME = dyn_cast<MemberExpr>(CE->getCallee()); 20240b57cec5SDimitry Andric // ME can be null when calling a method pointer 20250b57cec5SDimitry Andric const CXXMethodDecl *MD = CE->getMethodDecl(); 20260b57cec5SDimitry Andric 20270b57cec5SDimitry Andric if (ME && MD) { 20280b57cec5SDimitry Andric if (ME->isArrow()) { 2029fe6060f1SDimitry Andric // Should perhaps be AK_Written if !MD->isConst(). 20300b57cec5SDimitry Andric checkPtAccess(CE->getImplicitObjectArgument(), AK_Read); 20310b57cec5SDimitry Andric } else { 2032fe6060f1SDimitry Andric // Should perhaps be AK_Written if !MD->isConst(). 20330b57cec5SDimitry Andric checkAccess(CE->getImplicitObjectArgument(), AK_Read); 20340b57cec5SDimitry Andric } 20350b57cec5SDimitry Andric } 20360b57cec5SDimitry Andric 20370b57cec5SDimitry Andric examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end()); 20380b57cec5SDimitry Andric } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) { 203981ad6265SDimitry Andric OverloadedOperatorKind OEop = OE->getOperator(); 20400b57cec5SDimitry Andric switch (OEop) { 204181ad6265SDimitry Andric case OO_Equal: 204281ad6265SDimitry Andric case OO_PlusEqual: 204381ad6265SDimitry Andric case OO_MinusEqual: 204481ad6265SDimitry Andric case OO_StarEqual: 204581ad6265SDimitry Andric case OO_SlashEqual: 204681ad6265SDimitry Andric case OO_PercentEqual: 204781ad6265SDimitry Andric case OO_CaretEqual: 204881ad6265SDimitry Andric case OO_AmpEqual: 204981ad6265SDimitry Andric case OO_PipeEqual: 205081ad6265SDimitry Andric case OO_LessLessEqual: 205181ad6265SDimitry Andric case OO_GreaterGreaterEqual: 205281ad6265SDimitry Andric checkAccess(OE->getArg(1), AK_Read); 2053bdd1243dSDimitry Andric [[fallthrough]]; 205481ad6265SDimitry Andric case OO_PlusPlus: 205581ad6265SDimitry Andric case OO_MinusMinus: 205681ad6265SDimitry Andric checkAccess(OE->getArg(0), AK_Written); 20570b57cec5SDimitry Andric break; 20580b57cec5SDimitry Andric case OO_Star: 205981ad6265SDimitry Andric case OO_ArrowStar: 20600b57cec5SDimitry Andric case OO_Arrow: 20610b57cec5SDimitry Andric case OO_Subscript: 20620b57cec5SDimitry Andric if (!(OEop == OO_Star && OE->getNumArgs() > 1)) { 20630b57cec5SDimitry Andric // Grrr. operator* can be multiplication... 20640b57cec5SDimitry Andric checkPtAccess(OE->getArg(0), AK_Read); 20650b57cec5SDimitry Andric } 2066bdd1243dSDimitry Andric [[fallthrough]]; 20670b57cec5SDimitry Andric default: { 20680b57cec5SDimitry Andric // TODO: get rid of this, and rely on pass-by-ref instead. 20690b57cec5SDimitry Andric const Expr *Obj = OE->getArg(0); 20700b57cec5SDimitry Andric checkAccess(Obj, AK_Read); 20710b57cec5SDimitry Andric // Check the remaining arguments. For method operators, the first 20720b57cec5SDimitry Andric // argument is the implicit self argument, and doesn't appear in the 20730b57cec5SDimitry Andric // FunctionDecl, but for non-methods it does. 20740b57cec5SDimitry Andric const FunctionDecl *FD = OE->getDirectCallee(); 20750b57cec5SDimitry Andric examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(), 20760b57cec5SDimitry Andric /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD)); 20770b57cec5SDimitry Andric break; 20780b57cec5SDimitry Andric } 20790b57cec5SDimitry Andric } 20800b57cec5SDimitry Andric } else { 20810b57cec5SDimitry Andric examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end()); 20820b57cec5SDimitry Andric } 20830b57cec5SDimitry Andric 20840b57cec5SDimitry Andric auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl()); 20850b57cec5SDimitry Andric if(!D || !D->hasAttrs()) 20860b57cec5SDimitry Andric return; 20870b57cec5SDimitry Andric handleCall(Exp, D); 20880b57cec5SDimitry Andric } 20890b57cec5SDimitry Andric 20900b57cec5SDimitry Andric void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) { 20910b57cec5SDimitry Andric const CXXConstructorDecl *D = Exp->getConstructor(); 20920b57cec5SDimitry Andric if (D && D->isCopyConstructor()) { 20930b57cec5SDimitry Andric const Expr* Source = Exp->getArg(0); 20940b57cec5SDimitry Andric checkAccess(Source, AK_Read); 20950b57cec5SDimitry Andric } else { 20960b57cec5SDimitry Andric examineArguments(D, Exp->arg_begin(), Exp->arg_end()); 20970b57cec5SDimitry Andric } 2098bdd1243dSDimitry Andric if (D && D->hasAttrs()) 2099bdd1243dSDimitry Andric handleCall(Exp, D); 21000b57cec5SDimitry Andric } 21010b57cec5SDimitry Andric 2102bdd1243dSDimitry Andric static const Expr *UnpackConstruction(const Expr *E) { 2103bdd1243dSDimitry Andric if (auto *CE = dyn_cast<CastExpr>(E)) 2104bdd1243dSDimitry Andric if (CE->getCastKind() == CK_NoOp) 2105bdd1243dSDimitry Andric E = CE->getSubExpr()->IgnoreParens(); 2106bdd1243dSDimitry Andric if (auto *CE = dyn_cast<CastExpr>(E)) 2107bdd1243dSDimitry Andric if (CE->getCastKind() == CK_ConstructorConversion || 2108bdd1243dSDimitry Andric CE->getCastKind() == CK_UserDefinedConversion) 2109bdd1243dSDimitry Andric E = CE->getSubExpr(); 2110bdd1243dSDimitry Andric if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E)) 2111bdd1243dSDimitry Andric E = BTE->getSubExpr(); 2112bdd1243dSDimitry Andric return E; 21130b57cec5SDimitry Andric } 21140b57cec5SDimitry Andric 21150b57cec5SDimitry Andric void BuildLockset::VisitDeclStmt(const DeclStmt *S) { 21160b57cec5SDimitry Andric // adjust the context 21170b57cec5SDimitry Andric LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx); 21180b57cec5SDimitry Andric 21190b57cec5SDimitry Andric for (auto *D : S->getDeclGroup()) { 21200b57cec5SDimitry Andric if (auto *VD = dyn_cast_or_null<VarDecl>(D)) { 2121bdd1243dSDimitry Andric const Expr *E = VD->getInit(); 21220b57cec5SDimitry Andric if (!E) 21230b57cec5SDimitry Andric continue; 21240b57cec5SDimitry Andric E = E->IgnoreParens(); 21250b57cec5SDimitry Andric 21260b57cec5SDimitry Andric // handle constructors that involve temporaries 21270b57cec5SDimitry Andric if (auto *EWC = dyn_cast<ExprWithCleanups>(E)) 21285ffd83dbSDimitry Andric E = EWC->getSubExpr()->IgnoreParens(); 2129bdd1243dSDimitry Andric E = UnpackConstruction(E); 21300b57cec5SDimitry Andric 2131*5f757f3fSDimitry Andric if (auto Object = Analyzer->ConstructedObjects.find(E); 2132*5f757f3fSDimitry Andric Object != Analyzer->ConstructedObjects.end()) { 2133bdd1243dSDimitry Andric Object->second->setClangDecl(VD); 2134*5f757f3fSDimitry Andric Analyzer->ConstructedObjects.erase(Object); 21350b57cec5SDimitry Andric } 21360b57cec5SDimitry Andric } 21370b57cec5SDimitry Andric } 21380b57cec5SDimitry Andric } 21390b57cec5SDimitry Andric 2140bdd1243dSDimitry Andric void BuildLockset::VisitMaterializeTemporaryExpr( 2141bdd1243dSDimitry Andric const MaterializeTemporaryExpr *Exp) { 2142bdd1243dSDimitry Andric if (const ValueDecl *ExtD = Exp->getExtendingDecl()) { 2143*5f757f3fSDimitry Andric if (auto Object = Analyzer->ConstructedObjects.find( 2144*5f757f3fSDimitry Andric UnpackConstruction(Exp->getSubExpr())); 2145*5f757f3fSDimitry Andric Object != Analyzer->ConstructedObjects.end()) { 2146bdd1243dSDimitry Andric Object->second->setClangDecl(ExtD); 2147*5f757f3fSDimitry Andric Analyzer->ConstructedObjects.erase(Object); 2148bdd1243dSDimitry Andric } 2149bdd1243dSDimitry Andric } 2150bdd1243dSDimitry Andric } 2151bdd1243dSDimitry Andric 2152*5f757f3fSDimitry Andric void BuildLockset::VisitReturnStmt(const ReturnStmt *S) { 2153*5f757f3fSDimitry Andric if (Analyzer->CurrentFunction == nullptr) 2154*5f757f3fSDimitry Andric return; 2155*5f757f3fSDimitry Andric const Expr *RetVal = S->getRetValue(); 2156*5f757f3fSDimitry Andric if (!RetVal) 2157*5f757f3fSDimitry Andric return; 2158*5f757f3fSDimitry Andric 2159*5f757f3fSDimitry Andric // If returning by reference, check that the function requires the appropriate 2160*5f757f3fSDimitry Andric // capabilities. 2161*5f757f3fSDimitry Andric const QualType ReturnType = 2162*5f757f3fSDimitry Andric Analyzer->CurrentFunction->getReturnType().getCanonicalType(); 2163*5f757f3fSDimitry Andric if (ReturnType->isLValueReferenceType()) { 2164*5f757f3fSDimitry Andric Analyzer->checkAccess( 2165*5f757f3fSDimitry Andric FunctionExitFSet, RetVal, 2166*5f757f3fSDimitry Andric ReturnType->getPointeeType().isConstQualified() ? AK_Read : AK_Written, 2167*5f757f3fSDimitry Andric POK_ReturnByRef); 2168*5f757f3fSDimitry Andric } 2169*5f757f3fSDimitry Andric } 2170*5f757f3fSDimitry Andric 217128a41182SDimitry Andric /// Given two facts merging on a join point, possibly warn and decide whether to 217228a41182SDimitry Andric /// keep or replace. 2173fe6060f1SDimitry Andric /// 217428a41182SDimitry Andric /// \param CanModify Whether we can replace \p A by \p B. 217528a41182SDimitry Andric /// \return false if we should keep \p A, true if we should take \p B. 217628a41182SDimitry Andric bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B, 217728a41182SDimitry Andric bool CanModify) { 2178fe6060f1SDimitry Andric if (A.kind() != B.kind()) { 2179fe6060f1SDimitry Andric // For managed capabilities, the destructor should unlock in the right mode 2180fe6060f1SDimitry Andric // anyway. For asserted capabilities no unlocking is needed. 2181fe6060f1SDimitry Andric if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) { 218228a41182SDimitry Andric // The shared capability subsumes the exclusive capability, if possible. 218328a41182SDimitry Andric bool ShouldTakeB = B.kind() == LK_Shared; 218428a41182SDimitry Andric if (CanModify || !ShouldTakeB) 218528a41182SDimitry Andric return ShouldTakeB; 218628a41182SDimitry Andric } 218781ad6265SDimitry Andric Handler.handleExclusiveAndShared(B.getKind(), B.toString(), B.loc(), 218881ad6265SDimitry Andric A.loc()); 2189fe6060f1SDimitry Andric // Take the exclusive capability to reduce further warnings. 219028a41182SDimitry Andric return CanModify && B.kind() == LK_Exclusive; 2191fe6060f1SDimitry Andric } else { 2192fe6060f1SDimitry Andric // The non-asserted capability is the one we want to track. 219328a41182SDimitry Andric return CanModify && A.asserted() && !B.asserted(); 2194fe6060f1SDimitry Andric } 2195fe6060f1SDimitry Andric } 2196fe6060f1SDimitry Andric 21970b57cec5SDimitry Andric /// Compute the intersection of two locksets and issue warnings for any 21980b57cec5SDimitry Andric /// locks in the symmetric difference. 21990b57cec5SDimitry Andric /// 22000b57cec5SDimitry Andric /// This function is used at a merge point in the CFG when comparing the lockset 22010b57cec5SDimitry Andric /// of each branch being merged. For example, given the following sequence: 22020b57cec5SDimitry Andric /// A; if () then B; else C; D; we need to check that the lockset after B and C 22030b57cec5SDimitry Andric /// are the same. In the event of a difference, we use the intersection of these 22040b57cec5SDimitry Andric /// two locksets at the start of D. 22050b57cec5SDimitry Andric /// 2206fe6060f1SDimitry Andric /// \param EntrySet A lockset for entry into a (possibly new) block. 2207fe6060f1SDimitry Andric /// \param ExitSet The lockset on exiting a preceding block. 22080b57cec5SDimitry Andric /// \param JoinLoc The location of the join point for error reporting 2209fe6060f1SDimitry Andric /// \param EntryLEK The warning if a mutex is missing from \p EntrySet. 2210fe6060f1SDimitry Andric /// \param ExitLEK The warning if a mutex is missing from \p ExitSet. 2211fe6060f1SDimitry Andric void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &EntrySet, 2212fe6060f1SDimitry Andric const FactSet &ExitSet, 22130b57cec5SDimitry Andric SourceLocation JoinLoc, 2214fe6060f1SDimitry Andric LockErrorKind EntryLEK, 2215fe6060f1SDimitry Andric LockErrorKind ExitLEK) { 2216fe6060f1SDimitry Andric FactSet EntrySetOrig = EntrySet; 22170b57cec5SDimitry Andric 2218fe6060f1SDimitry Andric // Find locks in ExitSet that conflict or are not in EntrySet, and warn. 2219fe6060f1SDimitry Andric for (const auto &Fact : ExitSet) { 2220fe6060f1SDimitry Andric const FactEntry &ExitFact = FactMan[Fact]; 22210b57cec5SDimitry Andric 2222fe6060f1SDimitry Andric FactSet::iterator EntryIt = EntrySet.findLockIter(FactMan, ExitFact); 2223fe6060f1SDimitry Andric if (EntryIt != EntrySet.end()) { 222428a41182SDimitry Andric if (join(FactMan[*EntryIt], ExitFact, 222528a41182SDimitry Andric EntryLEK != LEK_LockedSomeLoopIterations)) 2226fe6060f1SDimitry Andric *EntryIt = Fact; 2227fe6060f1SDimitry Andric } else if (!ExitFact.managed()) { 2228fe6060f1SDimitry Andric ExitFact.handleRemovalFromIntersection(ExitSet, FactMan, JoinLoc, 2229fe6060f1SDimitry Andric EntryLEK, Handler); 22300b57cec5SDimitry Andric } 22310b57cec5SDimitry Andric } 22320b57cec5SDimitry Andric 2233fe6060f1SDimitry Andric // Find locks in EntrySet that are not in ExitSet, and remove them. 2234fe6060f1SDimitry Andric for (const auto &Fact : EntrySetOrig) { 2235fe6060f1SDimitry Andric const FactEntry *EntryFact = &FactMan[Fact]; 2236fe6060f1SDimitry Andric const FactEntry *ExitFact = ExitSet.findLock(FactMan, *EntryFact); 22370b57cec5SDimitry Andric 2238fe6060f1SDimitry Andric if (!ExitFact) { 2239fe6060f1SDimitry Andric if (!EntryFact->managed() || ExitLEK == LEK_LockedSomeLoopIterations) 2240fe6060f1SDimitry Andric EntryFact->handleRemovalFromIntersection(EntrySetOrig, FactMan, JoinLoc, 2241fe6060f1SDimitry Andric ExitLEK, Handler); 2242fe6060f1SDimitry Andric if (ExitLEK == LEK_LockedSomePredecessors) 2243fe6060f1SDimitry Andric EntrySet.removeLock(FactMan, *EntryFact); 22440b57cec5SDimitry Andric } 22450b57cec5SDimitry Andric } 22460b57cec5SDimitry Andric } 22470b57cec5SDimitry Andric 22480b57cec5SDimitry Andric // Return true if block B never continues to its successors. 22490b57cec5SDimitry Andric static bool neverReturns(const CFGBlock *B) { 22500b57cec5SDimitry Andric if (B->hasNoReturnElement()) 22510b57cec5SDimitry Andric return true; 22520b57cec5SDimitry Andric if (B->empty()) 22530b57cec5SDimitry Andric return false; 22540b57cec5SDimitry Andric 22550b57cec5SDimitry Andric CFGElement Last = B->back(); 2256bdd1243dSDimitry Andric if (std::optional<CFGStmt> S = Last.getAs<CFGStmt>()) { 22570b57cec5SDimitry Andric if (isa<CXXThrowExpr>(S->getStmt())) 22580b57cec5SDimitry Andric return true; 22590b57cec5SDimitry Andric } 22600b57cec5SDimitry Andric return false; 22610b57cec5SDimitry Andric } 22620b57cec5SDimitry Andric 22630b57cec5SDimitry Andric /// Check a function's CFG for thread-safety violations. 22640b57cec5SDimitry Andric /// 22650b57cec5SDimitry Andric /// We traverse the blocks in the CFG, compute the set of mutexes that are held 22660b57cec5SDimitry Andric /// at the end of each block, and issue warnings for thread safety violations. 22670b57cec5SDimitry Andric /// Each block in the CFG is traversed exactly once. 22680b57cec5SDimitry Andric void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) { 22690b57cec5SDimitry Andric // TODO: this whole function needs be rewritten as a visitor for CFGWalker. 22700b57cec5SDimitry Andric // For now, we just use the walker to set things up. 22710b57cec5SDimitry Andric threadSafety::CFGWalker walker; 22720b57cec5SDimitry Andric if (!walker.init(AC)) 22730b57cec5SDimitry Andric return; 22740b57cec5SDimitry Andric 22750b57cec5SDimitry Andric // AC.dumpCFG(true); 22760b57cec5SDimitry Andric // threadSafety::printSCFG(walker); 22770b57cec5SDimitry Andric 22780b57cec5SDimitry Andric CFG *CFGraph = walker.getGraph(); 22790b57cec5SDimitry Andric const NamedDecl *D = walker.getDecl(); 2280*5f757f3fSDimitry Andric CurrentFunction = dyn_cast<FunctionDecl>(D); 22810b57cec5SDimitry Andric 22820b57cec5SDimitry Andric if (D->hasAttr<NoThreadSafetyAnalysisAttr>()) 22830b57cec5SDimitry Andric return; 22840b57cec5SDimitry Andric 22850b57cec5SDimitry Andric // FIXME: Do something a bit more intelligent inside constructor and 22860b57cec5SDimitry Andric // destructor code. Constructors and destructors must assume unique access 22870b57cec5SDimitry Andric // to 'this', so checks on member variable access is disabled, but we should 22880b57cec5SDimitry Andric // still enable checks on other objects. 22890b57cec5SDimitry Andric if (isa<CXXConstructorDecl>(D)) 22900b57cec5SDimitry Andric return; // Don't check inside constructors. 22910b57cec5SDimitry Andric if (isa<CXXDestructorDecl>(D)) 22920b57cec5SDimitry Andric return; // Don't check inside destructors. 22930b57cec5SDimitry Andric 22940b57cec5SDimitry Andric Handler.enterFunction(CurrentFunction); 22950b57cec5SDimitry Andric 22960b57cec5SDimitry Andric BlockInfo.resize(CFGraph->getNumBlockIDs(), 22970b57cec5SDimitry Andric CFGBlockInfo::getEmptyBlockInfo(LocalVarMap)); 22980b57cec5SDimitry Andric 22990b57cec5SDimitry Andric // We need to explore the CFG via a "topological" ordering. 23000b57cec5SDimitry Andric // That way, we will be guaranteed to have information about required 23010b57cec5SDimitry Andric // predecessor locksets when exploring a new block. 23020b57cec5SDimitry Andric const PostOrderCFGView *SortedGraph = walker.getSortedGraph(); 23030b57cec5SDimitry Andric PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph); 23040b57cec5SDimitry Andric 2305*5f757f3fSDimitry Andric CFGBlockInfo &Initial = BlockInfo[CFGraph->getEntry().getBlockID()]; 2306*5f757f3fSDimitry Andric CFGBlockInfo &Final = BlockInfo[CFGraph->getExit().getBlockID()]; 2307*5f757f3fSDimitry Andric 23080b57cec5SDimitry Andric // Mark entry block as reachable 2309*5f757f3fSDimitry Andric Initial.Reachable = true; 23100b57cec5SDimitry Andric 23110b57cec5SDimitry Andric // Compute SSA names for local variables 23120b57cec5SDimitry Andric LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo); 23130b57cec5SDimitry Andric 23140b57cec5SDimitry Andric // Fill in source locations for all CFGBlocks. 23150b57cec5SDimitry Andric findBlockLocations(CFGraph, SortedGraph, BlockInfo); 23160b57cec5SDimitry Andric 23170b57cec5SDimitry Andric CapExprSet ExclusiveLocksAcquired; 23180b57cec5SDimitry Andric CapExprSet SharedLocksAcquired; 23190b57cec5SDimitry Andric CapExprSet LocksReleased; 23200b57cec5SDimitry Andric 23210b57cec5SDimitry Andric // Add locks from exclusive_locks_required and shared_locks_required 23220b57cec5SDimitry Andric // to initial lockset. Also turn off checking for lock and unlock functions. 23230b57cec5SDimitry Andric // FIXME: is there a more intelligent way to check lock/unlock functions? 23240b57cec5SDimitry Andric if (!SortedGraph->empty() && D->hasAttrs()) { 2325*5f757f3fSDimitry Andric assert(*SortedGraph->begin() == &CFGraph->getEntry()); 2326*5f757f3fSDimitry Andric FactSet &InitialLockset = Initial.EntrySet; 23270b57cec5SDimitry Andric 23280b57cec5SDimitry Andric CapExprSet ExclusiveLocksToAdd; 23290b57cec5SDimitry Andric CapExprSet SharedLocksToAdd; 23300b57cec5SDimitry Andric 23310b57cec5SDimitry Andric SourceLocation Loc = D->getLocation(); 23320b57cec5SDimitry Andric for (const auto *Attr : D->attrs()) { 23330b57cec5SDimitry Andric Loc = Attr->getLocation(); 23340b57cec5SDimitry Andric if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) { 23350b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 23360b57cec5SDimitry Andric nullptr, D); 23370b57cec5SDimitry Andric } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) { 23380b57cec5SDimitry Andric // UNLOCK_FUNCTION() is used to hide the underlying lock implementation. 23390b57cec5SDimitry Andric // We must ignore such methods. 23400b57cec5SDimitry Andric if (A->args_size() == 0) 23410b57cec5SDimitry Andric return; 23420b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A, 23430b57cec5SDimitry Andric nullptr, D); 23440b57cec5SDimitry Andric getMutexIDs(LocksReleased, A, nullptr, D); 23450b57cec5SDimitry Andric } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) { 23460b57cec5SDimitry Andric if (A->args_size() == 0) 23470b57cec5SDimitry Andric return; 23480b57cec5SDimitry Andric getMutexIDs(A->isShared() ? SharedLocksAcquired 23490b57cec5SDimitry Andric : ExclusiveLocksAcquired, 23500b57cec5SDimitry Andric A, nullptr, D); 23510b57cec5SDimitry Andric } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) { 23520b57cec5SDimitry Andric // Don't try to check trylock functions for now. 23530b57cec5SDimitry Andric return; 23540b57cec5SDimitry Andric } else if (isa<SharedTrylockFunctionAttr>(Attr)) { 23550b57cec5SDimitry Andric // Don't try to check trylock functions for now. 23560b57cec5SDimitry Andric return; 23570b57cec5SDimitry Andric } else if (isa<TryAcquireCapabilityAttr>(Attr)) { 23580b57cec5SDimitry Andric // Don't try to check trylock functions for now. 23590b57cec5SDimitry Andric return; 23600b57cec5SDimitry Andric } 23610b57cec5SDimitry Andric } 23620b57cec5SDimitry Andric 23630b57cec5SDimitry Andric // FIXME -- Loc can be wrong here. 23640b57cec5SDimitry Andric for (const auto &Mu : ExclusiveLocksToAdd) { 2365fe6060f1SDimitry Andric auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc, 2366fe6060f1SDimitry Andric FactEntry::Declared); 236781ad6265SDimitry Andric addLock(InitialLockset, std::move(Entry), true); 23680b57cec5SDimitry Andric } 23690b57cec5SDimitry Andric for (const auto &Mu : SharedLocksToAdd) { 2370fe6060f1SDimitry Andric auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc, 2371fe6060f1SDimitry Andric FactEntry::Declared); 237281ad6265SDimitry Andric addLock(InitialLockset, std::move(Entry), true); 23730b57cec5SDimitry Andric } 23740b57cec5SDimitry Andric } 23750b57cec5SDimitry Andric 2376*5f757f3fSDimitry Andric // Compute the expected exit set. 2377*5f757f3fSDimitry Andric // By default, we expect all locks held on entry to be held on exit. 2378*5f757f3fSDimitry Andric FactSet ExpectedFunctionExitSet = Initial.EntrySet; 2379*5f757f3fSDimitry Andric 2380*5f757f3fSDimitry Andric // Adjust the expected exit set by adding or removing locks, as declared 2381*5f757f3fSDimitry Andric // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then 2382*5f757f3fSDimitry Andric // issue the appropriate warning. 2383*5f757f3fSDimitry Andric // FIXME: the location here is not quite right. 2384*5f757f3fSDimitry Andric for (const auto &Lock : ExclusiveLocksAcquired) 2385*5f757f3fSDimitry Andric ExpectedFunctionExitSet.addLock( 2386*5f757f3fSDimitry Andric FactMan, std::make_unique<LockableFactEntry>(Lock, LK_Exclusive, 2387*5f757f3fSDimitry Andric D->getLocation())); 2388*5f757f3fSDimitry Andric for (const auto &Lock : SharedLocksAcquired) 2389*5f757f3fSDimitry Andric ExpectedFunctionExitSet.addLock( 2390*5f757f3fSDimitry Andric FactMan, 2391*5f757f3fSDimitry Andric std::make_unique<LockableFactEntry>(Lock, LK_Shared, D->getLocation())); 2392*5f757f3fSDimitry Andric for (const auto &Lock : LocksReleased) 2393*5f757f3fSDimitry Andric ExpectedFunctionExitSet.removeLock(FactMan, Lock); 2394*5f757f3fSDimitry Andric 23950b57cec5SDimitry Andric for (const auto *CurrBlock : *SortedGraph) { 23960b57cec5SDimitry Andric unsigned CurrBlockID = CurrBlock->getBlockID(); 23970b57cec5SDimitry Andric CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID]; 23980b57cec5SDimitry Andric 23990b57cec5SDimitry Andric // Use the default initial lockset in case there are no predecessors. 24000b57cec5SDimitry Andric VisitedBlocks.insert(CurrBlock); 24010b57cec5SDimitry Andric 24020b57cec5SDimitry Andric // Iterate through the predecessor blocks and warn if the lockset for all 24030b57cec5SDimitry Andric // predecessors is not the same. We take the entry lockset of the current 24040b57cec5SDimitry Andric // block to be the intersection of all previous locksets. 24050b57cec5SDimitry Andric // FIXME: By keeping the intersection, we may output more errors in future 24060b57cec5SDimitry Andric // for a lock which is not in the intersection, but was in the union. We 24070b57cec5SDimitry Andric // may want to also keep the union in future. As an example, let's say 24080b57cec5SDimitry Andric // the intersection contains Mutex L, and the union contains L and M. 24090b57cec5SDimitry Andric // Later we unlock M. At this point, we would output an error because we 24100b57cec5SDimitry Andric // never locked M; although the real error is probably that we forgot to 24110b57cec5SDimitry Andric // lock M on all code paths. Conversely, let's say that later we lock M. 24120b57cec5SDimitry Andric // In this case, we should compare against the intersection instead of the 24130b57cec5SDimitry Andric // union because the real error is probably that we forgot to unlock M on 24140b57cec5SDimitry Andric // all code paths. 24150b57cec5SDimitry Andric bool LocksetInitialized = false; 24160b57cec5SDimitry Andric for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(), 24170b57cec5SDimitry Andric PE = CurrBlock->pred_end(); PI != PE; ++PI) { 24180b57cec5SDimitry Andric // if *PI -> CurrBlock is a back edge 24190b57cec5SDimitry Andric if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) 24200b57cec5SDimitry Andric continue; 24210b57cec5SDimitry Andric 24220b57cec5SDimitry Andric unsigned PrevBlockID = (*PI)->getBlockID(); 24230b57cec5SDimitry Andric CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID]; 24240b57cec5SDimitry Andric 24250b57cec5SDimitry Andric // Ignore edges from blocks that can't return. 24260b57cec5SDimitry Andric if (neverReturns(*PI) || !PrevBlockInfo->Reachable) 24270b57cec5SDimitry Andric continue; 24280b57cec5SDimitry Andric 24290b57cec5SDimitry Andric // Okay, we can reach this block from the entry. 24300b57cec5SDimitry Andric CurrBlockInfo->Reachable = true; 24310b57cec5SDimitry Andric 24320b57cec5SDimitry Andric FactSet PrevLockset; 24330b57cec5SDimitry Andric getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock); 24340b57cec5SDimitry Andric 24350b57cec5SDimitry Andric if (!LocksetInitialized) { 24360b57cec5SDimitry Andric CurrBlockInfo->EntrySet = PrevLockset; 24370b57cec5SDimitry Andric LocksetInitialized = true; 24380b57cec5SDimitry Andric } else { 2439349cc55cSDimitry Andric // Surprisingly 'continue' doesn't always produce back edges, because 2440349cc55cSDimitry Andric // the CFG has empty "transition" blocks where they meet with the end 2441349cc55cSDimitry Andric // of the regular loop body. We still want to diagnose them as loop. 2442349cc55cSDimitry Andric intersectAndWarn( 2443349cc55cSDimitry Andric CurrBlockInfo->EntrySet, PrevLockset, CurrBlockInfo->EntryLoc, 2444349cc55cSDimitry Andric isa_and_nonnull<ContinueStmt>((*PI)->getTerminatorStmt()) 2445349cc55cSDimitry Andric ? LEK_LockedSomeLoopIterations 2446349cc55cSDimitry Andric : LEK_LockedSomePredecessors); 24470b57cec5SDimitry Andric } 24480b57cec5SDimitry Andric } 24490b57cec5SDimitry Andric 24500b57cec5SDimitry Andric // Skip rest of block if it's not reachable. 24510b57cec5SDimitry Andric if (!CurrBlockInfo->Reachable) 24520b57cec5SDimitry Andric continue; 24530b57cec5SDimitry Andric 2454*5f757f3fSDimitry Andric BuildLockset LocksetBuilder(this, *CurrBlockInfo, ExpectedFunctionExitSet); 24550b57cec5SDimitry Andric 24560b57cec5SDimitry Andric // Visit all the statements in the basic block. 24570b57cec5SDimitry Andric for (const auto &BI : *CurrBlock) { 24580b57cec5SDimitry Andric switch (BI.getKind()) { 24590b57cec5SDimitry Andric case CFGElement::Statement: { 24600b57cec5SDimitry Andric CFGStmt CS = BI.castAs<CFGStmt>(); 24610b57cec5SDimitry Andric LocksetBuilder.Visit(CS.getStmt()); 24620b57cec5SDimitry Andric break; 24630b57cec5SDimitry Andric } 2464bdd1243dSDimitry Andric // Ignore BaseDtor and MemberDtor for now. 24650b57cec5SDimitry Andric case CFGElement::AutomaticObjectDtor: { 24660b57cec5SDimitry Andric CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>(); 24670b57cec5SDimitry Andric const auto *DD = AD.getDestructorDecl(AC.getASTContext()); 24680b57cec5SDimitry Andric if (!DD->hasAttrs()) 24690b57cec5SDimitry Andric break; 24700b57cec5SDimitry Andric 2471bdd1243dSDimitry Andric LocksetBuilder.handleCall(nullptr, DD, 2472bdd1243dSDimitry Andric SxBuilder.createVariable(AD.getVarDecl()), 24730b57cec5SDimitry Andric AD.getTriggerStmt()->getEndLoc()); 2474bdd1243dSDimitry Andric break; 2475bdd1243dSDimitry Andric } 2476*5f757f3fSDimitry Andric 2477*5f757f3fSDimitry Andric case CFGElement::CleanupFunction: { 2478*5f757f3fSDimitry Andric const CFGCleanupFunction &CF = BI.castAs<CFGCleanupFunction>(); 2479*5f757f3fSDimitry Andric LocksetBuilder.handleCall(/*Exp=*/nullptr, CF.getFunctionDecl(), 2480*5f757f3fSDimitry Andric SxBuilder.createVariable(CF.getVarDecl()), 2481*5f757f3fSDimitry Andric CF.getVarDecl()->getLocation()); 2482*5f757f3fSDimitry Andric break; 2483*5f757f3fSDimitry Andric } 2484*5f757f3fSDimitry Andric 2485bdd1243dSDimitry Andric case CFGElement::TemporaryDtor: { 2486bdd1243dSDimitry Andric auto TD = BI.castAs<CFGTemporaryDtor>(); 2487bdd1243dSDimitry Andric 2488bdd1243dSDimitry Andric // Clean up constructed object even if there are no attributes to 2489bdd1243dSDimitry Andric // keep the number of objects in limbo as small as possible. 2490*5f757f3fSDimitry Andric if (auto Object = ConstructedObjects.find( 2491bdd1243dSDimitry Andric TD.getBindTemporaryExpr()->getSubExpr()); 2492*5f757f3fSDimitry Andric Object != ConstructedObjects.end()) { 2493bdd1243dSDimitry Andric const auto *DD = TD.getDestructorDecl(AC.getASTContext()); 2494bdd1243dSDimitry Andric if (DD->hasAttrs()) 2495bdd1243dSDimitry Andric // TODO: the location here isn't quite correct. 2496bdd1243dSDimitry Andric LocksetBuilder.handleCall(nullptr, DD, Object->second, 2497bdd1243dSDimitry Andric TD.getBindTemporaryExpr()->getEndLoc()); 2498*5f757f3fSDimitry Andric ConstructedObjects.erase(Object); 2499bdd1243dSDimitry Andric } 25000b57cec5SDimitry Andric break; 25010b57cec5SDimitry Andric } 25020b57cec5SDimitry Andric default: 25030b57cec5SDimitry Andric break; 25040b57cec5SDimitry Andric } 25050b57cec5SDimitry Andric } 25060b57cec5SDimitry Andric CurrBlockInfo->ExitSet = LocksetBuilder.FSet; 25070b57cec5SDimitry Andric 25080b57cec5SDimitry Andric // For every back edge from CurrBlock (the end of the loop) to another block 25090b57cec5SDimitry Andric // (FirstLoopBlock) we need to check that the Lockset of Block is equal to 25100b57cec5SDimitry Andric // the one held at the beginning of FirstLoopBlock. We can look up the 25110b57cec5SDimitry Andric // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map. 25120b57cec5SDimitry Andric for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(), 25130b57cec5SDimitry Andric SE = CurrBlock->succ_end(); SI != SE; ++SI) { 25140b57cec5SDimitry Andric // if CurrBlock -> *SI is *not* a back edge 25150b57cec5SDimitry Andric if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI)) 25160b57cec5SDimitry Andric continue; 25170b57cec5SDimitry Andric 25180b57cec5SDimitry Andric CFGBlock *FirstLoopBlock = *SI; 25190b57cec5SDimitry Andric CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()]; 25200b57cec5SDimitry Andric CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID]; 2521fe6060f1SDimitry Andric intersectAndWarn(PreLoop->EntrySet, LoopEnd->ExitSet, PreLoop->EntryLoc, 2522fe6060f1SDimitry Andric LEK_LockedSomeLoopIterations); 25230b57cec5SDimitry Andric } 25240b57cec5SDimitry Andric } 25250b57cec5SDimitry Andric 25260b57cec5SDimitry Andric // Skip the final check if the exit block is unreachable. 2527*5f757f3fSDimitry Andric if (!Final.Reachable) 25280b57cec5SDimitry Andric return; 25290b57cec5SDimitry Andric 25300b57cec5SDimitry Andric // FIXME: Should we call this function for all blocks which exit the function? 2531*5f757f3fSDimitry Andric intersectAndWarn(ExpectedFunctionExitSet, Final.ExitSet, Final.ExitLoc, 2532fe6060f1SDimitry Andric LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction); 25330b57cec5SDimitry Andric 25340b57cec5SDimitry Andric Handler.leaveFunction(CurrentFunction); 25350b57cec5SDimitry Andric } 25360b57cec5SDimitry Andric 25370b57cec5SDimitry Andric /// Check a function's CFG for thread-safety violations. 25380b57cec5SDimitry Andric /// 25390b57cec5SDimitry Andric /// We traverse the blocks in the CFG, compute the set of mutexes that are held 25400b57cec5SDimitry Andric /// at the end of each block, and issue warnings for thread safety violations. 25410b57cec5SDimitry Andric /// Each block in the CFG is traversed exactly once. 25420b57cec5SDimitry Andric void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC, 25430b57cec5SDimitry Andric ThreadSafetyHandler &Handler, 25440b57cec5SDimitry Andric BeforeSet **BSet) { 25450b57cec5SDimitry Andric if (!*BSet) 25460b57cec5SDimitry Andric *BSet = new BeforeSet; 25470b57cec5SDimitry Andric ThreadSafetyAnalyzer Analyzer(Handler, *BSet); 25480b57cec5SDimitry Andric Analyzer.runAnalysis(AC); 25490b57cec5SDimitry Andric } 25500b57cec5SDimitry Andric 25510b57cec5SDimitry Andric void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; } 25520b57cec5SDimitry Andric 25530b57cec5SDimitry Andric /// Helper function that returns a LockKind required for the given level 25540b57cec5SDimitry Andric /// of access. 25550b57cec5SDimitry Andric LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) { 25560b57cec5SDimitry Andric switch (AK) { 25570b57cec5SDimitry Andric case AK_Read : 25580b57cec5SDimitry Andric return LK_Shared; 25590b57cec5SDimitry Andric case AK_Written : 25600b57cec5SDimitry Andric return LK_Exclusive; 25610b57cec5SDimitry Andric } 25620b57cec5SDimitry Andric llvm_unreachable("Unknown AccessKind"); 25630b57cec5SDimitry Andric } 2564