1bbe25317SEugene Zelenko //===- ThreadSafety.cpp ---------------------------------------------------===//
233208340SCaitlin Sadowski //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
633208340SCaitlin Sadowski //
733208340SCaitlin Sadowski //===----------------------------------------------------------------------===//
833208340SCaitlin Sadowski //
933208340SCaitlin Sadowski // A intra-procedural analysis for thread safety (e.g. deadlocks and race
1033208340SCaitlin Sadowski // conditions), based off of an annotation system.
1133208340SCaitlin Sadowski //
12b2213910SDeLesley Hutchins // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
13fcd5b7e7SAaron Ballman // for more information.
1433208340SCaitlin Sadowski //
1533208340SCaitlin Sadowski //===----------------------------------------------------------------------===//
1633208340SCaitlin Sadowski
179670f847SMehdi Amini #include "clang/Analysis/Analyses/ThreadSafety.h"
18ea70eb30SBenjamin Kramer #include "clang/AST/Attr.h"
19bbe25317SEugene Zelenko #include "clang/AST/Decl.h"
2033208340SCaitlin Sadowski #include "clang/AST/DeclCXX.h"
21bbe25317SEugene Zelenko #include "clang/AST/DeclGroup.h"
22bbe25317SEugene Zelenko #include "clang/AST/Expr.h"
2333208340SCaitlin Sadowski #include "clang/AST/ExprCXX.h"
24bbe25317SEugene Zelenko #include "clang/AST/OperationKinds.h"
25bbe25317SEugene Zelenko #include "clang/AST/Stmt.h"
2633208340SCaitlin Sadowski #include "clang/AST/StmtVisitor.h"
27bbe25317SEugene Zelenko #include "clang/AST/Type.h"
283a02247dSChandler Carruth #include "clang/Analysis/Analyses/PostOrderCFGView.h"
290d9593ddSChandler Carruth #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
30b2213910SDeLesley Hutchins #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
317e615c2fSDeLesley Hutchins #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
32bbe25317SEugene Zelenko #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
3350657f6bSGeorge Karpenkov #include "clang/Analysis/AnalysisDeclContext.h"
343a02247dSChandler Carruth #include "clang/Analysis/CFG.h"
357146b003SAaron Puchert #include "clang/Basic/Builtins.h"
36bbe25317SEugene Zelenko #include "clang/Basic/LLVM.h"
373a8d6cffSDeLesley Hutchins #include "clang/Basic/OperatorKinds.h"
38ea70eb30SBenjamin Kramer #include "clang/Basic/SourceLocation.h"
39bbe25317SEugene Zelenko #include "clang/Basic/Specifiers.h"
40bbe25317SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
41bbe25317SEugene Zelenko #include "llvm/ADT/DenseMap.h"
4233208340SCaitlin Sadowski #include "llvm/ADT/ImmutableMap.h"
43bbe25317SEugene Zelenko #include "llvm/ADT/Optional.h"
44bbe25317SEugene Zelenko #include "llvm/ADT/STLExtras.h"
4533208340SCaitlin Sadowski #include "llvm/ADT/SmallVector.h"
4633208340SCaitlin Sadowski #include "llvm/ADT/StringRef.h"
47bbe25317SEugene Zelenko #include "llvm/Support/Allocator.h"
48bbe25317SEugene Zelenko #include "llvm/Support/Casting.h"
49bbe25317SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
509b7022e5SDeLesley Hutchins #include "llvm/Support/raw_ostream.h"
5133208340SCaitlin Sadowski #include <algorithm>
52bbe25317SEugene Zelenko #include <cassert>
53bbe25317SEugene Zelenko #include <functional>
54bbe25317SEugene Zelenko #include <iterator>
55bbe25317SEugene Zelenko #include <memory>
56bbe25317SEugene Zelenko #include <string>
57bbe25317SEugene Zelenko #include <type_traits>
589b7022e5SDeLesley Hutchins #include <utility>
5933208340SCaitlin Sadowski #include <vector>
60bbe25317SEugene Zelenko
6166a97ee9SBenjamin Kramer using namespace clang;
6266a97ee9SBenjamin Kramer using namespace threadSafety;
6333208340SCaitlin Sadowski
645b34a2fdSCaitlin Sadowski // Key method definition
65bbe25317SEugene Zelenko ThreadSafetyHandler::~ThreadSafetyHandler() = default;
665b34a2fdSCaitlin Sadowski
67c2090511SDeLesley Hutchins /// Issue a warning about an invalid lock expression
warnInvalidLock(ThreadSafetyHandler & Handler,const Expr * MutexExp,const NamedDecl * D,const Expr * DeclExp,StringRef Kind)685df82f21SDeLesley Hutchins static void warnInvalidLock(ThreadSafetyHandler &Handler,
69ea1f8338SDeLesley Hutchins const Expr *MutexExp, const NamedDecl *D,
70ea1f8338SDeLesley Hutchins const Expr *DeclExp, StringRef Kind) {
71c2090511SDeLesley Hutchins SourceLocation Loc;
72c2090511SDeLesley Hutchins if (DeclExp)
73c2090511SDeLesley Hutchins Loc = DeclExp->getExprLoc();
74c2090511SDeLesley Hutchins
75c2090511SDeLesley Hutchins // FIXME: add a note about the attribute location in MutexExp or D
76c2090511SDeLesley Hutchins if (Loc.isValid())
770314dbacSAaron Puchert Handler.handleInvalidLockExp(Loc);
78c2090511SDeLesley Hutchins }
79c2090511SDeLesley Hutchins
80bbe25317SEugene Zelenko namespace {
81bbe25317SEugene Zelenko
8278619430SAaron Puchert /// A set of CapabilityExpr objects, which are compiled from thread safety
8378619430SAaron Puchert /// attributes on a function.
844266522aSDeLesley Hutchins class CapExprSet : public SmallVector<CapabilityExpr, 4> {
8509bcefcbSDeLesley Hutchins public:
869fc8faf9SAdrian Prantl /// Push M onto list, but discard duplicates.
push_back_nodup(const CapabilityExpr & CapE)874266522aSDeLesley Hutchins void push_back_nodup(const CapabilityExpr &CapE) {
884bd46501SKazu Hirata if (llvm::none_of(*this, [=](const CapabilityExpr &CapE2) {
894266522aSDeLesley Hutchins return CapE.equals(CapE2);
904bd46501SKazu Hirata }))
914266522aSDeLesley Hutchins push_back(CapE);
9209bcefcbSDeLesley Hutchins }
9309bcefcbSDeLesley Hutchins };
9409bcefcbSDeLesley Hutchins
95ca988749SEd Schouten class FactManager;
96ca988749SEd Schouten class FactSet;
974266522aSDeLesley Hutchins
989fc8faf9SAdrian Prantl /// This is a helper class that stores a fact that is known at a
994266522aSDeLesley Hutchins /// particular point in program execution. Currently, a fact is a capability,
1004266522aSDeLesley Hutchins /// along with additional information, such as where it was acquired, whether
1014266522aSDeLesley Hutchins /// it is exclusive or shared, etc.
1024266522aSDeLesley Hutchins ///
1031b58759dSAaron Ballman /// FIXME: this analysis does not currently support re-entrant locking.
1044266522aSDeLesley Hutchins class FactEntry : public CapabilityExpr {
105530e074fSAaron Puchert public:
106530e074fSAaron Puchert /// Where a fact comes from.
107530e074fSAaron Puchert enum SourceKind {
108530e074fSAaron Puchert Acquired, ///< The fact has been directly acquired.
109530e074fSAaron Puchert Asserted, ///< The fact has been asserted to be held.
110530e074fSAaron Puchert Declared, ///< The fact is assumed to be held by callers.
111530e074fSAaron Puchert Managed, ///< The fact has been acquired through a scoped capability.
112530e074fSAaron Puchert };
113530e074fSAaron Puchert
1144266522aSDeLesley Hutchins private:
115bbe25317SEugene Zelenko /// Exclusive or shared.
116530e074fSAaron Puchert LockKind LKind : 8;
117530e074fSAaron Puchert
118530e074fSAaron Puchert // How it was acquired.
119530e074fSAaron Puchert SourceKind Source : 8;
120bbe25317SEugene Zelenko
121bbe25317SEugene Zelenko /// Where it was acquired.
122bbe25317SEugene Zelenko SourceLocation AcquireLoc;
123bbe25317SEugene Zelenko
1244266522aSDeLesley Hutchins public:
FactEntry(const CapabilityExpr & CE,LockKind LK,SourceLocation Loc,SourceKind Src)1254266522aSDeLesley Hutchins FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
126530e074fSAaron Puchert SourceKind Src)
127530e074fSAaron Puchert : CapabilityExpr(CE), LKind(LK), Source(Src), AcquireLoc(Loc) {}
128bbe25317SEugene Zelenko virtual ~FactEntry() = default;
12933208340SCaitlin Sadowski
kind() const1304266522aSDeLesley Hutchins LockKind kind() const { return LKind; }
loc() const1314266522aSDeLesley Hutchins SourceLocation loc() const { return AcquireLoc; }
132ab1dc2d5SDeLesley Hutchins
asserted() const133530e074fSAaron Puchert bool asserted() const { return Source == Asserted; }
declared() const134530e074fSAaron Puchert bool declared() const { return Source == Declared; }
managed() const135530e074fSAaron Puchert bool managed() const { return Source == Managed; }
136ca988749SEd Schouten
137ca988749SEd Schouten virtual void
138ca988749SEd Schouten handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
139ca988749SEd Schouten SourceLocation JoinLoc, LockErrorKind LEK,
140ca988749SEd Schouten ThreadSafetyHandler &Handler) const = 0;
141c3e37b75SAaron Puchert virtual void handleLock(FactSet &FSet, FactManager &FactMan,
142f8afb8fdSAaron Puchert const FactEntry &entry,
143f8afb8fdSAaron Puchert ThreadSafetyHandler &Handler) const = 0;
144ca988749SEd Schouten virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
145ca988749SEd Schouten const CapabilityExpr &Cp, SourceLocation UnlockLoc,
146f8afb8fdSAaron Puchert bool FullyRemove,
147f8afb8fdSAaron Puchert ThreadSafetyHandler &Handler) const = 0;
14833208340SCaitlin Sadowski
1494266522aSDeLesley Hutchins // Return true if LKind >= LK, where exclusive > shared
isAtLeast(LockKind LK) const150969f32d5SAaron Puchert bool isAtLeast(LockKind LK) const {
1514266522aSDeLesley Hutchins return (LKind == LK_Exclusive) || (LK == LK_Shared);
152a5a00e83SDeLesley Hutchins }
15333208340SCaitlin Sadowski };
15433208340SCaitlin Sadowski
155bbe25317SEugene Zelenko using FactID = unsigned short;
156c9776faaSDeLesley Hutchins
1579fc8faf9SAdrian Prantl /// FactManager manages the memory for all facts that are created during
158c9776faaSDeLesley Hutchins /// the analysis of a single routine.
159c9776faaSDeLesley Hutchins class FactManager {
160c9776faaSDeLesley Hutchins private:
161969f32d5SAaron Puchert std::vector<std::unique_ptr<const FactEntry>> Facts;
162c9776faaSDeLesley Hutchins
163c9776faaSDeLesley Hutchins public:
newFact(std::unique_ptr<FactEntry> Entry)164ca988749SEd Schouten FactID newFact(std::unique_ptr<FactEntry> Entry) {
165ca988749SEd Schouten Facts.push_back(std::move(Entry));
166c9776faaSDeLesley Hutchins return static_cast<unsigned short>(Facts.size() - 1);
167c9776faaSDeLesley Hutchins }
168c9776faaSDeLesley Hutchins
operator [](FactID F) const169ca988749SEd Schouten const FactEntry &operator[](FactID F) const { return *Facts[F]; }
170c9776faaSDeLesley Hutchins };
171c9776faaSDeLesley Hutchins
1729fc8faf9SAdrian Prantl /// A FactSet is the set of facts that are known to be true at a
173c9776faaSDeLesley Hutchins /// particular program point. FactSets must be small, because they are
174c9776faaSDeLesley Hutchins /// frequently copied, and are thus implemented as a set of indices into a
175c9776faaSDeLesley Hutchins /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
176c9776faaSDeLesley Hutchins /// locks, so we can get away with doing a linear search for lookup. Note
177c9776faaSDeLesley Hutchins /// that a hashtable or map is inappropriate in this case, because lookups
178c9776faaSDeLesley Hutchins /// may involve partial pattern matches, rather than exact matches.
179c9776faaSDeLesley Hutchins class FactSet {
180c9776faaSDeLesley Hutchins private:
181bbe25317SEugene Zelenko using FactVec = SmallVector<FactID, 4>;
182c9776faaSDeLesley Hutchins
183c9776faaSDeLesley Hutchins FactVec FactIDs;
184c9776faaSDeLesley Hutchins
185c9776faaSDeLesley Hutchins public:
186bbe25317SEugene Zelenko using iterator = FactVec::iterator;
187bbe25317SEugene Zelenko using const_iterator = FactVec::const_iterator;
188c9776faaSDeLesley Hutchins
begin()189c9776faaSDeLesley Hutchins iterator begin() { return FactIDs.begin(); }
begin() const190c9776faaSDeLesley Hutchins const_iterator begin() const { return FactIDs.begin(); }
191c9776faaSDeLesley Hutchins
end()192c9776faaSDeLesley Hutchins iterator end() { return FactIDs.end(); }
end() const193c9776faaSDeLesley Hutchins const_iterator end() const { return FactIDs.end(); }
194c9776faaSDeLesley Hutchins
isEmpty() const195c9776faaSDeLesley Hutchins bool isEmpty() const { return FactIDs.size() == 0; }
196c9776faaSDeLesley Hutchins
1973efd0495SDeLesley Hutchins // Return true if the set contains only negative facts
isEmpty(FactManager & FactMan) const1983efd0495SDeLesley Hutchins bool isEmpty(FactManager &FactMan) const {
199bbe25317SEugene Zelenko for (const auto FID : *this) {
2003efd0495SDeLesley Hutchins if (!FactMan[FID].negative())
2013efd0495SDeLesley Hutchins return false;
2023efd0495SDeLesley Hutchins }
2033efd0495SDeLesley Hutchins return true;
2043efd0495SDeLesley Hutchins }
2053efd0495SDeLesley Hutchins
addLockByID(FactID ID)2063efd0495SDeLesley Hutchins void addLockByID(FactID ID) { FactIDs.push_back(ID); }
2073efd0495SDeLesley Hutchins
addLock(FactManager & FM,std::unique_ptr<FactEntry> Entry)208ca988749SEd Schouten FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
209ca988749SEd Schouten FactID F = FM.newFact(std::move(Entry));
210c9776faaSDeLesley Hutchins FactIDs.push_back(F);
211c9776faaSDeLesley Hutchins return F;
212c9776faaSDeLesley Hutchins }
213c9776faaSDeLesley Hutchins
removeLock(FactManager & FM,const CapabilityExpr & CapE)2144266522aSDeLesley Hutchins bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
215c9776faaSDeLesley Hutchins unsigned n = FactIDs.size();
216c9776faaSDeLesley Hutchins if (n == 0)
217c9776faaSDeLesley Hutchins return false;
218c9776faaSDeLesley Hutchins
219c9776faaSDeLesley Hutchins for (unsigned i = 0; i < n-1; ++i) {
2204266522aSDeLesley Hutchins if (FM[FactIDs[i]].matches(CapE)) {
221c9776faaSDeLesley Hutchins FactIDs[i] = FactIDs[n-1];
222c9776faaSDeLesley Hutchins FactIDs.pop_back();
223c9776faaSDeLesley Hutchins return true;
224c9776faaSDeLesley Hutchins }
225c9776faaSDeLesley Hutchins }
2264266522aSDeLesley Hutchins if (FM[FactIDs[n-1]].matches(CapE)) {
227c9776faaSDeLesley Hutchins FactIDs.pop_back();
228c9776faaSDeLesley Hutchins return true;
229c9776faaSDeLesley Hutchins }
230c9776faaSDeLesley Hutchins return false;
231c9776faaSDeLesley Hutchins }
232c9776faaSDeLesley Hutchins
findLockIter(FactManager & FM,const CapabilityExpr & CapE)2334266522aSDeLesley Hutchins iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
23459a72b93SAaron Ballman return std::find_if(begin(), end(), [&](FactID ID) {
2354266522aSDeLesley Hutchins return FM[ID].matches(CapE);
23642f9a8a7SAaron Ballman });
2373b2c66bbSDeLesley Hutchins }
2383b2c66bbSDeLesley Hutchins
findLock(FactManager & FM,const CapabilityExpr & CapE) const239969f32d5SAaron Puchert const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
24059a72b93SAaron Ballman auto I = std::find_if(begin(), end(), [&](FactID ID) {
2414266522aSDeLesley Hutchins return FM[ID].matches(CapE);
24242f9a8a7SAaron Ballman });
2434266522aSDeLesley Hutchins return I != end() ? &FM[*I] : nullptr;
244a5a00e83SDeLesley Hutchins }
245a5a00e83SDeLesley Hutchins
findLockUniv(FactManager & FM,const CapabilityExpr & CapE) const246969f32d5SAaron Puchert const FactEntry *findLockUniv(FactManager &FM,
247969f32d5SAaron Puchert const CapabilityExpr &CapE) const {
24859a72b93SAaron Ballman auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2494266522aSDeLesley Hutchins return FM[ID].matchesUniv(CapE);
25042f9a8a7SAaron Ballman });
2514266522aSDeLesley Hutchins return I != end() ? &FM[*I] : nullptr;
252c9776faaSDeLesley Hutchins }
2535ff1644eSDeLesley Hutchins
findPartialMatch(FactManager & FM,const CapabilityExpr & CapE) const254969f32d5SAaron Puchert const FactEntry *findPartialMatch(FactManager &FM,
2554266522aSDeLesley Hutchins const CapabilityExpr &CapE) const {
256ab1dc2d5SDeLesley Hutchins auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
2574266522aSDeLesley Hutchins return FM[ID].partiallyMatches(CapE);
25842f9a8a7SAaron Ballman });
25942f9a8a7SAaron Ballman return I != end() ? &FM[*I] : nullptr;
2605ff1644eSDeLesley Hutchins }
261ab1dc2d5SDeLesley Hutchins
containsMutexDecl(FactManager & FM,const ValueDecl * Vd) const262ab1dc2d5SDeLesley Hutchins bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
263ab1dc2d5SDeLesley Hutchins auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
264ab1dc2d5SDeLesley Hutchins return FM[ID].valueDecl() == Vd;
265ab1dc2d5SDeLesley Hutchins });
266ab1dc2d5SDeLesley Hutchins return I != end();
267ab1dc2d5SDeLesley Hutchins }
268c9776faaSDeLesley Hutchins };
269c9776faaSDeLesley Hutchins
270ab1dc2d5SDeLesley Hutchins class ThreadSafetyAnalyzer;
271bbe25317SEugene Zelenko
27266a97ee9SBenjamin Kramer } // namespace
273ab1dc2d5SDeLesley Hutchins
27466a97ee9SBenjamin Kramer namespace clang {
27566a97ee9SBenjamin Kramer namespace threadSafety {
276bbe25317SEugene Zelenko
277ab1dc2d5SDeLesley Hutchins class BeforeSet {
278ab1dc2d5SDeLesley Hutchins private:
279bbe25317SEugene Zelenko using BeforeVect = SmallVector<const ValueDecl *, 4>;
280ab1dc2d5SDeLesley Hutchins
281ab1dc2d5SDeLesley Hutchins struct BeforeInfo {
28219ff5602SReid Kleckner BeforeVect Vect;
283bbe25317SEugene Zelenko int Visited = 0;
284bbe25317SEugene Zelenko
285bbe25317SEugene Zelenko BeforeInfo() = default;
286bbe25317SEugene Zelenko BeforeInfo(BeforeInfo &&) = default;
287ab1dc2d5SDeLesley Hutchins };
288ab1dc2d5SDeLesley Hutchins
289bbe25317SEugene Zelenko using BeforeMap =
290bbe25317SEugene Zelenko llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
291bbe25317SEugene Zelenko using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
292ab1dc2d5SDeLesley Hutchins
293ab1dc2d5SDeLesley Hutchins public:
294bbe25317SEugene Zelenko BeforeSet() = default;
295ab1dc2d5SDeLesley Hutchins
296ab1dc2d5SDeLesley Hutchins BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
297ab1dc2d5SDeLesley Hutchins ThreadSafetyAnalyzer& Analyzer);
298ab1dc2d5SDeLesley Hutchins
29919ff5602SReid Kleckner BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
30019ff5602SReid Kleckner ThreadSafetyAnalyzer &Analyzer);
30119ff5602SReid Kleckner
302ab1dc2d5SDeLesley Hutchins void checkBeforeAfter(const ValueDecl* Vd,
303ab1dc2d5SDeLesley Hutchins const FactSet& FSet,
304ab1dc2d5SDeLesley Hutchins ThreadSafetyAnalyzer& Analyzer,
305ab1dc2d5SDeLesley Hutchins SourceLocation Loc, StringRef CapKind);
306ab1dc2d5SDeLesley Hutchins
307ab1dc2d5SDeLesley Hutchins private:
308ab1dc2d5SDeLesley Hutchins BeforeMap BMap;
309ab1dc2d5SDeLesley Hutchins CycleMap CycMap;
310ab1dc2d5SDeLesley Hutchins };
311bbe25317SEugene Zelenko
312bbe25317SEugene Zelenko } // namespace threadSafety
313bbe25317SEugene Zelenko } // namespace clang
314ab1dc2d5SDeLesley Hutchins
31566a97ee9SBenjamin Kramer namespace {
316bbe25317SEugene Zelenko
3179b7022e5SDeLesley Hutchins class LocalVariableMap;
3189b7022e5SDeLesley Hutchins
319bbe25317SEugene Zelenko using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
320bbe25317SEugene Zelenko
32192286678SRichard Smith /// A side (entry or exit) of a CFG node.
32292286678SRichard Smith enum CFGBlockSide { CBS_Entry, CBS_Exit };
3239b7022e5SDeLesley Hutchins
3249b7022e5SDeLesley Hutchins /// CFGBlockInfo is a struct which contains all the information that is
3259b7022e5SDeLesley Hutchins /// maintained for each block in the CFG. See LocalVariableMap for more
3269b7022e5SDeLesley Hutchins /// information about the contexts.
3279b7022e5SDeLesley Hutchins struct CFGBlockInfo {
328bbe25317SEugene Zelenko // Lockset held at entry to block
329bbe25317SEugene Zelenko FactSet EntrySet;
330bbe25317SEugene Zelenko
331bbe25317SEugene Zelenko // Lockset held at exit from block
332bbe25317SEugene Zelenko FactSet ExitSet;
333bbe25317SEugene Zelenko
334bbe25317SEugene Zelenko // Context held at entry to block
335bbe25317SEugene Zelenko LocalVarContext EntryContext;
336bbe25317SEugene Zelenko
337bbe25317SEugene Zelenko // Context held at exit from block
338bbe25317SEugene Zelenko LocalVarContext ExitContext;
339bbe25317SEugene Zelenko
340bbe25317SEugene Zelenko // Location of first statement in block
341bbe25317SEugene Zelenko SourceLocation EntryLoc;
342bbe25317SEugene Zelenko
343bbe25317SEugene Zelenko // Location of last statement in block.
344bbe25317SEugene Zelenko SourceLocation ExitLoc;
345bbe25317SEugene Zelenko
346bbe25317SEugene Zelenko // Used to replay contexts later
347bbe25317SEugene Zelenko unsigned EntryIndex;
348bbe25317SEugene Zelenko
349bbe25317SEugene Zelenko // Is this block reachable?
350bbe25317SEugene Zelenko bool Reachable = false;
3519b7022e5SDeLesley Hutchins
getSet__anon6254f0e10811::CFGBlockInfo352c9776faaSDeLesley Hutchins const FactSet &getSet(CFGBlockSide Side) const {
35392286678SRichard Smith return Side == CBS_Entry ? EntrySet : ExitSet;
35492286678SRichard Smith }
355bbe25317SEugene Zelenko
getLocation__anon6254f0e10811::CFGBlockInfo35692286678SRichard Smith SourceLocation getLocation(CFGBlockSide Side) const {
35792286678SRichard Smith return Side == CBS_Entry ? EntryLoc : ExitLoc;
35892286678SRichard Smith }
35992286678SRichard Smith
3609b7022e5SDeLesley Hutchins private:
CFGBlockInfo__anon6254f0e10811::CFGBlockInfo361c9776faaSDeLesley Hutchins CFGBlockInfo(LocalVarContext EmptyCtx)
362bbe25317SEugene Zelenko : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
3639b7022e5SDeLesley Hutchins
3649b7022e5SDeLesley Hutchins public:
365c9776faaSDeLesley Hutchins static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
3669b7022e5SDeLesley Hutchins };
3679b7022e5SDeLesley Hutchins
3689b7022e5SDeLesley Hutchins // A LocalVariableMap maintains a map from local variables to their currently
3699b7022e5SDeLesley Hutchins // valid definitions. It provides SSA-like functionality when traversing the
3709b7022e5SDeLesley Hutchins // CFG. Like SSA, each definition or assignment to a variable is assigned a
3719b7022e5SDeLesley Hutchins // unique name (an integer), which acts as the SSA name for that definition.
3729b7022e5SDeLesley Hutchins // The total set of names is shared among all CFG basic blocks.
3739b7022e5SDeLesley Hutchins // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
3749b7022e5SDeLesley Hutchins // with their SSA-names. Instead, we compute a Context for each point in the
3759b7022e5SDeLesley Hutchins // code, which maps local variables to the appropriate SSA-name. This map
3769b7022e5SDeLesley Hutchins // changes with each assignment.
3779b7022e5SDeLesley Hutchins //
3789b7022e5SDeLesley Hutchins // The map is computed in a single pass over the CFG. Subsequent analyses can
3799b7022e5SDeLesley Hutchins // then query the map to find the appropriate Context for a statement, and use
3809b7022e5SDeLesley Hutchins // that Context to look up the definitions of variables.
3819b7022e5SDeLesley Hutchins class LocalVariableMap {
3829b7022e5SDeLesley Hutchins public:
383bbe25317SEugene Zelenko using Context = LocalVarContext;
3849b7022e5SDeLesley Hutchins
3859b7022e5SDeLesley Hutchins /// A VarDefinition consists of an expression, representing the value of the
3869b7022e5SDeLesley Hutchins /// variable, along with the context in which that expression should be
3879b7022e5SDeLesley Hutchins /// interpreted. A reference VarDefinition does not itself contain this
3889b7022e5SDeLesley Hutchins /// information, but instead contains a pointer to a previous VarDefinition.
3899b7022e5SDeLesley Hutchins struct VarDefinition {
3909b7022e5SDeLesley Hutchins public:
3919b7022e5SDeLesley Hutchins friend class LocalVariableMap;
3929b7022e5SDeLesley Hutchins
393bbe25317SEugene Zelenko // The original declaration for this variable.
394bbe25317SEugene Zelenko const NamedDecl *Dec;
395bbe25317SEugene Zelenko
396bbe25317SEugene Zelenko // The expression for this variable, OR
397bbe25317SEugene Zelenko const Expr *Exp = nullptr;
398bbe25317SEugene Zelenko
399bbe25317SEugene Zelenko // Reference to another VarDefinition
400bbe25317SEugene Zelenko unsigned Ref = 0;
401bbe25317SEugene Zelenko
402bbe25317SEugene Zelenko // The map with which Exp should be interpreted.
403bbe25317SEugene Zelenko Context Ctx;
4049b7022e5SDeLesley Hutchins
isReference__anon6254f0e10811::LocalVariableMap::VarDefinition4059b7022e5SDeLesley Hutchins bool isReference() { return !Exp; }
4069b7022e5SDeLesley Hutchins
4079b7022e5SDeLesley Hutchins private:
4089b7022e5SDeLesley Hutchins // Create ordinary variable definition
VarDefinition__anon6254f0e10811::LocalVariableMap::VarDefinition4098c9d9579SDeLesley Hutchins VarDefinition(const NamedDecl *D, const Expr *E, Context C)
410bbe25317SEugene Zelenko : Dec(D), Exp(E), Ctx(C) {}
4119b7022e5SDeLesley Hutchins
4129b7022e5SDeLesley Hutchins // Create reference to previous definition
VarDefinition__anon6254f0e10811::LocalVariableMap::VarDefinition4138c9d9579SDeLesley Hutchins VarDefinition(const NamedDecl *D, unsigned R, Context C)
414bbe25317SEugene Zelenko : Dec(D), Ref(R), Ctx(C) {}
4159b7022e5SDeLesley Hutchins };
4169b7022e5SDeLesley Hutchins
4179b7022e5SDeLesley Hutchins private:
4189b7022e5SDeLesley Hutchins Context::Factory ContextFactory;
4199b7022e5SDeLesley Hutchins std::vector<VarDefinition> VarDefinitions;
420cd37c091SAaron Puchert std::vector<std::pair<const Stmt *, Context>> SavedContexts;
4219b7022e5SDeLesley Hutchins
4229b7022e5SDeLesley Hutchins public:
LocalVariableMap()4239b7022e5SDeLesley Hutchins LocalVariableMap() {
4249b7022e5SDeLesley Hutchins // index 0 is a placeholder for undefined variables (aka phi-nodes).
42525542943SCraig Topper VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
4269b7022e5SDeLesley Hutchins }
4279b7022e5SDeLesley Hutchins
4289b7022e5SDeLesley Hutchins /// Look up a definition, within the given context.
lookup(const NamedDecl * D,Context Ctx)4298c9d9579SDeLesley Hutchins const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
4309b7022e5SDeLesley Hutchins const unsigned *i = Ctx.lookup(D);
4319b7022e5SDeLesley Hutchins if (!i)
43225542943SCraig Topper return nullptr;
4339b7022e5SDeLesley Hutchins assert(*i < VarDefinitions.size());
4349b7022e5SDeLesley Hutchins return &VarDefinitions[*i];
4359b7022e5SDeLesley Hutchins }
4369b7022e5SDeLesley Hutchins
4379b7022e5SDeLesley Hutchins /// Look up the definition for D within the given context. Returns
4389d53033dSDeLesley Hutchins /// NULL if the expression is not statically known. If successful, also
4399d53033dSDeLesley Hutchins /// modifies Ctx to hold the context of the return Expr.
lookupExpr(const NamedDecl * D,Context & Ctx)4408c9d9579SDeLesley Hutchins const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
4419b7022e5SDeLesley Hutchins const unsigned *P = Ctx.lookup(D);
4429b7022e5SDeLesley Hutchins if (!P)
44325542943SCraig Topper return nullptr;
4449b7022e5SDeLesley Hutchins
4459b7022e5SDeLesley Hutchins unsigned i = *P;
4469b7022e5SDeLesley Hutchins while (i > 0) {
4479d53033dSDeLesley Hutchins if (VarDefinitions[i].Exp) {
4489d53033dSDeLesley Hutchins Ctx = VarDefinitions[i].Ctx;
4499b7022e5SDeLesley Hutchins return VarDefinitions[i].Exp;
4509d53033dSDeLesley Hutchins }
4519b7022e5SDeLesley Hutchins i = VarDefinitions[i].Ref;
4529b7022e5SDeLesley Hutchins }
45325542943SCraig Topper return nullptr;
4549b7022e5SDeLesley Hutchins }
4559b7022e5SDeLesley Hutchins
getEmptyContext()4569b7022e5SDeLesley Hutchins Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
4579b7022e5SDeLesley Hutchins
4589b7022e5SDeLesley Hutchins /// Return the next context after processing S. This function is used by
4599b7022e5SDeLesley Hutchins /// clients of the class to get the appropriate context when traversing the
4609b7022e5SDeLesley Hutchins /// CFG. It must be called for every assignment or DeclStmt.
getNextContext(unsigned & CtxIndex,const Stmt * S,Context C)461cd37c091SAaron Puchert Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
4629b7022e5SDeLesley Hutchins if (SavedContexts[CtxIndex+1].first == S) {
4639b7022e5SDeLesley Hutchins CtxIndex++;
4649b7022e5SDeLesley Hutchins Context Result = SavedContexts[CtxIndex].second;
4659b7022e5SDeLesley Hutchins return Result;
4669b7022e5SDeLesley Hutchins }
4679b7022e5SDeLesley Hutchins return C;
4689b7022e5SDeLesley Hutchins }
4699b7022e5SDeLesley Hutchins
dumpVarDefinitionName(unsigned i)4709b7022e5SDeLesley Hutchins void dumpVarDefinitionName(unsigned i) {
4719b7022e5SDeLesley Hutchins if (i == 0) {
4729b7022e5SDeLesley Hutchins llvm::errs() << "Undefined";
4739b7022e5SDeLesley Hutchins return;
4749b7022e5SDeLesley Hutchins }
4758c9d9579SDeLesley Hutchins const NamedDecl *Dec = VarDefinitions[i].Dec;
4769b7022e5SDeLesley Hutchins if (!Dec) {
4779b7022e5SDeLesley Hutchins llvm::errs() << "<<NULL>>";
4789b7022e5SDeLesley Hutchins return;
4799b7022e5SDeLesley Hutchins }
4809b7022e5SDeLesley Hutchins Dec->printName(llvm::errs());
481e637711aSRoman Divacky llvm::errs() << "." << i << " " << ((const void*) Dec);
4829b7022e5SDeLesley Hutchins }
4839b7022e5SDeLesley Hutchins
4849b7022e5SDeLesley Hutchins /// Dumps an ASCII representation of the variable map to llvm::errs()
dump()4859b7022e5SDeLesley Hutchins void dump() {
4869b7022e5SDeLesley Hutchins for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
4878c9d9579SDeLesley Hutchins const Expr *Exp = VarDefinitions[i].Exp;
4889b7022e5SDeLesley Hutchins unsigned Ref = VarDefinitions[i].Ref;
4899b7022e5SDeLesley Hutchins
4909b7022e5SDeLesley Hutchins dumpVarDefinitionName(i);
4919b7022e5SDeLesley Hutchins llvm::errs() << " = ";
4929b7022e5SDeLesley Hutchins if (Exp) Exp->dump();
4939b7022e5SDeLesley Hutchins else {
4949b7022e5SDeLesley Hutchins dumpVarDefinitionName(Ref);
4959b7022e5SDeLesley Hutchins llvm::errs() << "\n";
4969b7022e5SDeLesley Hutchins }
4979b7022e5SDeLesley Hutchins }
4989b7022e5SDeLesley Hutchins }
4999b7022e5SDeLesley Hutchins
5009b7022e5SDeLesley Hutchins /// Dumps an ASCII representation of a Context to llvm::errs()
dumpContext(Context C)5019b7022e5SDeLesley Hutchins void dumpContext(Context C) {
5029b7022e5SDeLesley Hutchins for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
5038c9d9579SDeLesley Hutchins const NamedDecl *D = I.getKey();
5049b7022e5SDeLesley Hutchins D->printName(llvm::errs());
5059b7022e5SDeLesley Hutchins const unsigned *i = C.lookup(D);
5069b7022e5SDeLesley Hutchins llvm::errs() << " -> ";
5079b7022e5SDeLesley Hutchins dumpVarDefinitionName(*i);
5089b7022e5SDeLesley Hutchins llvm::errs() << "\n";
5099b7022e5SDeLesley Hutchins }
5109b7022e5SDeLesley Hutchins }
5119b7022e5SDeLesley Hutchins
5129b7022e5SDeLesley Hutchins /// Builds the variable map.
513e80bfcd0SAaron Ballman void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
5149b7022e5SDeLesley Hutchins std::vector<CFGBlockInfo> &BlockInfo);
5159b7022e5SDeLesley Hutchins
5169b7022e5SDeLesley Hutchins protected:
517bbe25317SEugene Zelenko friend class VarMapBuilder;
518bbe25317SEugene Zelenko
5199b7022e5SDeLesley Hutchins // Get the current context index
getContextIndex()5209b7022e5SDeLesley Hutchins unsigned getContextIndex() { return SavedContexts.size()-1; }
5219b7022e5SDeLesley Hutchins
5229b7022e5SDeLesley Hutchins // Save the current context for later replay
saveContext(const Stmt * S,Context C)523cd37c091SAaron Puchert void saveContext(const Stmt *S, Context C) {
5249b7022e5SDeLesley Hutchins SavedContexts.push_back(std::make_pair(S, C));
5259b7022e5SDeLesley Hutchins }
5269b7022e5SDeLesley Hutchins
5279b7022e5SDeLesley Hutchins // Adds a new definition to the given context, and returns a new context.
5289b7022e5SDeLesley Hutchins // This method should be called when declaring a new variable.
addDefinition(const NamedDecl * D,const Expr * Exp,Context Ctx)5299ee54d11SAaron Ballman Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
5309b7022e5SDeLesley Hutchins assert(!Ctx.contains(D));
5319b7022e5SDeLesley Hutchins unsigned newID = VarDefinitions.size();
5329b7022e5SDeLesley Hutchins Context NewCtx = ContextFactory.add(Ctx, D, newID);
5339b7022e5SDeLesley Hutchins VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
5349b7022e5SDeLesley Hutchins return NewCtx;
5359b7022e5SDeLesley Hutchins }
5369b7022e5SDeLesley Hutchins
5379b7022e5SDeLesley Hutchins // Add a new reference to an existing definition.
addReference(const NamedDecl * D,unsigned i,Context Ctx)5388c9d9579SDeLesley Hutchins Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
5399b7022e5SDeLesley Hutchins unsigned newID = VarDefinitions.size();
5409b7022e5SDeLesley Hutchins Context NewCtx = ContextFactory.add(Ctx, D, newID);
5419b7022e5SDeLesley Hutchins VarDefinitions.push_back(VarDefinition(D, i, Ctx));
5429b7022e5SDeLesley Hutchins return NewCtx;
5439b7022e5SDeLesley Hutchins }
5449b7022e5SDeLesley Hutchins
5459b7022e5SDeLesley Hutchins // Updates a definition only if that definition is already in the map.
5469b7022e5SDeLesley Hutchins // This method should be called when assigning to an existing variable.
updateDefinition(const NamedDecl * D,Expr * Exp,Context Ctx)5478c9d9579SDeLesley Hutchins Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
5489b7022e5SDeLesley Hutchins if (Ctx.contains(D)) {
5499b7022e5SDeLesley Hutchins unsigned newID = VarDefinitions.size();
5509b7022e5SDeLesley Hutchins Context NewCtx = ContextFactory.remove(Ctx, D);
5519b7022e5SDeLesley Hutchins NewCtx = ContextFactory.add(NewCtx, D, newID);
5529b7022e5SDeLesley Hutchins VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
5539b7022e5SDeLesley Hutchins return NewCtx;
5549b7022e5SDeLesley Hutchins }
5559b7022e5SDeLesley Hutchins return Ctx;
5569b7022e5SDeLesley Hutchins }
5579b7022e5SDeLesley Hutchins
5589b7022e5SDeLesley Hutchins // Removes a definition from the context, but keeps the variable name
5599b7022e5SDeLesley Hutchins // as a valid variable. The index 0 is a placeholder for cleared definitions.
clearDefinition(const NamedDecl * D,Context Ctx)5608c9d9579SDeLesley Hutchins Context clearDefinition(const NamedDecl *D, Context Ctx) {
5619b7022e5SDeLesley Hutchins Context NewCtx = Ctx;
5629b7022e5SDeLesley Hutchins if (NewCtx.contains(D)) {
5639b7022e5SDeLesley Hutchins NewCtx = ContextFactory.remove(NewCtx, D);
5649b7022e5SDeLesley Hutchins NewCtx = ContextFactory.add(NewCtx, D, 0);
5659b7022e5SDeLesley Hutchins }
5669b7022e5SDeLesley Hutchins return NewCtx;
5679b7022e5SDeLesley Hutchins }
5689b7022e5SDeLesley Hutchins
5699b7022e5SDeLesley Hutchins // Remove a definition entirely frmo the context.
removeDefinition(const NamedDecl * D,Context Ctx)5708c9d9579SDeLesley Hutchins Context removeDefinition(const NamedDecl *D, Context Ctx) {
5719b7022e5SDeLesley Hutchins Context NewCtx = Ctx;
5729b7022e5SDeLesley Hutchins if (NewCtx.contains(D)) {
5739b7022e5SDeLesley Hutchins NewCtx = ContextFactory.remove(NewCtx, D);
5749b7022e5SDeLesley Hutchins }
5759b7022e5SDeLesley Hutchins return NewCtx;
5769b7022e5SDeLesley Hutchins }
5779b7022e5SDeLesley Hutchins
5789b7022e5SDeLesley Hutchins Context intersectContexts(Context C1, Context C2);
5799b7022e5SDeLesley Hutchins Context createReferenceContext(Context C);
5809b7022e5SDeLesley Hutchins void intersectBackEdge(Context C1, Context C2);
5819b7022e5SDeLesley Hutchins };
5829b7022e5SDeLesley Hutchins
583bbe25317SEugene Zelenko } // namespace
5849b7022e5SDeLesley Hutchins
5859b7022e5SDeLesley Hutchins // This has to be defined after LocalVariableMap.
getEmptyBlockInfo(LocalVariableMap & M)586c9776faaSDeLesley Hutchins CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
587c9776faaSDeLesley Hutchins return CFGBlockInfo(M.getEmptyContext());
5889b7022e5SDeLesley Hutchins }
5899b7022e5SDeLesley Hutchins
590bbe25317SEugene Zelenko namespace {
5919b7022e5SDeLesley Hutchins
5929b7022e5SDeLesley Hutchins /// Visitor which builds a LocalVariableMap
593cd37c091SAaron Puchert class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
5949b7022e5SDeLesley Hutchins public:
5959b7022e5SDeLesley Hutchins LocalVariableMap* VMap;
5969b7022e5SDeLesley Hutchins LocalVariableMap::Context Ctx;
5979b7022e5SDeLesley Hutchins
VarMapBuilder(LocalVariableMap * VM,LocalVariableMap::Context C)5989b7022e5SDeLesley Hutchins VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
5999b7022e5SDeLesley Hutchins : VMap(VM), Ctx(C) {}
6009b7022e5SDeLesley Hutchins
601cd37c091SAaron Puchert void VisitDeclStmt(const DeclStmt *S);
602cd37c091SAaron Puchert void VisitBinaryOperator(const BinaryOperator *BO);
6039b7022e5SDeLesley Hutchins };
6049b7022e5SDeLesley Hutchins
605bbe25317SEugene Zelenko } // namespace
6069b7022e5SDeLesley Hutchins
6079b7022e5SDeLesley Hutchins // Add new local variables to the variable map
VisitDeclStmt(const DeclStmt * S)608cd37c091SAaron Puchert void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
6099b7022e5SDeLesley Hutchins bool modifiedCtx = false;
610cd37c091SAaron Puchert const DeclGroupRef DGrp = S->getDeclGroup();
6119ee54d11SAaron Ballman for (const auto *D : DGrp) {
6129ee54d11SAaron Ballman if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
6139ee54d11SAaron Ballman const Expr *E = VD->getInit();
6149b7022e5SDeLesley Hutchins
6159b7022e5SDeLesley Hutchins // Add local variables with trivial type to the variable map
6169b7022e5SDeLesley Hutchins QualType T = VD->getType();
6179b7022e5SDeLesley Hutchins if (T.isTrivialType(VD->getASTContext())) {
6189b7022e5SDeLesley Hutchins Ctx = VMap->addDefinition(VD, E, Ctx);
6199b7022e5SDeLesley Hutchins modifiedCtx = true;
6209b7022e5SDeLesley Hutchins }
6219b7022e5SDeLesley Hutchins }
6229b7022e5SDeLesley Hutchins }
6239b7022e5SDeLesley Hutchins if (modifiedCtx)
6249b7022e5SDeLesley Hutchins VMap->saveContext(S, Ctx);
6259b7022e5SDeLesley Hutchins }
6269b7022e5SDeLesley Hutchins
6279b7022e5SDeLesley Hutchins // Update local variable definitions in variable map
VisitBinaryOperator(const BinaryOperator * BO)628cd37c091SAaron Puchert void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
6299b7022e5SDeLesley Hutchins if (!BO->isAssignmentOp())
6309b7022e5SDeLesley Hutchins return;
6319b7022e5SDeLesley Hutchins
6329b7022e5SDeLesley Hutchins Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
6339b7022e5SDeLesley Hutchins
6349b7022e5SDeLesley Hutchins // Update the variable map and current context.
635bbe25317SEugene Zelenko if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
636bbe25317SEugene Zelenko const ValueDecl *VDec = DRE->getDecl();
6379b7022e5SDeLesley Hutchins if (Ctx.lookup(VDec)) {
6389b7022e5SDeLesley Hutchins if (BO->getOpcode() == BO_Assign)
6399b7022e5SDeLesley Hutchins Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
6409b7022e5SDeLesley Hutchins else
6419b7022e5SDeLesley Hutchins // FIXME -- handle compound assignment operators
6429b7022e5SDeLesley Hutchins Ctx = VMap->clearDefinition(VDec, Ctx);
6439b7022e5SDeLesley Hutchins VMap->saveContext(BO, Ctx);
6449b7022e5SDeLesley Hutchins }
6459b7022e5SDeLesley Hutchins }
6469b7022e5SDeLesley Hutchins }
6479b7022e5SDeLesley Hutchins
6489b7022e5SDeLesley Hutchins // Computes the intersection of two contexts. The intersection is the
6499b7022e5SDeLesley Hutchins // set of variables which have the same definition in both contexts;
6509b7022e5SDeLesley Hutchins // variables with different definitions are discarded.
6519b7022e5SDeLesley Hutchins LocalVariableMap::Context
intersectContexts(Context C1,Context C2)6529b7022e5SDeLesley Hutchins LocalVariableMap::intersectContexts(Context C1, Context C2) {
6539b7022e5SDeLesley Hutchins Context Result = C1;
6549ee54d11SAaron Ballman for (const auto &P : C1) {
6559ee54d11SAaron Ballman const NamedDecl *Dec = P.first;
6569b7022e5SDeLesley Hutchins const unsigned *i2 = C2.lookup(Dec);
6579b7022e5SDeLesley Hutchins if (!i2) // variable doesn't exist on second path
6589b7022e5SDeLesley Hutchins Result = removeDefinition(Dec, Result);
6599ee54d11SAaron Ballman else if (*i2 != P.second) // variable exists, but has different definition
6609b7022e5SDeLesley Hutchins Result = clearDefinition(Dec, Result);
6619b7022e5SDeLesley Hutchins }
6629b7022e5SDeLesley Hutchins return Result;
6639b7022e5SDeLesley Hutchins }
6649b7022e5SDeLesley Hutchins
6659b7022e5SDeLesley Hutchins // For every variable in C, create a new variable that refers to the
6669b7022e5SDeLesley Hutchins // definition in C. Return a new context that contains these new variables.
6679b7022e5SDeLesley Hutchins // (We use this for a naive implementation of SSA on loop back-edges.)
createReferenceContext(Context C)6689b7022e5SDeLesley Hutchins LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
6699b7022e5SDeLesley Hutchins Context Result = getEmptyContext();
6709ee54d11SAaron Ballman for (const auto &P : C)
6719ee54d11SAaron Ballman Result = addReference(P.first, P.second, Result);
6729b7022e5SDeLesley Hutchins return Result;
6739b7022e5SDeLesley Hutchins }
6749b7022e5SDeLesley Hutchins
6759b7022e5SDeLesley Hutchins // This routine also takes the intersection of C1 and C2, but it does so by
6769b7022e5SDeLesley Hutchins // altering the VarDefinitions. C1 must be the result of an earlier call to
6779b7022e5SDeLesley Hutchins // createReferenceContext.
intersectBackEdge(Context C1,Context C2)6789b7022e5SDeLesley Hutchins void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
6799ee54d11SAaron Ballman for (const auto &P : C1) {
6809ee54d11SAaron Ballman unsigned i1 = P.second;
6819b7022e5SDeLesley Hutchins VarDefinition *VDef = &VarDefinitions[i1];
6829b7022e5SDeLesley Hutchins assert(VDef->isReference());
6839b7022e5SDeLesley Hutchins
6849ee54d11SAaron Ballman const unsigned *i2 = C2.lookup(P.first);
6859b7022e5SDeLesley Hutchins if (!i2 || (*i2 != i1))
6869b7022e5SDeLesley Hutchins VDef->Ref = 0; // Mark this variable as undefined
6879b7022e5SDeLesley Hutchins }
6889b7022e5SDeLesley Hutchins }
6899b7022e5SDeLesley Hutchins
6909b7022e5SDeLesley Hutchins // Traverse the CFG in topological order, so all predecessors of a block
6919b7022e5SDeLesley Hutchins // (excluding back-edges) are visited before the block itself. At
6929b7022e5SDeLesley Hutchins // each point in the code, we calculate a Context, which holds the set of
6939b7022e5SDeLesley Hutchins // variable definitions which are visible at that point in execution.
6949b7022e5SDeLesley Hutchins // Visible variables are mapped to their definitions using an array that
6959b7022e5SDeLesley Hutchins // contains all definitions.
6969b7022e5SDeLesley Hutchins //
6979b7022e5SDeLesley Hutchins // At join points in the CFG, the set is computed as the intersection of
6989b7022e5SDeLesley Hutchins // the incoming sets along each edge, E.g.
6999b7022e5SDeLesley Hutchins //
7009b7022e5SDeLesley Hutchins // { Context | VarDefinitions }
7019b7022e5SDeLesley Hutchins // int x = 0; { x -> x1 | x1 = 0 }
7029b7022e5SDeLesley Hutchins // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
7039b7022e5SDeLesley Hutchins // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
7049b7022e5SDeLesley Hutchins // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
7059b7022e5SDeLesley Hutchins // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
7069b7022e5SDeLesley Hutchins //
7079b7022e5SDeLesley Hutchins // This is essentially a simpler and more naive version of the standard SSA
7089b7022e5SDeLesley Hutchins // algorithm. Those definitions that remain in the intersection are from blocks
7099b7022e5SDeLesley Hutchins // that strictly dominate the current block. We do not bother to insert proper
7109b7022e5SDeLesley Hutchins // phi nodes, because they are not used in our analysis; instead, wherever
7119b7022e5SDeLesley Hutchins // a phi node would be required, we simply remove that definition from the
7129b7022e5SDeLesley Hutchins // context (E.g. x above).
7139b7022e5SDeLesley Hutchins //
7149b7022e5SDeLesley Hutchins // The initial traversal does not capture back-edges, so those need to be
7159b7022e5SDeLesley Hutchins // handled on a separate pass. Whenever the first pass encounters an
7169b7022e5SDeLesley Hutchins // incoming back edge, it duplicates the context, creating new definitions
7179b7022e5SDeLesley Hutchins // that refer back to the originals. (These correspond to places where SSA
7189b7022e5SDeLesley Hutchins // might have to insert a phi node.) On the second pass, these definitions are
719830885caSSylvestre Ledru // set to NULL if the variable has changed on the back-edge (i.e. a phi
7209b7022e5SDeLesley Hutchins // node was actually required.) E.g.
7219b7022e5SDeLesley Hutchins //
7229b7022e5SDeLesley Hutchins // { Context | VarDefinitions }
7239b7022e5SDeLesley Hutchins // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
7249b7022e5SDeLesley Hutchins // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
7259b7022e5SDeLesley Hutchins // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
7269b7022e5SDeLesley Hutchins // ... { y -> y1 | x3 = 2, x2 = 1, ... }
traverseCFG(CFG * CFGraph,const PostOrderCFGView * SortedGraph,std::vector<CFGBlockInfo> & BlockInfo)7279b7022e5SDeLesley Hutchins void LocalVariableMap::traverseCFG(CFG *CFGraph,
728e80bfcd0SAaron Ballman const PostOrderCFGView *SortedGraph,
7299b7022e5SDeLesley Hutchins std::vector<CFGBlockInfo> &BlockInfo) {
7309b7022e5SDeLesley Hutchins PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
7319b7022e5SDeLesley Hutchins
732e80bfcd0SAaron Ballman for (const auto *CurrBlock : *SortedGraph) {
73388d85365SAaron Puchert unsigned CurrBlockID = CurrBlock->getBlockID();
7349b7022e5SDeLesley Hutchins CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
7359b7022e5SDeLesley Hutchins
7369b7022e5SDeLesley Hutchins VisitedBlocks.insert(CurrBlock);
7379b7022e5SDeLesley Hutchins
7389b7022e5SDeLesley Hutchins // Calculate the entry context for the current block
7399b7022e5SDeLesley Hutchins bool HasBackEdges = false;
7409b7022e5SDeLesley Hutchins bool CtxInit = true;
7419b7022e5SDeLesley Hutchins for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
7429b7022e5SDeLesley Hutchins PE = CurrBlock->pred_end(); PI != PE; ++PI) {
7439b7022e5SDeLesley Hutchins // if *PI -> CurrBlock is a back edge, so skip it
74425542943SCraig Topper if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
7459b7022e5SDeLesley Hutchins HasBackEdges = true;
7469b7022e5SDeLesley Hutchins continue;
7479b7022e5SDeLesley Hutchins }
7489b7022e5SDeLesley Hutchins
74988d85365SAaron Puchert unsigned PrevBlockID = (*PI)->getBlockID();
7509b7022e5SDeLesley Hutchins CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
7519b7022e5SDeLesley Hutchins
7529b7022e5SDeLesley Hutchins if (CtxInit) {
7539b7022e5SDeLesley Hutchins CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
7549b7022e5SDeLesley Hutchins CtxInit = false;
7559b7022e5SDeLesley Hutchins }
7569b7022e5SDeLesley Hutchins else {
7579b7022e5SDeLesley Hutchins CurrBlockInfo->EntryContext =
7589b7022e5SDeLesley Hutchins intersectContexts(CurrBlockInfo->EntryContext,
7599b7022e5SDeLesley Hutchins PrevBlockInfo->ExitContext);
7609b7022e5SDeLesley Hutchins }
7619b7022e5SDeLesley Hutchins }
7629b7022e5SDeLesley Hutchins
7639b7022e5SDeLesley Hutchins // Duplicate the context if we have back-edges, so we can call
7649b7022e5SDeLesley Hutchins // intersectBackEdges later.
7659b7022e5SDeLesley Hutchins if (HasBackEdges)
7669b7022e5SDeLesley Hutchins CurrBlockInfo->EntryContext =
7679b7022e5SDeLesley Hutchins createReferenceContext(CurrBlockInfo->EntryContext);
7689b7022e5SDeLesley Hutchins
7699b7022e5SDeLesley Hutchins // Create a starting context index for the current block
77025542943SCraig Topper saveContext(nullptr, CurrBlockInfo->EntryContext);
7719b7022e5SDeLesley Hutchins CurrBlockInfo->EntryIndex = getContextIndex();
7729b7022e5SDeLesley Hutchins
7739b7022e5SDeLesley Hutchins // Visit all the statements in the basic block.
7749b7022e5SDeLesley Hutchins VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
775bbe25317SEugene Zelenko for (const auto &BI : *CurrBlock) {
776bbe25317SEugene Zelenko switch (BI.getKind()) {
7779b7022e5SDeLesley Hutchins case CFGElement::Statement: {
778bbe25317SEugene Zelenko CFGStmt CS = BI.castAs<CFGStmt>();
779cd37c091SAaron Puchert VMapBuilder.Visit(CS.getStmt());
7809b7022e5SDeLesley Hutchins break;
7819b7022e5SDeLesley Hutchins }
7829b7022e5SDeLesley Hutchins default:
7839b7022e5SDeLesley Hutchins break;
7849b7022e5SDeLesley Hutchins }
7859b7022e5SDeLesley Hutchins }
7869b7022e5SDeLesley Hutchins CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
7879b7022e5SDeLesley Hutchins
7889b7022e5SDeLesley Hutchins // Mark variables on back edges as "unknown" if they've been changed.
7899b7022e5SDeLesley Hutchins for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
7909b7022e5SDeLesley Hutchins SE = CurrBlock->succ_end(); SI != SE; ++SI) {
7919b7022e5SDeLesley Hutchins // if CurrBlock -> *SI is *not* a back edge
79225542943SCraig Topper if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
7939b7022e5SDeLesley Hutchins continue;
7949b7022e5SDeLesley Hutchins
7959b7022e5SDeLesley Hutchins CFGBlock *FirstLoopBlock = *SI;
7969b7022e5SDeLesley Hutchins Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
7979b7022e5SDeLesley Hutchins Context LoopEnd = CurrBlockInfo->ExitContext;
7989b7022e5SDeLesley Hutchins intersectBackEdge(LoopBegin, LoopEnd);
7999b7022e5SDeLesley Hutchins }
8009b7022e5SDeLesley Hutchins }
8019b7022e5SDeLesley Hutchins
8029b7022e5SDeLesley Hutchins // Put an extra entry at the end of the indexed context array
8039b7022e5SDeLesley Hutchins unsigned exitID = CFGraph->getExit().getBlockID();
80425542943SCraig Topper saveContext(nullptr, BlockInfo[exitID].ExitContext);
8059b7022e5SDeLesley Hutchins }
8069b7022e5SDeLesley Hutchins
80792286678SRichard Smith /// Find the appropriate source locations to use when producing diagnostics for
80892286678SRichard Smith /// each block in the CFG.
findBlockLocations(CFG * CFGraph,const PostOrderCFGView * SortedGraph,std::vector<CFGBlockInfo> & BlockInfo)80992286678SRichard Smith static void findBlockLocations(CFG *CFGraph,
810e80bfcd0SAaron Ballman const PostOrderCFGView *SortedGraph,
81192286678SRichard Smith std::vector<CFGBlockInfo> &BlockInfo) {
812e80bfcd0SAaron Ballman for (const auto *CurrBlock : *SortedGraph) {
81392286678SRichard Smith CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
81492286678SRichard Smith
81592286678SRichard Smith // Find the source location of the last statement in the block, if the
81692286678SRichard Smith // block is not empty.
8174e53032dSArtem Dergachev if (const Stmt *S = CurrBlock->getTerminatorStmt()) {
818f2ceec48SStephen Kelly CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
81992286678SRichard Smith } else {
82092286678SRichard Smith for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
82192286678SRichard Smith BE = CurrBlock->rend(); BI != BE; ++BI) {
82292286678SRichard Smith // FIXME: Handle other CFGElement kinds.
82300be69abSDavid Blaikie if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
824f2ceec48SStephen Kelly CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
82592286678SRichard Smith break;
82692286678SRichard Smith }
82792286678SRichard Smith }
82892286678SRichard Smith }
82992286678SRichard Smith
830ed1fe5d0SYaron Keren if (CurrBlockInfo->ExitLoc.isValid()) {
83192286678SRichard Smith // This block contains at least one statement. Find the source location
83292286678SRichard Smith // of the first statement in the block.
833bbe25317SEugene Zelenko for (const auto &BI : *CurrBlock) {
83492286678SRichard Smith // FIXME: Handle other CFGElement kinds.
835bbe25317SEugene Zelenko if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
836f2ceec48SStephen Kelly CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
83792286678SRichard Smith break;
83892286678SRichard Smith }
83992286678SRichard Smith }
84092286678SRichard Smith } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
84192286678SRichard Smith CurrBlock != &CFGraph->getExit()) {
84292286678SRichard Smith // The block is empty, and has a single predecessor. Use its exit
84392286678SRichard Smith // location.
84492286678SRichard Smith CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
84592286678SRichard Smith BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
8466de19ea4SAaron Puchert } else if (CurrBlock->succ_size() == 1 && *CurrBlock->succ_begin()) {
8476de19ea4SAaron Puchert // The block is empty, and has a single successor. Use its entry
8486de19ea4SAaron Puchert // location.
8496de19ea4SAaron Puchert CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
8506de19ea4SAaron Puchert BlockInfo[(*CurrBlock->succ_begin())->getBlockID()].EntryLoc;
85192286678SRichard Smith }
85292286678SRichard Smith }
85392286678SRichard Smith }
8549b7022e5SDeLesley Hutchins
855bbe25317SEugene Zelenko namespace {
856bbe25317SEugene Zelenko
857ca988749SEd Schouten class LockableFactEntry : public FactEntry {
858ca988749SEd Schouten public:
LockableFactEntry(const CapabilityExpr & CE,LockKind LK,SourceLocation Loc,SourceKind Src=Acquired)859ca988749SEd Schouten LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
860530e074fSAaron Puchert SourceKind Src = Acquired)
861530e074fSAaron Puchert : FactEntry(CE, LK, Loc, Src) {}
862ca988749SEd Schouten
863ca988749SEd Schouten void
handleRemovalFromIntersection(const FactSet & FSet,FactManager & FactMan,SourceLocation JoinLoc,LockErrorKind LEK,ThreadSafetyHandler & Handler) const864ca988749SEd Schouten handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
865ca988749SEd Schouten SourceLocation JoinLoc, LockErrorKind LEK,
866ca988749SEd Schouten ThreadSafetyHandler &Handler) const override {
867f664e2ecSAaron Puchert if (!asserted() && !negative() && !isUniversal()) {
868f8afb8fdSAaron Puchert Handler.handleMutexHeldEndOfScope(getKind(), toString(), loc(), JoinLoc,
869ca988749SEd Schouten LEK);
870ca988749SEd Schouten }
871ca988749SEd Schouten }
872ca988749SEd Schouten
handleLock(FactSet & FSet,FactManager & FactMan,const FactEntry & entry,ThreadSafetyHandler & Handler) const873c3e37b75SAaron Puchert void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
874f8afb8fdSAaron Puchert ThreadSafetyHandler &Handler) const override {
875f8afb8fdSAaron Puchert Handler.handleDoubleLock(entry.getKind(), entry.toString(), loc(),
876f8afb8fdSAaron Puchert entry.loc());
877c3e37b75SAaron Puchert }
878c3e37b75SAaron Puchert
handleUnlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,ThreadSafetyHandler & Handler) const879ca988749SEd Schouten void handleUnlock(FactSet &FSet, FactManager &FactMan,
880ca988749SEd Schouten const CapabilityExpr &Cp, SourceLocation UnlockLoc,
881f8afb8fdSAaron Puchert bool FullyRemove,
882f8afb8fdSAaron Puchert ThreadSafetyHandler &Handler) const override {
883ca988749SEd Schouten FSet.removeLock(FactMan, Cp);
884ca988749SEd Schouten if (!Cp.negative()) {
8852b3d49b6SJonas Devlieghere FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
886ca988749SEd Schouten !Cp, LK_Exclusive, UnlockLoc));
887ca988749SEd Schouten }
888ca988749SEd Schouten }
889ca988749SEd Schouten };
890ca988749SEd Schouten
891ca988749SEd Schouten class ScopedLockableFactEntry : public FactEntry {
892ca988749SEd Schouten private:
8936a68efc9SAaron Puchert enum UnderlyingCapabilityKind {
8946a68efc9SAaron Puchert UCK_Acquired, ///< Any kind of acquired capability.
8956a68efc9SAaron Puchert UCK_ReleasedShared, ///< Shared capability that was released.
8966a68efc9SAaron Puchert UCK_ReleasedExclusive, ///< Exclusive capability that was released.
8976a68efc9SAaron Puchert };
8986a68efc9SAaron Puchert
899d65c9224SAaron Puchert struct UnderlyingCapability {
900d65c9224SAaron Puchert CapabilityExpr Cap;
901d65c9224SAaron Puchert UnderlyingCapabilityKind Kind;
902d65c9224SAaron Puchert };
9036a68efc9SAaron Puchert
904d65c9224SAaron Puchert SmallVector<UnderlyingCapability, 2> UnderlyingMutexes;
905ca988749SEd Schouten
906ca988749SEd Schouten public:
ScopedLockableFactEntry(const CapabilityExpr & CE,SourceLocation Loc)9071386b59bSAaron Puchert ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc)
908530e074fSAaron Puchert : FactEntry(CE, LK_Exclusive, Loc, Acquired) {}
9091386b59bSAaron Puchert
addLock(const CapabilityExpr & M)9101850f56cSAaron Puchert void addLock(const CapabilityExpr &M) {
911d65c9224SAaron Puchert UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_Acquired});
9121386b59bSAaron Puchert }
9131386b59bSAaron Puchert
addExclusiveUnlock(const CapabilityExpr & M)9141386b59bSAaron Puchert void addExclusiveUnlock(const CapabilityExpr &M) {
915d65c9224SAaron Puchert UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedExclusive});
9161386b59bSAaron Puchert }
9171386b59bSAaron Puchert
addSharedUnlock(const CapabilityExpr & M)9181386b59bSAaron Puchert void addSharedUnlock(const CapabilityExpr &M) {
919d65c9224SAaron Puchert UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedShared});
920ca988749SEd Schouten }
921ca988749SEd Schouten
922ca988749SEd Schouten void
handleRemovalFromIntersection(const FactSet & FSet,FactManager & FactMan,SourceLocation JoinLoc,LockErrorKind LEK,ThreadSafetyHandler & Handler) const923ca988749SEd Schouten handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
924ca988749SEd Schouten SourceLocation JoinLoc, LockErrorKind LEK,
925ca988749SEd Schouten ThreadSafetyHandler &Handler) const override {
9266a68efc9SAaron Puchert for (const auto &UnderlyingMutex : UnderlyingMutexes) {
927d65c9224SAaron Puchert const auto *Entry = FSet.findLock(FactMan, UnderlyingMutex.Cap);
928d65c9224SAaron Puchert if ((UnderlyingMutex.Kind == UCK_Acquired && Entry) ||
929d65c9224SAaron Puchert (UnderlyingMutex.Kind != UCK_Acquired && !Entry)) {
930ca988749SEd Schouten // If this scoped lock manages another mutex, and if the underlying
9316a68efc9SAaron Puchert // mutex is still/not held, then warn about the underlying mutex.
932f8afb8fdSAaron Puchert Handler.handleMutexHeldEndOfScope(UnderlyingMutex.Cap.getKind(),
933f8afb8fdSAaron Puchert UnderlyingMutex.Cap.toString(), loc(),
934f8afb8fdSAaron Puchert JoinLoc, LEK);
935ca988749SEd Schouten }
936ca988749SEd Schouten }
937ca988749SEd Schouten }
938ca988749SEd Schouten
handleLock(FactSet & FSet,FactManager & FactMan,const FactEntry & entry,ThreadSafetyHandler & Handler) const939c3e37b75SAaron Puchert void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
940f8afb8fdSAaron Puchert ThreadSafetyHandler &Handler) const override {
9416a68efc9SAaron Puchert for (const auto &UnderlyingMutex : UnderlyingMutexes) {
942d65c9224SAaron Puchert if (UnderlyingMutex.Kind == UCK_Acquired)
943d65c9224SAaron Puchert lock(FSet, FactMan, UnderlyingMutex.Cap, entry.kind(), entry.loc(),
944f8afb8fdSAaron Puchert &Handler);
9456a68efc9SAaron Puchert else
946f8afb8fdSAaron Puchert unlock(FSet, FactMan, UnderlyingMutex.Cap, entry.loc(), &Handler);
947c3e37b75SAaron Puchert }
948c3e37b75SAaron Puchert }
949c3e37b75SAaron Puchert
handleUnlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,ThreadSafetyHandler & Handler) const950ca988749SEd Schouten void handleUnlock(FactSet &FSet, FactManager &FactMan,
951ca988749SEd Schouten const CapabilityExpr &Cp, SourceLocation UnlockLoc,
952f8afb8fdSAaron Puchert bool FullyRemove,
953f8afb8fdSAaron Puchert ThreadSafetyHandler &Handler) const override {
954ca988749SEd Schouten assert(!Cp.negative() && "Managing object cannot be negative.");
9556a68efc9SAaron Puchert for (const auto &UnderlyingMutex : UnderlyingMutexes) {
9566a68efc9SAaron Puchert // Remove/lock the underlying mutex if it exists/is still unlocked; warn
9576a68efc9SAaron Puchert // on double unlocking/locking if we're not destroying the scoped object.
9586a68efc9SAaron Puchert ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler;
959d65c9224SAaron Puchert if (UnderlyingMutex.Kind == UCK_Acquired) {
960f8afb8fdSAaron Puchert unlock(FSet, FactMan, UnderlyingMutex.Cap, UnlockLoc, TSHandler);
961ca988749SEd Schouten } else {
962d65c9224SAaron Puchert LockKind kind = UnderlyingMutex.Kind == UCK_ReleasedShared
9636a68efc9SAaron Puchert ? LK_Shared
9646a68efc9SAaron Puchert : LK_Exclusive;
965f8afb8fdSAaron Puchert lock(FSet, FactMan, UnderlyingMutex.Cap, kind, UnlockLoc, TSHandler);
966ca988749SEd Schouten }
967ca988749SEd Schouten }
968ca988749SEd Schouten if (FullyRemove)
969ca988749SEd Schouten FSet.removeLock(FactMan, Cp);
970ca988749SEd Schouten }
9716a68efc9SAaron Puchert
9726a68efc9SAaron Puchert private:
lock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,LockKind kind,SourceLocation loc,ThreadSafetyHandler * Handler) const9736a68efc9SAaron Puchert void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
974f8afb8fdSAaron Puchert LockKind kind, SourceLocation loc,
975f8afb8fdSAaron Puchert ThreadSafetyHandler *Handler) const {
976ffa1d6adSAaron Puchert if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
977ffa1d6adSAaron Puchert if (Handler)
978f8afb8fdSAaron Puchert Handler->handleDoubleLock(Cp.getKind(), Cp.toString(), Fact->loc(),
979f8afb8fdSAaron Puchert loc);
980ffa1d6adSAaron Puchert } else {
9816a68efc9SAaron Puchert FSet.removeLock(FactMan, !Cp);
9826a68efc9SAaron Puchert FSet.addLock(FactMan,
983530e074fSAaron Puchert std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed));
9846a68efc9SAaron Puchert }
9856a68efc9SAaron Puchert }
9866a68efc9SAaron Puchert
unlock(FactSet & FSet,FactManager & FactMan,const CapabilityExpr & Cp,SourceLocation loc,ThreadSafetyHandler * Handler) const9876a68efc9SAaron Puchert void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
988f8afb8fdSAaron Puchert SourceLocation loc, ThreadSafetyHandler *Handler) const {
9896a68efc9SAaron Puchert if (FSet.findLock(FactMan, Cp)) {
9906a68efc9SAaron Puchert FSet.removeLock(FactMan, Cp);
9912b3d49b6SJonas Devlieghere FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
9926a68efc9SAaron Puchert !Cp, LK_Exclusive, loc));
9936a68efc9SAaron Puchert } else if (Handler) {
994f70912f8SAaron Puchert SourceLocation PrevLoc;
995f70912f8SAaron Puchert if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
996f70912f8SAaron Puchert PrevLoc = Neg->loc();
997f8afb8fdSAaron Puchert Handler->handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), loc, PrevLoc);
9986a68efc9SAaron Puchert }
9996a68efc9SAaron Puchert }
1000ca988749SEd Schouten };
1001ca988749SEd Schouten
10029fc8faf9SAdrian Prantl /// Class which implements the core thread safety analysis routines.
10039b7022e5SDeLesley Hutchins class ThreadSafetyAnalyzer {
10049b7022e5SDeLesley Hutchins friend class BuildLockset;
100566a97ee9SBenjamin Kramer friend class threadSafety::BeforeSet;
10069b7022e5SDeLesley Hutchins
1007ea1f8338SDeLesley Hutchins llvm::BumpPtrAllocator Bpa;
1008ea1f8338SDeLesley Hutchins threadSafety::til::MemRegionRef Arena;
1009ea1f8338SDeLesley Hutchins threadSafety::SExprBuilder SxBuilder;
1010ea1f8338SDeLesley Hutchins
10119b7022e5SDeLesley Hutchins ThreadSafetyHandler &Handler;
10124266522aSDeLesley Hutchins const CXXMethodDecl *CurrentMethod;
10139b7022e5SDeLesley Hutchins LocalVariableMap LocalVarMap;
1014c9776faaSDeLesley Hutchins FactManager FactMan;
10158c9d9579SDeLesley Hutchins std::vector<CFGBlockInfo> BlockInfo;
10169b7022e5SDeLesley Hutchins
1017ab1dc2d5SDeLesley Hutchins BeforeSet *GlobalBeforeSet;
1018ab1dc2d5SDeLesley Hutchins
10199b7022e5SDeLesley Hutchins public:
ThreadSafetyAnalyzer(ThreadSafetyHandler & H,BeforeSet * Bset)1020ab1dc2d5SDeLesley Hutchins ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
1021ab1dc2d5SDeLesley Hutchins : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
10229b7022e5SDeLesley Hutchins
10233efd0495SDeLesley Hutchins bool inCurrentScope(const CapabilityExpr &CapE);
10243efd0495SDeLesley Hutchins
1025ca988749SEd Schouten void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
1026f8afb8fdSAaron Puchert bool ReqAttr = false);
10274266522aSDeLesley Hutchins void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
1028f8afb8fdSAaron Puchert SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind);
102909bcefcbSDeLesley Hutchins
103009bcefcbSDeLesley Hutchins template <typename AttrType>
103168c7fcdaSAaron Puchert void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
103225542943SCraig Topper const NamedDecl *D, VarDecl *SelfDecl = nullptr);
10338c9d9579SDeLesley Hutchins
10348c9d9579SDeLesley Hutchins template <class AttrType>
103568c7fcdaSAaron Puchert void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
103609bcefcbSDeLesley Hutchins const NamedDecl *D,
10378c9d9579SDeLesley Hutchins const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
10388c9d9579SDeLesley Hutchins Expr *BrE, bool Neg);
103909bcefcbSDeLesley Hutchins
10408c9d9579SDeLesley Hutchins const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
10418c9d9579SDeLesley Hutchins bool &Negate);
1042ebbf7701SDeLesley Hutchins
1043c9776faaSDeLesley Hutchins void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
10448c9d9579SDeLesley Hutchins const CFGBlock* PredBlock,
10458c9d9579SDeLesley Hutchins const CFGBlock *CurrBlock);
10468c9d9579SDeLesley Hutchins
10479b889f82SAaron Puchert bool join(const FactEntry &a, const FactEntry &b, bool CanModify);
10483d64677cSAaron Puchert
1049e0b90771SAaron Puchert void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet,
1050e0b90771SAaron Puchert SourceLocation JoinLoc, LockErrorKind EntryLEK,
1051e0b90771SAaron Puchert LockErrorKind ExitLEK);
10526e6dbb76SDeLesley Hutchins
intersectAndWarn(FactSet & EntrySet,const FactSet & ExitSet,SourceLocation JoinLoc,LockErrorKind LEK)1053e0b90771SAaron Puchert void intersectAndWarn(FactSet &EntrySet, const FactSet &ExitSet,
1054e0b90771SAaron Puchert SourceLocation JoinLoc, LockErrorKind LEK) {
1055e0b90771SAaron Puchert intersectAndWarn(EntrySet, ExitSet, JoinLoc, LEK, LEK);
10566e6dbb76SDeLesley Hutchins }
10579b7022e5SDeLesley Hutchins
10589b7022e5SDeLesley Hutchins void runAnalysis(AnalysisDeclContext &AC);
10599b7022e5SDeLesley Hutchins };
1060bbe25317SEugene Zelenko
106166a97ee9SBenjamin Kramer } // namespace
1062ab1dc2d5SDeLesley Hutchins
1063ab1dc2d5SDeLesley Hutchins /// Process acquired_before and acquired_after attributes on Vd.
insertAttrExprs(const ValueDecl * Vd,ThreadSafetyAnalyzer & Analyzer)1064ab1dc2d5SDeLesley Hutchins BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1065ab1dc2d5SDeLesley Hutchins ThreadSafetyAnalyzer& Analyzer) {
1066ab1dc2d5SDeLesley Hutchins // Create a new entry for Vd.
106719ff5602SReid Kleckner BeforeInfo *Info = nullptr;
106819ff5602SReid Kleckner {
106919ff5602SReid Kleckner // Keep InfoPtr in its own scope in case BMap is modified later and the
107019ff5602SReid Kleckner // reference becomes invalid.
107119ff5602SReid Kleckner std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
107219ff5602SReid Kleckner if (!InfoPtr)
107319ff5602SReid Kleckner InfoPtr.reset(new BeforeInfo());
107419ff5602SReid Kleckner Info = InfoPtr.get();
107519ff5602SReid Kleckner }
1076ab1dc2d5SDeLesley Hutchins
1077bbe25317SEugene Zelenko for (const auto *At : Vd->attrs()) {
1078ab1dc2d5SDeLesley Hutchins switch (At->getKind()) {
1079ab1dc2d5SDeLesley Hutchins case attr::AcquiredBefore: {
1080bbe25317SEugene Zelenko const auto *A = cast<AcquiredBeforeAttr>(At);
1081ab1dc2d5SDeLesley Hutchins
1082ab1dc2d5SDeLesley Hutchins // Read exprs from the attribute, and add them to BeforeVect.
1083ab1dc2d5SDeLesley Hutchins for (const auto *Arg : A->args()) {
1084ab1dc2d5SDeLesley Hutchins CapabilityExpr Cp =
1085ab1dc2d5SDeLesley Hutchins Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1086ab1dc2d5SDeLesley Hutchins if (const ValueDecl *Cpvd = Cp.valueDecl()) {
108719ff5602SReid Kleckner Info->Vect.push_back(Cpvd);
1088bbe25317SEugene Zelenko const auto It = BMap.find(Cpvd);
1089ab1dc2d5SDeLesley Hutchins if (It == BMap.end())
1090ab1dc2d5SDeLesley Hutchins insertAttrExprs(Cpvd, Analyzer);
1091ab1dc2d5SDeLesley Hutchins }
1092ab1dc2d5SDeLesley Hutchins }
1093ab1dc2d5SDeLesley Hutchins break;
1094ab1dc2d5SDeLesley Hutchins }
1095ab1dc2d5SDeLesley Hutchins case attr::AcquiredAfter: {
1096bbe25317SEugene Zelenko const auto *A = cast<AcquiredAfterAttr>(At);
1097ab1dc2d5SDeLesley Hutchins
1098ab1dc2d5SDeLesley Hutchins // Read exprs from the attribute, and add them to BeforeVect.
1099ab1dc2d5SDeLesley Hutchins for (const auto *Arg : A->args()) {
1100ab1dc2d5SDeLesley Hutchins CapabilityExpr Cp =
1101ab1dc2d5SDeLesley Hutchins Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1102ab1dc2d5SDeLesley Hutchins if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1103ab1dc2d5SDeLesley Hutchins // Get entry for mutex listed in attribute
110419ff5602SReid Kleckner BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
110519ff5602SReid Kleckner ArgInfo->Vect.push_back(Vd);
1106ab1dc2d5SDeLesley Hutchins }
1107ab1dc2d5SDeLesley Hutchins }
1108ab1dc2d5SDeLesley Hutchins break;
1109ab1dc2d5SDeLesley Hutchins }
1110ab1dc2d5SDeLesley Hutchins default:
1111ab1dc2d5SDeLesley Hutchins break;
1112ab1dc2d5SDeLesley Hutchins }
1113ab1dc2d5SDeLesley Hutchins }
1114ab1dc2d5SDeLesley Hutchins
1115ab1dc2d5SDeLesley Hutchins return Info;
1116ab1dc2d5SDeLesley Hutchins }
1117ab1dc2d5SDeLesley Hutchins
111819ff5602SReid Kleckner BeforeSet::BeforeInfo *
getBeforeInfoForDecl(const ValueDecl * Vd,ThreadSafetyAnalyzer & Analyzer)111919ff5602SReid Kleckner BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
112019ff5602SReid Kleckner ThreadSafetyAnalyzer &Analyzer) {
112119ff5602SReid Kleckner auto It = BMap.find(Vd);
112219ff5602SReid Kleckner BeforeInfo *Info = nullptr;
112319ff5602SReid Kleckner if (It == BMap.end())
112419ff5602SReid Kleckner Info = insertAttrExprs(Vd, Analyzer);
112519ff5602SReid Kleckner else
112619ff5602SReid Kleckner Info = It->second.get();
112719ff5602SReid Kleckner assert(Info && "BMap contained nullptr?");
112819ff5602SReid Kleckner return Info;
112919ff5602SReid Kleckner }
1130ab1dc2d5SDeLesley Hutchins
1131ab1dc2d5SDeLesley Hutchins /// Return true if any mutexes in FSet are in the acquired_before set of Vd.
checkBeforeAfter(const ValueDecl * StartVd,const FactSet & FSet,ThreadSafetyAnalyzer & Analyzer,SourceLocation Loc,StringRef CapKind)1132ab1dc2d5SDeLesley Hutchins void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1133ab1dc2d5SDeLesley Hutchins const FactSet& FSet,
1134ab1dc2d5SDeLesley Hutchins ThreadSafetyAnalyzer& Analyzer,
1135ab1dc2d5SDeLesley Hutchins SourceLocation Loc, StringRef CapKind) {
1136ab1dc2d5SDeLesley Hutchins SmallVector<BeforeInfo*, 8> InfoVect;
1137ab1dc2d5SDeLesley Hutchins
1138ab1dc2d5SDeLesley Hutchins // Do a depth-first traversal of Vd.
1139ab1dc2d5SDeLesley Hutchins // Return true if there are cycles.
1140ab1dc2d5SDeLesley Hutchins std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1141ab1dc2d5SDeLesley Hutchins if (!Vd)
1142ab1dc2d5SDeLesley Hutchins return false;
1143ab1dc2d5SDeLesley Hutchins
114419ff5602SReid Kleckner BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
1145ab1dc2d5SDeLesley Hutchins
1146ab1dc2d5SDeLesley Hutchins if (Info->Visited == 1)
1147ab1dc2d5SDeLesley Hutchins return true;
1148ab1dc2d5SDeLesley Hutchins
1149ab1dc2d5SDeLesley Hutchins if (Info->Visited == 2)
1150ab1dc2d5SDeLesley Hutchins return false;
1151ab1dc2d5SDeLesley Hutchins
115219ff5602SReid Kleckner if (Info->Vect.empty())
1153ab1dc2d5SDeLesley Hutchins return false;
1154ab1dc2d5SDeLesley Hutchins
1155ab1dc2d5SDeLesley Hutchins InfoVect.push_back(Info);
1156ab1dc2d5SDeLesley Hutchins Info->Visited = 1;
1157bbe25317SEugene Zelenko for (const auto *Vdb : Info->Vect) {
1158ab1dc2d5SDeLesley Hutchins // Exclude mutexes in our immediate before set.
1159ab1dc2d5SDeLesley Hutchins if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1160ab1dc2d5SDeLesley Hutchins StringRef L1 = StartVd->getName();
1161ab1dc2d5SDeLesley Hutchins StringRef L2 = Vdb->getName();
1162ab1dc2d5SDeLesley Hutchins Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1163ab1dc2d5SDeLesley Hutchins }
1164ab1dc2d5SDeLesley Hutchins // Transitively search other before sets, and warn on cycles.
1165ab1dc2d5SDeLesley Hutchins if (traverse(Vdb)) {
1166ab1dc2d5SDeLesley Hutchins if (CycMap.find(Vd) == CycMap.end()) {
1167ab1dc2d5SDeLesley Hutchins CycMap.insert(std::make_pair(Vd, true));
1168ab1dc2d5SDeLesley Hutchins StringRef L1 = Vd->getName();
1169ab1dc2d5SDeLesley Hutchins Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1170ab1dc2d5SDeLesley Hutchins }
1171ab1dc2d5SDeLesley Hutchins }
1172ab1dc2d5SDeLesley Hutchins }
1173ab1dc2d5SDeLesley Hutchins Info->Visited = 2;
1174ab1dc2d5SDeLesley Hutchins return false;
1175ab1dc2d5SDeLesley Hutchins };
1176ab1dc2d5SDeLesley Hutchins
1177ab1dc2d5SDeLesley Hutchins traverse(StartVd);
1178ab1dc2d5SDeLesley Hutchins
1179ab1dc2d5SDeLesley Hutchins for (auto *Info : InfoVect)
1180ab1dc2d5SDeLesley Hutchins Info->Visited = 0;
1181ab1dc2d5SDeLesley Hutchins }
1182ab1dc2d5SDeLesley Hutchins
11839fc8faf9SAdrian Prantl /// Gets the value decl pointer from DeclRefExprs or MemberExprs.
getValueDecl(const Expr * Exp)1184e0449043SAaron Ballman static const ValueDecl *getValueDecl(const Expr *Exp) {
1185e0449043SAaron Ballman if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1186e0449043SAaron Ballman return getValueDecl(CE->getSubExpr());
1187e0449043SAaron Ballman
1188e0449043SAaron Ballman if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1189e0449043SAaron Ballman return DR->getDecl();
1190e0449043SAaron Ballman
1191e0449043SAaron Ballman if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1192e0449043SAaron Ballman return ME->getMemberDecl();
1193e0449043SAaron Ballman
1194e0449043SAaron Ballman return nullptr;
1195e0449043SAaron Ballman }
1196e0449043SAaron Ballman
119766a97ee9SBenjamin Kramer namespace {
1198bbe25317SEugene Zelenko
1199e0449043SAaron Ballman template <typename Ty>
1200a82eaa70SAaron Ballman class has_arg_iterator_range {
1201bbe25317SEugene Zelenko using yes = char[1];
1202bbe25317SEugene Zelenko using no = char[2];
1203e0449043SAaron Ballman
1204e0449043SAaron Ballman template <typename Inner>
1205a82eaa70SAaron Ballman static yes& test(Inner *I, decltype(I->args()) * = nullptr);
1206e0449043SAaron Ballman
1207e0449043SAaron Ballman template <typename>
1208e0449043SAaron Ballman static no& test(...);
1209e0449043SAaron Ballman
1210e0449043SAaron Ballman public:
1211e0449043SAaron Ballman static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1212e0449043SAaron Ballman };
1213bbe25317SEugene Zelenko
121466a97ee9SBenjamin Kramer } // namespace
1215e0449043SAaron Ballman
inCurrentScope(const CapabilityExpr & CapE)1216bbe25317SEugene Zelenko bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
12175250a03aSAaron Puchert const threadSafety::til::SExpr *SExp = CapE.sexpr();
12185250a03aSAaron Puchert assert(SExp && "Null expressions should be ignored");
12195250a03aSAaron Puchert
12205250a03aSAaron Puchert if (const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) {
12215250a03aSAaron Puchert const ValueDecl *VD = LP->clangDecl();
1222bbed8cfeSAaron Puchert // Variables defined in a function are always inaccessible.
1223bbed8cfeSAaron Puchert if (!VD->isDefinedOutsideFunctionOrMethod())
1224bbed8cfeSAaron Puchert return false;
1225bbed8cfeSAaron Puchert // For now we consider static class members to be inaccessible.
1226bbed8cfeSAaron Puchert if (isa<CXXRecordDecl>(VD->getDeclContext()))
1227bbed8cfeSAaron Puchert return false;
1228bbed8cfeSAaron Puchert // Global variables are always in scope.
1229bbed8cfeSAaron Puchert return true;
12305250a03aSAaron Puchert }
12315250a03aSAaron Puchert
12325250a03aSAaron Puchert // Members are in scope from methods of the same class.
12335250a03aSAaron Puchert if (const auto *P = dyn_cast<til::Project>(SExp)) {
12343efd0495SDeLesley Hutchins if (!CurrentMethod)
12353efd0495SDeLesley Hutchins return false;
1236b296c64eSAaron Puchert const ValueDecl *VD = P->clangDecl();
12373efd0495SDeLesley Hutchins return VD->getDeclContext() == CurrentMethod->getDeclContext();
12383efd0495SDeLesley Hutchins }
12395250a03aSAaron Puchert
12403efd0495SDeLesley Hutchins return false;
12413efd0495SDeLesley Hutchins }
12423efd0495SDeLesley Hutchins
12439fc8faf9SAdrian Prantl /// Add a new lock to the lockset, warning if the lock is already there.
12443efd0495SDeLesley Hutchins /// \param ReqAttr -- true if this is part of an initial Requires attribute.
addLock(FactSet & FSet,std::unique_ptr<FactEntry> Entry,bool ReqAttr)1245ca988749SEd Schouten void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1246ca988749SEd Schouten std::unique_ptr<FactEntry> Entry,
1247f8afb8fdSAaron Puchert bool ReqAttr) {
1248ca988749SEd Schouten if (Entry->shouldIgnore())
12493c3d57bcSDeLesley Hutchins return;
12503c3d57bcSDeLesley Hutchins
1251ca988749SEd Schouten if (!ReqAttr && !Entry->negative()) {
12523efd0495SDeLesley Hutchins // look for the negative capability, and remove it from the fact set.
1253ca988749SEd Schouten CapabilityExpr NegC = !*Entry;
1254969f32d5SAaron Puchert const FactEntry *Nen = FSet.findLock(FactMan, NegC);
12553efd0495SDeLesley Hutchins if (Nen) {
12563efd0495SDeLesley Hutchins FSet.removeLock(FactMan, NegC);
12573efd0495SDeLesley Hutchins }
12583efd0495SDeLesley Hutchins else {
1259ca988749SEd Schouten if (inCurrentScope(*Entry) && !Entry->asserted())
1260f8afb8fdSAaron Puchert Handler.handleNegativeNotHeld(Entry->getKind(), Entry->toString(),
1261ca988749SEd Schouten NegC.toString(), Entry->loc());
12623efd0495SDeLesley Hutchins }
12633efd0495SDeLesley Hutchins }
12644266522aSDeLesley Hutchins
1265ab1dc2d5SDeLesley Hutchins // Check before/after constraints
1266ab1dc2d5SDeLesley Hutchins if (Handler.issueBetaWarnings() &&
1267ab1dc2d5SDeLesley Hutchins !Entry->asserted() && !Entry->declared()) {
1268ab1dc2d5SDeLesley Hutchins GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1269f8afb8fdSAaron Puchert Entry->loc(), Entry->getKind());
1270ab1dc2d5SDeLesley Hutchins }
1271ab1dc2d5SDeLesley Hutchins
12724266522aSDeLesley Hutchins // FIXME: Don't always warn when we have support for reentrant locks.
1273969f32d5SAaron Puchert if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
1274ca988749SEd Schouten if (!Entry->asserted())
1275f8afb8fdSAaron Puchert Cp->handleLock(FSet, FactMan, *Entry, Handler);
12768c9d9579SDeLesley Hutchins } else {
1277ca988749SEd Schouten FSet.addLock(FactMan, std::move(Entry));
12788c9d9579SDeLesley Hutchins }
12798c9d9579SDeLesley Hutchins }
12808c9d9579SDeLesley Hutchins
12819fc8faf9SAdrian Prantl /// Remove a lock from the lockset, warning if the lock is not there.
12828c9d9579SDeLesley Hutchins /// \param UnlockLoc The source location of the unlock (only used in error msg)
removeLock(FactSet & FSet,const CapabilityExpr & Cp,SourceLocation UnlockLoc,bool FullyRemove,LockKind ReceivedKind)12834266522aSDeLesley Hutchins void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
1284d162c91bSDeLesley Hutchins SourceLocation UnlockLoc,
1285f8afb8fdSAaron Puchert bool FullyRemove, LockKind ReceivedKind) {
12864266522aSDeLesley Hutchins if (Cp.shouldIgnore())
12873c3d57bcSDeLesley Hutchins return;
12883c3d57bcSDeLesley Hutchins
12894266522aSDeLesley Hutchins const FactEntry *LDat = FSet.findLock(FactMan, Cp);
12908c9d9579SDeLesley Hutchins if (!LDat) {
1291f70912f8SAaron Puchert SourceLocation PrevLoc;
1292f70912f8SAaron Puchert if (const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
1293f70912f8SAaron Puchert PrevLoc = Neg->loc();
1294f8afb8fdSAaron Puchert Handler.handleUnmatchedUnlock(Cp.getKind(), Cp.toString(), UnlockLoc,
1295f8afb8fdSAaron Puchert PrevLoc);
1296c9776faaSDeLesley Hutchins return;
12978c9d9579SDeLesley Hutchins }
1298c9776faaSDeLesley Hutchins
1299df115d9bSAaron Ballman // Generic lock removal doesn't care about lock kind mismatches, but
1300df115d9bSAaron Ballman // otherwise diagnose when the lock kinds are mismatched.
13014266522aSDeLesley Hutchins if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1302f8afb8fdSAaron Puchert Handler.handleIncorrectUnlockKind(Cp.getKind(), Cp.toString(), LDat->kind(),
1303ad4d52a5SAaron Puchert ReceivedKind, LDat->loc(), UnlockLoc);
1304df115d9bSAaron Ballman }
1305df115d9bSAaron Ballman
1306f8afb8fdSAaron Puchert LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler);
130709bcefcbSDeLesley Hutchins }
13088c9d9579SDeLesley Hutchins
13099fc8faf9SAdrian Prantl /// Extract the list of mutexIDs from the attribute on an expression,
131009bcefcbSDeLesley Hutchins /// and push them onto Mtxs, discarding any duplicates.
13118c9d9579SDeLesley Hutchins template <typename AttrType>
getMutexIDs(CapExprSet & Mtxs,AttrType * Attr,const Expr * Exp,const NamedDecl * D,VarDecl * SelfDecl)13124266522aSDeLesley Hutchins void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
131368c7fcdaSAaron Puchert const Expr *Exp, const NamedDecl *D,
13141fe88561SDeLesley Hutchins VarDecl *SelfDecl) {
13158c9d9579SDeLesley Hutchins if (Attr->args_size() == 0) {
13168c9d9579SDeLesley Hutchins // The mutex held is the "this" object.
13174266522aSDeLesley Hutchins CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
13184266522aSDeLesley Hutchins if (Cp.isInvalid()) {
1319f8afb8fdSAaron Puchert warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
1320ea1f8338SDeLesley Hutchins return;
1321ea1f8338SDeLesley Hutchins }
1322ea1f8338SDeLesley Hutchins //else
13234266522aSDeLesley Hutchins if (!Cp.shouldIgnore())
13244266522aSDeLesley Hutchins Mtxs.push_back_nodup(Cp);
132509bcefcbSDeLesley Hutchins return;
13268c9d9579SDeLesley Hutchins }
132709bcefcbSDeLesley Hutchins
1328a82eaa70SAaron Ballman for (const auto *Arg : Attr->args()) {
13294266522aSDeLesley Hutchins CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
13304266522aSDeLesley Hutchins if (Cp.isInvalid()) {
1331f8afb8fdSAaron Puchert warnInvalidLock(Handler, nullptr, D, Exp, Cp.getKind());
13324266522aSDeLesley Hutchins continue;
1333ea1f8338SDeLesley Hutchins }
1334ea1f8338SDeLesley Hutchins //else
13354266522aSDeLesley Hutchins if (!Cp.shouldIgnore())
13364266522aSDeLesley Hutchins Mtxs.push_back_nodup(Cp);
133709bcefcbSDeLesley Hutchins }
13388c9d9579SDeLesley Hutchins }
13398c9d9579SDeLesley Hutchins
13409fc8faf9SAdrian Prantl /// Extract the list of mutexIDs from a trylock attribute. If the
134109bcefcbSDeLesley Hutchins /// trylock applies to the given edge, then push them onto Mtxs, discarding
134209bcefcbSDeLesley Hutchins /// any duplicates.
13438c9d9579SDeLesley Hutchins template <class AttrType>
getMutexIDs(CapExprSet & Mtxs,AttrType * Attr,const Expr * Exp,const NamedDecl * D,const CFGBlock * PredBlock,const CFGBlock * CurrBlock,Expr * BrE,bool Neg)13444266522aSDeLesley Hutchins void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
134568c7fcdaSAaron Puchert const Expr *Exp, const NamedDecl *D,
13468c9d9579SDeLesley Hutchins const CFGBlock *PredBlock,
13478c9d9579SDeLesley Hutchins const CFGBlock *CurrBlock,
13488c9d9579SDeLesley Hutchins Expr *BrE, bool Neg) {
13498c9d9579SDeLesley Hutchins // Find out which branch has the lock
13502f3fc6baSAaron Ballman bool branch = false;
1351bbe25317SEugene Zelenko if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
13528c9d9579SDeLesley Hutchins branch = BLE->getValue();
1353bbe25317SEugene Zelenko else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
13548c9d9579SDeLesley Hutchins branch = ILE->getValue().getBoolValue();
13552f3fc6baSAaron Ballman
13568c9d9579SDeLesley Hutchins int branchnum = branch ? 0 : 1;
13572f3fc6baSAaron Ballman if (Neg)
13582f3fc6baSAaron Ballman branchnum = !branchnum;
13598c9d9579SDeLesley Hutchins
13608c9d9579SDeLesley Hutchins // If we've taken the trylock branch, then add the lock
13618c9d9579SDeLesley Hutchins int i = 0;
13628c9d9579SDeLesley Hutchins for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
13638c9d9579SDeLesley Hutchins SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
13642f3fc6baSAaron Ballman if (*SI == CurrBlock && i == branchnum)
136509bcefcbSDeLesley Hutchins getMutexIDs(Mtxs, Attr, Exp, D);
13668c9d9579SDeLesley Hutchins }
13678c9d9579SDeLesley Hutchins }
13688c9d9579SDeLesley Hutchins
getStaticBooleanValue(Expr * E,bool & TCond)136966a97ee9SBenjamin Kramer static bool getStaticBooleanValue(Expr *E, bool &TCond) {
1370868830f7SDeLesley Hutchins if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1371868830f7SDeLesley Hutchins TCond = false;
1372868830f7SDeLesley Hutchins return true;
1373bbe25317SEugene Zelenko } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1374868830f7SDeLesley Hutchins TCond = BLE->getValue();
1375868830f7SDeLesley Hutchins return true;
1376bbe25317SEugene Zelenko } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
1377868830f7SDeLesley Hutchins TCond = ILE->getValue().getBoolValue();
1378868830f7SDeLesley Hutchins return true;
1379bbe25317SEugene Zelenko } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
1380868830f7SDeLesley Hutchins return getStaticBooleanValue(CE->getSubExpr(), TCond);
1381868830f7SDeLesley Hutchins return false;
1382868830f7SDeLesley Hutchins }
1383868830f7SDeLesley Hutchins
13848c9d9579SDeLesley Hutchins // If Cond can be traced back to a function call, return the call expression.
13858c9d9579SDeLesley Hutchins // The negate variable should be called with false, and will be set to true
13868c9d9579SDeLesley Hutchins // if the function call is negated, e.g. if (!mu.tryLock(...))
getTrylockCallExpr(const Stmt * Cond,LocalVarContext C,bool & Negate)13878c9d9579SDeLesley Hutchins const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
13888c9d9579SDeLesley Hutchins LocalVarContext C,
13898c9d9579SDeLesley Hutchins bool &Negate) {
13908c9d9579SDeLesley Hutchins if (!Cond)
139125542943SCraig Topper return nullptr;
13928c9d9579SDeLesley Hutchins
13937146b003SAaron Puchert if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
13947146b003SAaron Puchert if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
13957146b003SAaron Puchert return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
13968c9d9579SDeLesley Hutchins return CallExp;
13977146b003SAaron Puchert }
1398bbe25317SEugene Zelenko else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
1399868830f7SDeLesley Hutchins return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1400bbe25317SEugene Zelenko else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
14018c9d9579SDeLesley Hutchins return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
14027c44da27SBill Wendling else if (const auto *FE = dyn_cast<FullExpr>(Cond))
14037c44da27SBill Wendling return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
1404bbe25317SEugene Zelenko else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
14058c9d9579SDeLesley Hutchins const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
14068c9d9579SDeLesley Hutchins return getTrylockCallExpr(E, C, Negate);
14078c9d9579SDeLesley Hutchins }
1408bbe25317SEugene Zelenko else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
14098c9d9579SDeLesley Hutchins if (UOP->getOpcode() == UO_LNot) {
14108c9d9579SDeLesley Hutchins Negate = !Negate;
14118c9d9579SDeLesley Hutchins return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
14128c9d9579SDeLesley Hutchins }
141325542943SCraig Topper return nullptr;
1414868830f7SDeLesley Hutchins }
1415bbe25317SEugene Zelenko else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
1416868830f7SDeLesley Hutchins if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1417868830f7SDeLesley Hutchins if (BOP->getOpcode() == BO_NE)
1418868830f7SDeLesley Hutchins Negate = !Negate;
1419868830f7SDeLesley Hutchins
1420868830f7SDeLesley Hutchins bool TCond = false;
1421868830f7SDeLesley Hutchins if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1422868830f7SDeLesley Hutchins if (!TCond) Negate = !Negate;
1423868830f7SDeLesley Hutchins return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1424868830f7SDeLesley Hutchins }
14259f5193cfSDeLesley Hutchins TCond = false;
14269f5193cfSDeLesley Hutchins if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1427868830f7SDeLesley Hutchins if (!TCond) Negate = !Negate;
1428868830f7SDeLesley Hutchins return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1429868830f7SDeLesley Hutchins }
143025542943SCraig Topper return nullptr;
1431868830f7SDeLesley Hutchins }
14329f5193cfSDeLesley Hutchins if (BOP->getOpcode() == BO_LAnd) {
14339f5193cfSDeLesley Hutchins // LHS must have been evaluated in a different block.
14349f5193cfSDeLesley Hutchins return getTrylockCallExpr(BOP->getRHS(), C, Negate);
14359f5193cfSDeLesley Hutchins }
1436bbe25317SEugene Zelenko if (BOP->getOpcode() == BO_LOr)
14379f5193cfSDeLesley Hutchins return getTrylockCallExpr(BOP->getRHS(), C, Negate);
143825542943SCraig Topper return nullptr;
1439b0a2a0cfSAaron Puchert } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
1440b0a2a0cfSAaron Puchert bool TCond, FCond;
1441b0a2a0cfSAaron Puchert if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
1442b0a2a0cfSAaron Puchert getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
1443b0a2a0cfSAaron Puchert if (TCond && !FCond)
1444b0a2a0cfSAaron Puchert return getTrylockCallExpr(COP->getCond(), C, Negate);
1445b0a2a0cfSAaron Puchert if (!TCond && FCond) {
1446b0a2a0cfSAaron Puchert Negate = !Negate;
1447b0a2a0cfSAaron Puchert return getTrylockCallExpr(COP->getCond(), C, Negate);
1448b0a2a0cfSAaron Puchert }
1449b0a2a0cfSAaron Puchert }
14508c9d9579SDeLesley Hutchins }
145125542943SCraig Topper return nullptr;
14528c9d9579SDeLesley Hutchins }
14538c9d9579SDeLesley Hutchins
14549fc8faf9SAdrian Prantl /// Find the lockset that holds on the edge between PredBlock
1455ebbf7701SDeLesley Hutchins /// and CurrBlock. The edge set is the exit set of PredBlock (passed
1456ebbf7701SDeLesley Hutchins /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
getEdgeLockset(FactSet & Result,const FactSet & ExitSet,const CFGBlock * PredBlock,const CFGBlock * CurrBlock)1457c9776faaSDeLesley Hutchins void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1458c9776faaSDeLesley Hutchins const FactSet &ExitSet,
14598c9d9579SDeLesley Hutchins const CFGBlock *PredBlock,
14608c9d9579SDeLesley Hutchins const CFGBlock *CurrBlock) {
1461c9776faaSDeLesley Hutchins Result = ExitSet;
1462c9776faaSDeLesley Hutchins
14639f5193cfSDeLesley Hutchins const Stmt *Cond = PredBlock->getTerminatorCondition();
1464b0a2a0cfSAaron Puchert // We don't acquire try-locks on ?: branches, only when its result is used.
14654e53032dSArtem Dergachev if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminatorStmt()))
1466c9776faaSDeLesley Hutchins return;
1467ebbf7701SDeLesley Hutchins
14688c9d9579SDeLesley Hutchins bool Negate = false;
14698c9d9579SDeLesley Hutchins const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
14708c9d9579SDeLesley Hutchins const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
14718c9d9579SDeLesley Hutchins
147268c7fcdaSAaron Puchert const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
14738c9d9579SDeLesley Hutchins if (!Exp)
1474c9776faaSDeLesley Hutchins return;
14758c9d9579SDeLesley Hutchins
1476bbe25317SEugene Zelenko auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
14778c9d9579SDeLesley Hutchins if(!FunDecl || !FunDecl->hasAttrs())
1478c9776faaSDeLesley Hutchins return;
14798c9d9579SDeLesley Hutchins
14804266522aSDeLesley Hutchins CapExprSet ExclusiveLocksToAdd;
14814266522aSDeLesley Hutchins CapExprSet SharedLocksToAdd;
14828c9d9579SDeLesley Hutchins
14838c9d9579SDeLesley Hutchins // If the condition is a call to a Trylock function, then grab the attributes
1484bbe25317SEugene Zelenko for (const auto *Attr : FunDecl->attrs()) {
14858c9d9579SDeLesley Hutchins switch (Attr->getKind()) {
148681d07fc2SAaron Ballman case attr::TryAcquireCapability: {
148781d07fc2SAaron Ballman auto *A = cast<TryAcquireCapabilityAttr>(Attr);
148881d07fc2SAaron Ballman getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
148981d07fc2SAaron Ballman Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
149081d07fc2SAaron Ballman Negate);
149181d07fc2SAaron Ballman break;
149281d07fc2SAaron Ballman };
14938c9d9579SDeLesley Hutchins case attr::ExclusiveTrylockFunction: {
1494bbe25317SEugene Zelenko const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
1495f8afb8fdSAaron Puchert getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
1496f8afb8fdSAaron Puchert A->getSuccessValue(), Negate);
14978c9d9579SDeLesley Hutchins break;
14988c9d9579SDeLesley Hutchins }
14998c9d9579SDeLesley Hutchins case attr::SharedTrylockFunction: {
1500bbe25317SEugene Zelenko const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
1501f8afb8fdSAaron Puchert getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
1502f8afb8fdSAaron Puchert A->getSuccessValue(), Negate);
15038c9d9579SDeLesley Hutchins break;
15048c9d9579SDeLesley Hutchins }
15058c9d9579SDeLesley Hutchins default:
15068c9d9579SDeLesley Hutchins break;
15078c9d9579SDeLesley Hutchins }
15088c9d9579SDeLesley Hutchins }
150909bcefcbSDeLesley Hutchins
151009bcefcbSDeLesley Hutchins // Add and remove locks.
151109bcefcbSDeLesley Hutchins SourceLocation Loc = Exp->getExprLoc();
1512e0449043SAaron Ballman for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
15132b3d49b6SJonas Devlieghere addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1514f8afb8fdSAaron Puchert LK_Exclusive, Loc));
1515e0449043SAaron Ballman for (const auto &SharedLockToAdd : SharedLocksToAdd)
15162b3d49b6SJonas Devlieghere addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd,
1517f8afb8fdSAaron Puchert LK_Shared, Loc));
151809bcefcbSDeLesley Hutchins }
15198c9d9579SDeLesley Hutchins
152066a97ee9SBenjamin Kramer namespace {
1521bbe25317SEugene Zelenko
15229fc8faf9SAdrian Prantl /// We use this class to visit different types of expressions in
152333208340SCaitlin Sadowski /// CFGBlocks, and build up the lockset.
152433208340SCaitlin Sadowski /// An expression may cause us to add or remove locks from the lockset, or else
152533208340SCaitlin Sadowski /// output error messages related to missing locks.
152633208340SCaitlin Sadowski /// FIXME: In future, we may be able to not inherit from a visitor.
1527cd37c091SAaron Puchert class BuildLockset : public ConstStmtVisitor<BuildLockset> {
1528c2090511SDeLesley Hutchins friend class ThreadSafetyAnalyzer;
1529c2090511SDeLesley Hutchins
15308c9d9579SDeLesley Hutchins ThreadSafetyAnalyzer *Analyzer;
1531c9776faaSDeLesley Hutchins FactSet FSet;
15329b7022e5SDeLesley Hutchins LocalVariableMap::Context LVarCtx;
15339b7022e5SDeLesley Hutchins unsigned CtxIndex;
153433208340SCaitlin Sadowski
15353efd0495SDeLesley Hutchins // helper functions
15365df82f21SDeLesley Hutchins void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1537e0449043SAaron Ballman Expr *MutexExp, ProtectedOperationKind POK,
1538f8afb8fdSAaron Puchert SourceLocation Loc);
1539f8afb8fdSAaron Puchert void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp);
15408c9d9579SDeLesley Hutchins
1541c60dc2cfSDeLesley Hutchins void checkAccess(const Expr *Exp, AccessKind AK,
1542c60dc2cfSDeLesley Hutchins ProtectedOperationKind POK = POK_VarAccess);
1543c60dc2cfSDeLesley Hutchins void checkPtAccess(const Expr *Exp, AccessKind AK,
1544c60dc2cfSDeLesley Hutchins ProtectedOperationKind POK = POK_VarAccess);
15455df82f21SDeLesley Hutchins
1546cd37c091SAaron Puchert void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
154735389e51SAaron Puchert void examineArguments(const FunctionDecl *FD,
154835389e51SAaron Puchert CallExpr::const_arg_iterator ArgBegin,
154935389e51SAaron Puchert CallExpr::const_arg_iterator ArgEnd,
155035389e51SAaron Puchert bool SkipFirstParam = false);
155133208340SCaitlin Sadowski
155233208340SCaitlin Sadowski public:
BuildLockset(ThreadSafetyAnalyzer * Anlzr,CFGBlockInfo & Info)15538c9d9579SDeLesley Hutchins BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1554cd37c091SAaron Puchert : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
1555bbe25317SEugene Zelenko LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
155633208340SCaitlin Sadowski
1557cd37c091SAaron Puchert void VisitUnaryOperator(const UnaryOperator *UO);
1558cd37c091SAaron Puchert void VisitBinaryOperator(const BinaryOperator *BO);
1559cd37c091SAaron Puchert void VisitCastExpr(const CastExpr *CE);
1560cd37c091SAaron Puchert void VisitCallExpr(const CallExpr *Exp);
1561cd37c091SAaron Puchert void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1562cd37c091SAaron Puchert void VisitDeclStmt(const DeclStmt *S);
156333208340SCaitlin Sadowski };
1564bbe25317SEugene Zelenko
156566a97ee9SBenjamin Kramer } // namespace
15664266522aSDeLesley Hutchins
15679fc8faf9SAdrian Prantl /// Warn if the LSet does not contain a lock sufficient to protect access
1568a088f67bSDeLesley Hutchins /// of at least the passed in AccessKind.
warnIfMutexNotHeld(const NamedDecl * D,const Expr * Exp,AccessKind AK,Expr * MutexExp,ProtectedOperationKind POK,SourceLocation Loc)15695df82f21SDeLesley Hutchins void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
157033208340SCaitlin Sadowski AccessKind AK, Expr *MutexExp,
1571e0449043SAaron Ballman ProtectedOperationKind POK,
1572f8afb8fdSAaron Puchert SourceLocation Loc) {
157333208340SCaitlin Sadowski LockKind LK = getLockKindFromAccessKind(AK);
1574a088f67bSDeLesley Hutchins
15754266522aSDeLesley Hutchins CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
15764266522aSDeLesley Hutchins if (Cp.isInvalid()) {
1577f8afb8fdSAaron Puchert warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, Cp.getKind());
1578a5a00e83SDeLesley Hutchins return;
15794266522aSDeLesley Hutchins } else if (Cp.shouldIgnore()) {
1580a5a00e83SDeLesley Hutchins return;
1581a5a00e83SDeLesley Hutchins }
1582a5a00e83SDeLesley Hutchins
15834266522aSDeLesley Hutchins if (Cp.negative()) {
15844266522aSDeLesley Hutchins // Negative capabilities act like locks excluded
1585969f32d5SAaron Puchert const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
15864266522aSDeLesley Hutchins if (LDat) {
15874266522aSDeLesley Hutchins Analyzer->Handler.handleFunExcludesLock(
1588f8afb8fdSAaron Puchert Cp.getKind(), D->getNameAsString(), (!Cp).toString(), Loc);
15894266522aSDeLesley Hutchins return;
15904266522aSDeLesley Hutchins }
15914266522aSDeLesley Hutchins
15924266522aSDeLesley Hutchins // If this does not refer to a negative capability in the same class,
15934266522aSDeLesley Hutchins // then stop here.
15943efd0495SDeLesley Hutchins if (!Analyzer->inCurrentScope(Cp))
15954266522aSDeLesley Hutchins return;
15964266522aSDeLesley Hutchins
15974266522aSDeLesley Hutchins // Otherwise the negative requirement must be propagated to the caller.
15984266522aSDeLesley Hutchins LDat = FSet.findLock(Analyzer->FactMan, Cp);
15994266522aSDeLesley Hutchins if (!LDat) {
16008ca00c5cSAaron Puchert Analyzer->Handler.handleNegativeNotHeld(D, Cp.toString(), Loc);
16014266522aSDeLesley Hutchins }
16024266522aSDeLesley Hutchins return;
16034266522aSDeLesley Hutchins }
16044266522aSDeLesley Hutchins
1605969f32d5SAaron Puchert const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
16065ff1644eSDeLesley Hutchins bool NoError = true;
16075ff1644eSDeLesley Hutchins if (!LDat) {
16085ff1644eSDeLesley Hutchins // No exact match found. Look for a partial match.
16094266522aSDeLesley Hutchins LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
16104266522aSDeLesley Hutchins if (LDat) {
16115ff1644eSDeLesley Hutchins // Warn that there's no precise match.
16124266522aSDeLesley Hutchins std::string PartMatchStr = LDat->toString();
16135ff1644eSDeLesley Hutchins StringRef PartMatchName(PartMatchStr);
1614f8afb8fdSAaron Puchert Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
16154133b13bSDeLesley Hutchins LK, Loc, &PartMatchName);
16165ff1644eSDeLesley Hutchins } else {
16175ff1644eSDeLesley Hutchins // Warn that there's no match at all.
1618f8afb8fdSAaron Puchert Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
16194133b13bSDeLesley Hutchins LK, Loc);
16205ff1644eSDeLesley Hutchins }
16215ff1644eSDeLesley Hutchins NoError = false;
16225ff1644eSDeLesley Hutchins }
16235ff1644eSDeLesley Hutchins // Make sure the mutex we found is the right kind.
16244266522aSDeLesley Hutchins if (NoError && LDat && !LDat->isAtLeast(LK)) {
1625f8afb8fdSAaron Puchert Analyzer->Handler.handleMutexNotHeld(Cp.getKind(), D, POK, Cp.toString(),
16264133b13bSDeLesley Hutchins LK, Loc);
162733208340SCaitlin Sadowski }
16284266522aSDeLesley Hutchins }
162933208340SCaitlin Sadowski
16309fc8faf9SAdrian Prantl /// Warn if the LSet contains the given lock.
warnIfMutexHeld(const NamedDecl * D,const Expr * Exp,Expr * MutexExp)16315df82f21SDeLesley Hutchins void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1632f8afb8fdSAaron Puchert Expr *MutexExp) {
16334266522aSDeLesley Hutchins CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
16344266522aSDeLesley Hutchins if (Cp.isInvalid()) {
1635f8afb8fdSAaron Puchert warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, Cp.getKind());
16364266522aSDeLesley Hutchins return;
16374266522aSDeLesley Hutchins } else if (Cp.shouldIgnore()) {
1638a5a00e83SDeLesley Hutchins return;
1639a5a00e83SDeLesley Hutchins }
1640a5a00e83SDeLesley Hutchins
1641969f32d5SAaron Puchert const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
16424266522aSDeLesley Hutchins if (LDat) {
1643f8afb8fdSAaron Puchert Analyzer->Handler.handleFunExcludesLock(Cp.getKind(), D->getNameAsString(),
1644f8afb8fdSAaron Puchert Cp.toString(), Exp->getExprLoc());
16454266522aSDeLesley Hutchins }
1646a5a00e83SDeLesley Hutchins }
1647a5a00e83SDeLesley Hutchins
16489fc8faf9SAdrian Prantl /// Checks guarded_by and pt_guarded_by attributes.
16495df82f21SDeLesley Hutchins /// Whenever we identify an access (read or write) to a DeclRefExpr that is
16505df82f21SDeLesley Hutchins /// marked with guarded_by, we must ensure the appropriate mutexes are held.
16515df82f21SDeLesley Hutchins /// Similarly, we check if the access is to an expression that dereferences
16525df82f21SDeLesley Hutchins /// a pointer marked with pt_guarded_by.
checkAccess(const Expr * Exp,AccessKind AK,ProtectedOperationKind POK)1653c60dc2cfSDeLesley Hutchins void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1654c60dc2cfSDeLesley Hutchins ProtectedOperationKind POK) {
16554baaa5abSRichard Smith Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
16565df82f21SDeLesley Hutchins
16574133b13bSDeLesley Hutchins SourceLocation Loc = Exp->getExprLoc();
16584133b13bSDeLesley Hutchins
16594133b13bSDeLesley Hutchins // Local variables of reference type cannot be re-assigned;
16604133b13bSDeLesley Hutchins // map them to their initializer.
1661b0088589SAaron Ballman while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1662b0088589SAaron Ballman const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
16634133b13bSDeLesley Hutchins if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1664b0088589SAaron Ballman if (const auto *E = VD->getInit()) {
166557deab77SAaron Ballman // Guard against self-initialization. e.g., int &i = i;
166657deab77SAaron Ballman if (E == Exp)
166757deab77SAaron Ballman break;
16684133b13bSDeLesley Hutchins Exp = E;
16694133b13bSDeLesley Hutchins continue;
16704133b13bSDeLesley Hutchins }
16714133b13bSDeLesley Hutchins }
16724133b13bSDeLesley Hutchins break;
16734133b13bSDeLesley Hutchins }
16744133b13bSDeLesley Hutchins
1675bbe25317SEugene Zelenko if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
16765df82f21SDeLesley Hutchins // For dereferences
1677bbe25317SEugene Zelenko if (UO->getOpcode() == UO_Deref)
1678c60dc2cfSDeLesley Hutchins checkPtAccess(UO->getSubExpr(), AK, POK);
167933208340SCaitlin Sadowski return;
168033208340SCaitlin Sadowski }
168133208340SCaitlin Sadowski
1682*bfe63ab6SAaron Puchert if (const auto *BO = dyn_cast<BinaryOperator>(Exp)) {
1683*bfe63ab6SAaron Puchert switch (BO->getOpcode()) {
1684*bfe63ab6SAaron Puchert case BO_PtrMemD: // .*
1685*bfe63ab6SAaron Puchert return checkAccess(BO->getLHS(), AK, POK);
1686*bfe63ab6SAaron Puchert case BO_PtrMemI: // ->*
1687*bfe63ab6SAaron Puchert return checkPtAccess(BO->getLHS(), AK, POK);
1688*bfe63ab6SAaron Puchert default:
1689*bfe63ab6SAaron Puchert return;
1690*bfe63ab6SAaron Puchert }
1691*bfe63ab6SAaron Puchert }
1692*bfe63ab6SAaron Puchert
1693bbe25317SEugene Zelenko if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1694c60dc2cfSDeLesley Hutchins checkPtAccess(AE->getLHS(), AK, POK);
1695e73d6b60SDeLesley Hutchins return;
1696e73d6b60SDeLesley Hutchins }
1697e73d6b60SDeLesley Hutchins
1698bbe25317SEugene Zelenko if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
16990cfa1a5aSDeLesley Hutchins if (ME->isArrow())
1700c60dc2cfSDeLesley Hutchins checkPtAccess(ME->getBase(), AK, POK);
17010cfa1a5aSDeLesley Hutchins else
1702c60dc2cfSDeLesley Hutchins checkAccess(ME->getBase(), AK, POK);
17030cfa1a5aSDeLesley Hutchins }
17040cfa1a5aSDeLesley Hutchins
170533208340SCaitlin Sadowski const ValueDecl *D = getValueDecl(Exp);
170633208340SCaitlin Sadowski if (!D || !D->hasAttrs())
170733208340SCaitlin Sadowski return;
170833208340SCaitlin Sadowski
17093efd0495SDeLesley Hutchins if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
17100314dbacSAaron Puchert Analyzer->Handler.handleNoMutexHeld(D, POK, AK, Loc);
17113efd0495SDeLesley Hutchins }
171233208340SCaitlin Sadowski
1713be22bcb1SAaron Ballman for (const auto *I : D->specific_attrs<GuardedByAttr>())
1714f8afb8fdSAaron Puchert warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK, Loc);
171533208340SCaitlin Sadowski }
171633208340SCaitlin Sadowski
17179fc8faf9SAdrian Prantl /// Checks pt_guarded_by and pt_guarded_var attributes.
1718c60dc2cfSDeLesley Hutchins /// POK is the same operationKind that was passed to checkAccess.
checkPtAccess(const Expr * Exp,AccessKind AK,ProtectedOperationKind POK)1719c60dc2cfSDeLesley Hutchins void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1720c60dc2cfSDeLesley Hutchins ProtectedOperationKind POK) {
1721e73d6b60SDeLesley Hutchins while (true) {
1722bbe25317SEugene Zelenko if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
1723e73d6b60SDeLesley Hutchins Exp = PE->getSubExpr();
1724e73d6b60SDeLesley Hutchins continue;
1725e73d6b60SDeLesley Hutchins }
1726bbe25317SEugene Zelenko if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
1727e73d6b60SDeLesley Hutchins if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1728e73d6b60SDeLesley Hutchins // If it's an actual array, and not a pointer, then it's elements
1729e73d6b60SDeLesley Hutchins // are protected by GUARDED_BY, not PT_GUARDED_BY;
1730c60dc2cfSDeLesley Hutchins checkAccess(CE->getSubExpr(), AK, POK);
1731e73d6b60SDeLesley Hutchins return;
1732e73d6b60SDeLesley Hutchins }
1733e73d6b60SDeLesley Hutchins Exp = CE->getSubExpr();
1734e73d6b60SDeLesley Hutchins continue;
1735e73d6b60SDeLesley Hutchins }
1736e73d6b60SDeLesley Hutchins break;
1737e73d6b60SDeLesley Hutchins }
17385df82f21SDeLesley Hutchins
1739c60dc2cfSDeLesley Hutchins // Pass by reference warnings are under a different flag.
1740c60dc2cfSDeLesley Hutchins ProtectedOperationKind PtPOK = POK_VarDereference;
1741c60dc2cfSDeLesley Hutchins if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1742c60dc2cfSDeLesley Hutchins
17435df82f21SDeLesley Hutchins const ValueDecl *D = getValueDecl(Exp);
17445df82f21SDeLesley Hutchins if (!D || !D->hasAttrs())
17455df82f21SDeLesley Hutchins return;
17465df82f21SDeLesley Hutchins
17473efd0495SDeLesley Hutchins if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
17480314dbacSAaron Puchert Analyzer->Handler.handleNoMutexHeld(D, PtPOK, AK, Exp->getExprLoc());
17495df82f21SDeLesley Hutchins
1750be22bcb1SAaron Ballman for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1751f8afb8fdSAaron Puchert warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK, Exp->getExprLoc());
17525df82f21SDeLesley Hutchins }
17535df82f21SDeLesley Hutchins
17549fc8faf9SAdrian Prantl /// Process a function call, method call, constructor call,
1755db917bdeSDeLesley Hutchins /// or destructor call. This involves looking at the attributes on the
1756db917bdeSDeLesley Hutchins /// corresponding function/method/constructor/destructor, issuing warnings,
1757db917bdeSDeLesley Hutchins /// and updating the locksets accordingly.
175833208340SCaitlin Sadowski ///
175933208340SCaitlin Sadowski /// FIXME: For classes annotated with one of the guarded annotations, we need
176033208340SCaitlin Sadowski /// to treat const method calls as reads and non-const method calls as writes,
176133208340SCaitlin Sadowski /// and check that the appropriate locks are held. Non-const method calls with
176233208340SCaitlin Sadowski /// the same signature as const method calls can be also treated as reads.
176333208340SCaitlin Sadowski ///
handleCall(const Expr * Exp,const NamedDecl * D,VarDecl * VD)1764cd37c091SAaron Puchert void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1765cd37c091SAaron Puchert VarDecl *VD) {
1766b6824317SDeLesley Hutchins SourceLocation Loc = Exp->getExprLoc();
17674266522aSDeLesley Hutchins CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
17684266522aSDeLesley Hutchins CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
17691850f56cSAaron Puchert CapExprSet ScopedReqsAndExcludes;
177009bcefcbSDeLesley Hutchins
1771e97654b2SRichard Smith // Figure out if we're constructing an object of scoped lockable class
177274e0f40dSHaojian Wu bool isScopedVar = false;
17733c355aa2SDeLesley Hutchins if (VD) {
1774bbe25317SEugene Zelenko if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
17753c355aa2SDeLesley Hutchins const CXXRecordDecl* PD = CD->getParent();
17763c355aa2SDeLesley Hutchins if (PD && PD->hasAttr<ScopedLockableAttr>())
177774e0f40dSHaojian Wu isScopedVar = true;
17783c355aa2SDeLesley Hutchins }
17793c355aa2SDeLesley Hutchins }
17803c355aa2SDeLesley Hutchins
17811b58759dSAaron Ballman for(const Attr *At : D->attrs()) {
178209bcefcbSDeLesley Hutchins switch (At->getKind()) {
178318d85aedSAaron Ballman // When we encounter a lock function, we need to add the lock to our
178418d85aedSAaron Ballman // lockset.
178518d85aedSAaron Ballman case attr::AcquireCapability: {
1786bbe25317SEugene Zelenko const auto *A = cast<AcquireCapabilityAttr>(At);
178718d85aedSAaron Ballman Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
178818d85aedSAaron Ballman : ExclusiveLocksToAdd,
178918d85aedSAaron Ballman A, Exp, D, VD);
179033208340SCaitlin Sadowski break;
1791a088f67bSDeLesley Hutchins }
179233208340SCaitlin Sadowski
1793b6824317SDeLesley Hutchins // An assert will add a lock to the lockset, but will not generate
1794b6824317SDeLesley Hutchins // a warning if it is already there, and will not generate a warning
1795b6824317SDeLesley Hutchins // if it is not removed.
1796b6824317SDeLesley Hutchins case attr::AssertExclusiveLock: {
1797bbe25317SEugene Zelenko const auto *A = cast<AssertExclusiveLockAttr>(At);
1798b6824317SDeLesley Hutchins
17994266522aSDeLesley Hutchins CapExprSet AssertLocks;
1800b6824317SDeLesley Hutchins Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1801e0449043SAaron Ballman for (const auto &AssertLock : AssertLocks)
1802530e074fSAaron Puchert Analyzer->addLock(
1803f8afb8fdSAaron Puchert FSet, std::make_unique<LockableFactEntry>(
1804f8afb8fdSAaron Puchert AssertLock, LK_Exclusive, Loc, FactEntry::Asserted));
1805b6824317SDeLesley Hutchins break;
1806b6824317SDeLesley Hutchins }
1807b6824317SDeLesley Hutchins case attr::AssertSharedLock: {
1808bbe25317SEugene Zelenko const auto *A = cast<AssertSharedLockAttr>(At);
1809b6824317SDeLesley Hutchins
18104266522aSDeLesley Hutchins CapExprSet AssertLocks;
1811b6824317SDeLesley Hutchins Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1812e0449043SAaron Ballman for (const auto &AssertLock : AssertLocks)
1813530e074fSAaron Puchert Analyzer->addLock(
1814f8afb8fdSAaron Puchert FSet, std::make_unique<LockableFactEntry>(
1815f8afb8fdSAaron Puchert AssertLock, LK_Shared, Loc, FactEntry::Asserted));
1816b6824317SDeLesley Hutchins break;
1817b6824317SDeLesley Hutchins }
1818b6824317SDeLesley Hutchins
1819ec1369edSJosh Gao case attr::AssertCapability: {
1820bbe25317SEugene Zelenko const auto *A = cast<AssertCapabilityAttr>(At);
1821ec1369edSJosh Gao CapExprSet AssertLocks;
1822ec1369edSJosh Gao Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1823ec1369edSJosh Gao for (const auto &AssertLock : AssertLocks)
1824f8afb8fdSAaron Puchert Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(
1825ec1369edSJosh Gao AssertLock,
1826f8afb8fdSAaron Puchert A->isShared() ? LK_Shared : LK_Exclusive,
1827f8afb8fdSAaron Puchert Loc, FactEntry::Asserted));
1828ec1369edSJosh Gao break;
1829ec1369edSJosh Gao }
1830ec1369edSJosh Gao
183133208340SCaitlin Sadowski // When we encounter an unlock function, we need to remove unlocked
183233208340SCaitlin Sadowski // mutexes from the lockset, and flag a warning if they are not there.
183318d85aedSAaron Ballman case attr::ReleaseCapability: {
1834bbe25317SEugene Zelenko const auto *A = cast<ReleaseCapabilityAttr>(At);
1835df115d9bSAaron Ballman if (A->isGeneric())
1836df115d9bSAaron Ballman Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1837df115d9bSAaron Ballman else if (A->isShared())
1838df115d9bSAaron Ballman Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1839df115d9bSAaron Ballman else
1840df115d9bSAaron Ballman Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
184133208340SCaitlin Sadowski break;
184233208340SCaitlin Sadowski }
184333208340SCaitlin Sadowski
1844efe348ecSAaron Ballman case attr::RequiresCapability: {
1845bbe25317SEugene Zelenko const auto *A = cast<RequiresCapabilityAttr>(At);
18463c355aa2SDeLesley Hutchins for (auto *Arg : A->args()) {
1847a82eaa70SAaron Ballman warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
1848f8afb8fdSAaron Puchert POK_FunctionCall, Exp->getExprLoc());
18493c355aa2SDeLesley Hutchins // use for adopting a lock
18501850f56cSAaron Puchert if (isScopedVar)
18511850f56cSAaron Puchert Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD);
18523c355aa2SDeLesley Hutchins }
185333208340SCaitlin Sadowski break;
185433208340SCaitlin Sadowski }
185533208340SCaitlin Sadowski
185633208340SCaitlin Sadowski case attr::LocksExcluded: {
1857bbe25317SEugene Zelenko const auto *A = cast<LocksExcludedAttr>(At);
18581850f56cSAaron Puchert for (auto *Arg : A->args()) {
1859f8afb8fdSAaron Puchert warnIfMutexHeld(D, Exp, Arg);
18601850f56cSAaron Puchert // use for deferring a lock
18611850f56cSAaron Puchert if (isScopedVar)
18621850f56cSAaron Puchert Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, VD);
18631850f56cSAaron Puchert }
186433208340SCaitlin Sadowski break;
186533208340SCaitlin Sadowski }
186633208340SCaitlin Sadowski
1867d4733638SAlp Toker // Ignore attributes unrelated to thread-safety
186833208340SCaitlin Sadowski default:
186933208340SCaitlin Sadowski break;
187033208340SCaitlin Sadowski }
187133208340SCaitlin Sadowski }
187209bcefcbSDeLesley Hutchins
18731b58759dSAaron Ballman // Remove locks first to allow lock upgrading/downgrading.
18741b58759dSAaron Ballman // FIXME -- should only fully remove if the attribute refers to 'this'.
18751b58759dSAaron Ballman bool Dtor = isa<CXXDestructorDecl>(D);
18761b58759dSAaron Ballman for (const auto &M : ExclusiveLocksToRemove)
1877f8afb8fdSAaron Puchert Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive);
18781b58759dSAaron Ballman for (const auto &M : SharedLocksToRemove)
1879f8afb8fdSAaron Puchert Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared);
18801b58759dSAaron Ballman for (const auto &M : GenericLocksToRemove)
1881f8afb8fdSAaron Puchert Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic);
18821b58759dSAaron Ballman
188309bcefcbSDeLesley Hutchins // Add locks.
1884530e074fSAaron Puchert FactEntry::SourceKind Source =
1885530e074fSAaron Puchert isScopedVar ? FactEntry::Managed : FactEntry::Acquired;
1886df115d9bSAaron Ballman for (const auto &M : ExclusiveLocksToAdd)
1887f8afb8fdSAaron Puchert Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(M, LK_Exclusive,
1888f8afb8fdSAaron Puchert Loc, Source));
1889df115d9bSAaron Ballman for (const auto &M : SharedLocksToAdd)
1890530e074fSAaron Puchert Analyzer->addLock(
1891f8afb8fdSAaron Puchert FSet, std::make_unique<LockableFactEntry>(M, LK_Shared, Loc, Source));
189209bcefcbSDeLesley Hutchins
189374e0f40dSHaojian Wu if (isScopedVar) {
1894ca988749SEd Schouten // Add the managing object as a dummy mutex, mapped to the underlying mutex.
189509bcefcbSDeLesley Hutchins SourceLocation MLoc = VD->getLocation();
18965fc4db75SBruno Ricci DeclRefExpr DRE(VD->getASTContext(), VD, false, VD->getType(), VK_LValue,
18975fc4db75SBruno Ricci VD->getLocation());
18984266522aSDeLesley Hutchins // FIXME: does this store a pointer to DRE?
18994266522aSDeLesley Hutchins CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
19003c355aa2SDeLesley Hutchins
19012b3d49b6SJonas Devlieghere auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, MLoc);
19021386b59bSAaron Puchert for (const auto &M : ExclusiveLocksToAdd)
19031850f56cSAaron Puchert ScopedEntry->addLock(M);
19041386b59bSAaron Puchert for (const auto &M : SharedLocksToAdd)
19051850f56cSAaron Puchert ScopedEntry->addLock(M);
19061850f56cSAaron Puchert for (const auto &M : ScopedReqsAndExcludes)
19071850f56cSAaron Puchert ScopedEntry->addLock(M);
19081386b59bSAaron Puchert for (const auto &M : ExclusiveLocksToRemove)
19091386b59bSAaron Puchert ScopedEntry->addExclusiveUnlock(M);
19101386b59bSAaron Puchert for (const auto &M : SharedLocksToRemove)
19111386b59bSAaron Puchert ScopedEntry->addSharedUnlock(M);
1912f8afb8fdSAaron Puchert Analyzer->addLock(FSet, std::move(ScopedEntry));
191309bcefcbSDeLesley Hutchins }
191433208340SCaitlin Sadowski }
191533208340SCaitlin Sadowski
19169fc8faf9SAdrian Prantl /// For unary operations which read and write a variable, we need to
1917db917bdeSDeLesley Hutchins /// check whether we hold any required mutexes. Reads are checked in
1918db917bdeSDeLesley Hutchins /// VisitCastExpr.
VisitUnaryOperator(const UnaryOperator * UO)1919cd37c091SAaron Puchert void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
1920db917bdeSDeLesley Hutchins switch (UO->getOpcode()) {
1921bbe25317SEugene Zelenko case UO_PostDec:
1922bbe25317SEugene Zelenko case UO_PostInc:
1923bbe25317SEugene Zelenko case UO_PreDec:
1924bbe25317SEugene Zelenko case UO_PreInc:
19255df82f21SDeLesley Hutchins checkAccess(UO->getSubExpr(), AK_Written);
1926db917bdeSDeLesley Hutchins break;
1927db917bdeSDeLesley Hutchins default:
1928db917bdeSDeLesley Hutchins break;
1929db917bdeSDeLesley Hutchins }
1930db917bdeSDeLesley Hutchins }
1931db917bdeSDeLesley Hutchins
1932db917bdeSDeLesley Hutchins /// For binary operations which assign to a variable (writes), we need to check
1933db917bdeSDeLesley Hutchins /// whether we hold any required mutexes.
1934db917bdeSDeLesley Hutchins /// FIXME: Deal with non-primitive types.
VisitBinaryOperator(const BinaryOperator * BO)1935cd37c091SAaron Puchert void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
1936db917bdeSDeLesley Hutchins if (!BO->isAssignmentOp())
1937db917bdeSDeLesley Hutchins return;
19389b7022e5SDeLesley Hutchins
19399b7022e5SDeLesley Hutchins // adjust the context
19408c9d9579SDeLesley Hutchins LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
19419b7022e5SDeLesley Hutchins
19425df82f21SDeLesley Hutchins checkAccess(BO->getLHS(), AK_Written);
1943db917bdeSDeLesley Hutchins }
1944db917bdeSDeLesley Hutchins
1945db917bdeSDeLesley Hutchins /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1946db917bdeSDeLesley Hutchins /// need to ensure we hold any required mutexes.
1947db917bdeSDeLesley Hutchins /// FIXME: Deal with non-primitive types.
VisitCastExpr(const CastExpr * CE)1948cd37c091SAaron Puchert void BuildLockset::VisitCastExpr(const CastExpr *CE) {
1949db917bdeSDeLesley Hutchins if (CE->getCastKind() != CK_LValueToRValue)
1950db917bdeSDeLesley Hutchins return;
19515df82f21SDeLesley Hutchins checkAccess(CE->getSubExpr(), AK_Read);
1952db917bdeSDeLesley Hutchins }
1953db917bdeSDeLesley Hutchins
examineArguments(const FunctionDecl * FD,CallExpr::const_arg_iterator ArgBegin,CallExpr::const_arg_iterator ArgEnd,bool SkipFirstParam)195435389e51SAaron Puchert void BuildLockset::examineArguments(const FunctionDecl *FD,
195535389e51SAaron Puchert CallExpr::const_arg_iterator ArgBegin,
195635389e51SAaron Puchert CallExpr::const_arg_iterator ArgEnd,
195735389e51SAaron Puchert bool SkipFirstParam) {
195835389e51SAaron Puchert // Currently we can't do anything if we don't know the function declaration.
195935389e51SAaron Puchert if (!FD)
196035389e51SAaron Puchert return;
1961c60dc2cfSDeLesley Hutchins
196235389e51SAaron Puchert // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
196335389e51SAaron Puchert // only turns off checking within the body of a function, but we also
196435389e51SAaron Puchert // use it to turn off checking in arguments to the function. This
196535389e51SAaron Puchert // could result in some false negatives, but the alternative is to
196635389e51SAaron Puchert // create yet another attribute.
196735389e51SAaron Puchert if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
196835389e51SAaron Puchert return;
196935389e51SAaron Puchert
197035389e51SAaron Puchert const ArrayRef<ParmVarDecl *> Params = FD->parameters();
197135389e51SAaron Puchert auto Param = Params.begin();
197235389e51SAaron Puchert if (SkipFirstParam)
197335389e51SAaron Puchert ++Param;
197435389e51SAaron Puchert
197535389e51SAaron Puchert // There can be default arguments, so we stop when one iterator is at end().
197635389e51SAaron Puchert for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd;
197735389e51SAaron Puchert ++Param, ++Arg) {
197835389e51SAaron Puchert QualType Qt = (*Param)->getType();
197935389e51SAaron Puchert if (Qt->isReferenceType())
198035389e51SAaron Puchert checkAccess(*Arg, AK_Read, POK_PassByRef);
198135389e51SAaron Puchert }
198235389e51SAaron Puchert }
198335389e51SAaron Puchert
VisitCallExpr(const CallExpr * Exp)198435389e51SAaron Puchert void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
1985bbe25317SEugene Zelenko if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1986bbe25317SEugene Zelenko const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
1987f489d2b8SDeLesley Hutchins // ME can be null when calling a method pointer
1988bbe25317SEugene Zelenko const CXXMethodDecl *MD = CE->getMethodDecl();
1989f489d2b8SDeLesley Hutchins
1990f489d2b8SDeLesley Hutchins if (ME && MD) {
1991f489d2b8SDeLesley Hutchins if (ME->isArrow()) {
1992c61ae6e6SAaron Puchert // Should perhaps be AK_Written if !MD->isConst().
1993f489d2b8SDeLesley Hutchins checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1994f489d2b8SDeLesley Hutchins } else {
1995c61ae6e6SAaron Puchert // Should perhaps be AK_Written if !MD->isConst().
1996f489d2b8SDeLesley Hutchins checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1997f489d2b8SDeLesley Hutchins }
1998f489d2b8SDeLesley Hutchins }
1999c60dc2cfSDeLesley Hutchins
200035389e51SAaron Puchert examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
200135389e51SAaron Puchert } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
200244ae49e1SAaron Puchert OverloadedOperatorKind OEop = OE->getOperator();
2003c60dc2cfSDeLesley Hutchins switch (OEop) {
200444ae49e1SAaron Puchert case OO_Equal:
200544ae49e1SAaron Puchert case OO_PlusEqual:
200644ae49e1SAaron Puchert case OO_MinusEqual:
200744ae49e1SAaron Puchert case OO_StarEqual:
200844ae49e1SAaron Puchert case OO_SlashEqual:
200944ae49e1SAaron Puchert case OO_PercentEqual:
201044ae49e1SAaron Puchert case OO_CaretEqual:
201144ae49e1SAaron Puchert case OO_AmpEqual:
201244ae49e1SAaron Puchert case OO_PipeEqual:
201344ae49e1SAaron Puchert case OO_LessLessEqual:
201444ae49e1SAaron Puchert case OO_GreaterGreaterEqual:
201544ae49e1SAaron Puchert checkAccess(OE->getArg(1), AK_Read);
201644ae49e1SAaron Puchert LLVM_FALLTHROUGH;
201744ae49e1SAaron Puchert case OO_PlusPlus:
201844ae49e1SAaron Puchert case OO_MinusMinus:
201944ae49e1SAaron Puchert checkAccess(OE->getArg(0), AK_Written);
2020f489d2b8SDeLesley Hutchins break;
20215ede5cc9SDeLesley Hutchins case OO_Star:
202244ae49e1SAaron Puchert case OO_ArrowStar:
2023e73d6b60SDeLesley Hutchins case OO_Arrow:
202435389e51SAaron Puchert case OO_Subscript:
2025c60dc2cfSDeLesley Hutchins if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
2026c60dc2cfSDeLesley Hutchins // Grrr. operator* can be multiplication...
202735389e51SAaron Puchert checkPtAccess(OE->getArg(0), AK_Read);
2028c60dc2cfSDeLesley Hutchins }
202935389e51SAaron Puchert LLVM_FALLTHROUGH;
2030f489d2b8SDeLesley Hutchins default: {
2031c60dc2cfSDeLesley Hutchins // TODO: get rid of this, and rely on pass-by-ref instead.
203205b7b370SDeLesley Hutchins const Expr *Obj = OE->getArg(0);
203305b7b370SDeLesley Hutchins checkAccess(Obj, AK_Read);
203435389e51SAaron Puchert // Check the remaining arguments. For method operators, the first
203535389e51SAaron Puchert // argument is the implicit self argument, and doesn't appear in the
203635389e51SAaron Puchert // FunctionDecl, but for non-methods it does.
203735389e51SAaron Puchert const FunctionDecl *FD = OE->getDirectCallee();
203835389e51SAaron Puchert examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
203935389e51SAaron Puchert /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
2040f489d2b8SDeLesley Hutchins break;
2041f489d2b8SDeLesley Hutchins }
2042f489d2b8SDeLesley Hutchins }
2043c60dc2cfSDeLesley Hutchins } else {
204435389e51SAaron Puchert examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
2045445a31cdSDeLesley Hutchins }
2046c60dc2cfSDeLesley Hutchins
2047bbe25317SEugene Zelenko auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2048db917bdeSDeLesley Hutchins if(!D || !D->hasAttrs())
2049db917bdeSDeLesley Hutchins return;
2050db917bdeSDeLesley Hutchins handleCall(Exp, D);
2051db917bdeSDeLesley Hutchins }
2052db917bdeSDeLesley Hutchins
VisitCXXConstructExpr(const CXXConstructExpr * Exp)2053cd37c091SAaron Puchert void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
2054f489d2b8SDeLesley Hutchins const CXXConstructorDecl *D = Exp->getConstructor();
2055f489d2b8SDeLesley Hutchins if (D && D->isCopyConstructor()) {
2056f489d2b8SDeLesley Hutchins const Expr* Source = Exp->getArg(0);
2057f489d2b8SDeLesley Hutchins checkAccess(Source, AK_Read);
205835389e51SAaron Puchert } else {
205935389e51SAaron Puchert examineArguments(D, Exp->arg_begin(), Exp->arg_end());
2060f489d2b8SDeLesley Hutchins }
2061f7faa6a6SDeLesley Hutchins }
2062f7faa6a6SDeLesley Hutchins
2063e97654b2SRichard Smith static CXXConstructorDecl *
findConstructorForByValueReturn(const CXXRecordDecl * RD)2064e97654b2SRichard Smith findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2065e97654b2SRichard Smith // Prefer a move constructor over a copy constructor. If there's more than
2066e97654b2SRichard Smith // one copy constructor or more than one move constructor, we arbitrarily
2067e97654b2SRichard Smith // pick the first declared such constructor rather than trying to guess which
2068e97654b2SRichard Smith // one is more appropriate.
2069e97654b2SRichard Smith CXXConstructorDecl *CopyCtor = nullptr;
2070bbe25317SEugene Zelenko for (auto *Ctor : RD->ctors()) {
2071e97654b2SRichard Smith if (Ctor->isDeleted())
2072e97654b2SRichard Smith continue;
2073e97654b2SRichard Smith if (Ctor->isMoveConstructor())
2074e97654b2SRichard Smith return Ctor;
2075e97654b2SRichard Smith if (!CopyCtor && Ctor->isCopyConstructor())
2076e97654b2SRichard Smith CopyCtor = Ctor;
2077e97654b2SRichard Smith }
2078e97654b2SRichard Smith return CopyCtor;
2079e97654b2SRichard Smith }
2080e97654b2SRichard Smith
buildFakeCtorCall(CXXConstructorDecl * CD,ArrayRef<Expr * > Args,SourceLocation Loc)2081e97654b2SRichard Smith static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2082e97654b2SRichard Smith SourceLocation Loc) {
2083e97654b2SRichard Smith ASTContext &Ctx = CD->getASTContext();
2084e97654b2SRichard Smith return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2085e97654b2SRichard Smith CD, true, Args, false, false, false, false,
2086e97654b2SRichard Smith CXXConstructExpr::CK_Complete,
2087e97654b2SRichard Smith SourceRange(Loc, Loc));
2088e97654b2SRichard Smith }
2089e97654b2SRichard Smith
VisitDeclStmt(const DeclStmt * S)2090cd37c091SAaron Puchert void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
20919b7022e5SDeLesley Hutchins // adjust the context
20928c9d9579SDeLesley Hutchins LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
20939b7022e5SDeLesley Hutchins
20949ee54d11SAaron Ballman for (auto *D : S->getDeclGroup()) {
2095bbe25317SEugene Zelenko if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2096f7faa6a6SDeLesley Hutchins Expr *E = VD->getInit();
2097e97654b2SRichard Smith if (!E)
2098e97654b2SRichard Smith continue;
2099e97654b2SRichard Smith E = E->IgnoreParens();
21000c1da20bSDeLesley Hutchins
2101e97654b2SRichard Smith // handle constructors that involve temporaries
2102e97654b2SRichard Smith if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
210324485aecSEli Friedman E = EWC->getSubExpr()->IgnoreParens();
210424485aecSEli Friedman if (auto *CE = dyn_cast<CastExpr>(E))
210524485aecSEli Friedman if (CE->getCastKind() == CK_NoOp ||
210624485aecSEli Friedman CE->getCastKind() == CK_ConstructorConversion ||
210724485aecSEli Friedman CE->getCastKind() == CK_UserDefinedConversion)
210824485aecSEli Friedman E = CE->getSubExpr()->IgnoreParens();
2109e97654b2SRichard Smith if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
211024485aecSEli Friedman E = BTE->getSubExpr()->IgnoreParens();
2111e97654b2SRichard Smith
2112bbe25317SEugene Zelenko if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2113bbe25317SEugene Zelenko const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2114f7faa6a6SDeLesley Hutchins if (!CtorD || !CtorD->hasAttrs())
2115e97654b2SRichard Smith continue;
2116e97654b2SRichard Smith handleCall(E, CtorD, VD);
2117aef5d8fdSMatheus Izvekov } else if (isa<CallExpr>(E) && E->isPRValue()) {
2118e97654b2SRichard Smith // If the object is initialized by a function call that returns a
2119e97654b2SRichard Smith // scoped lockable by value, use the attributes on the copy or move
2120e97654b2SRichard Smith // constructor to figure out what effect that should have on the
2121e97654b2SRichard Smith // lockset.
2122e97654b2SRichard Smith // FIXME: Is this really the best way to handle this situation?
2123e97654b2SRichard Smith auto *RD = E->getType()->getAsCXXRecordDecl();
2124e97654b2SRichard Smith if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2125e97654b2SRichard Smith continue;
2126e97654b2SRichard Smith CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2127e97654b2SRichard Smith if (!CtorD || !CtorD->hasAttrs())
2128e97654b2SRichard Smith continue;
2129f2ceec48SStephen Kelly handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
2130f7faa6a6SDeLesley Hutchins }
2131f7faa6a6SDeLesley Hutchins }
2132f7faa6a6SDeLesley Hutchins }
2133db917bdeSDeLesley Hutchins }
2134db917bdeSDeLesley Hutchins
21359b889f82SAaron Puchert /// Given two facts merging on a join point, possibly warn and decide whether to
21369b889f82SAaron Puchert /// keep or replace.
21373d64677cSAaron Puchert ///
21389b889f82SAaron Puchert /// \param CanModify Whether we can replace \p A by \p B.
21399b889f82SAaron Puchert /// \return false if we should keep \p A, true if we should take \p B.
join(const FactEntry & A,const FactEntry & B,bool CanModify)21409b889f82SAaron Puchert bool ThreadSafetyAnalyzer::join(const FactEntry &A, const FactEntry &B,
21419b889f82SAaron Puchert bool CanModify) {
21423d64677cSAaron Puchert if (A.kind() != B.kind()) {
2143cf0b337cSAaron Puchert // For managed capabilities, the destructor should unlock in the right mode
2144cf0b337cSAaron Puchert // anyway. For asserted capabilities no unlocking is needed.
2145cf0b337cSAaron Puchert if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) {
21469b889f82SAaron Puchert // The shared capability subsumes the exclusive capability, if possible.
21479b889f82SAaron Puchert bool ShouldTakeB = B.kind() == LK_Shared;
21489b889f82SAaron Puchert if (CanModify || !ShouldTakeB)
21499b889f82SAaron Puchert return ShouldTakeB;
21509b889f82SAaron Puchert }
2151f8afb8fdSAaron Puchert Handler.handleExclusiveAndShared(B.getKind(), B.toString(), B.loc(),
2152f8afb8fdSAaron Puchert A.loc());
21533d64677cSAaron Puchert // Take the exclusive capability to reduce further warnings.
21549b889f82SAaron Puchert return CanModify && B.kind() == LK_Exclusive;
21553d64677cSAaron Puchert } else {
21563d64677cSAaron Puchert // The non-asserted capability is the one we want to track.
21579b889f82SAaron Puchert return CanModify && A.asserted() && !B.asserted();
21583d64677cSAaron Puchert }
21593d64677cSAaron Puchert }
21603d64677cSAaron Puchert
21619fc8faf9SAdrian Prantl /// Compute the intersection of two locksets and issue warnings for any
2162af9b7c5fSCaitlin Sadowski /// locks in the symmetric difference.
2163af9b7c5fSCaitlin Sadowski ///
2164af9b7c5fSCaitlin Sadowski /// This function is used at a merge point in the CFG when comparing the lockset
2165af9b7c5fSCaitlin Sadowski /// of each branch being merged. For example, given the following sequence:
2166af9b7c5fSCaitlin Sadowski /// A; if () then B; else C; D; we need to check that the lockset after B and C
2167af9b7c5fSCaitlin Sadowski /// are the same. In the event of a difference, we use the intersection of these
2168af9b7c5fSCaitlin Sadowski /// two locksets at the start of D.
2169ebbf7701SDeLesley Hutchins ///
2170e0b90771SAaron Puchert /// \param EntrySet A lockset for entry into a (possibly new) block.
2171e0b90771SAaron Puchert /// \param ExitSet The lockset on exiting a preceding block.
2172ebbf7701SDeLesley Hutchins /// \param JoinLoc The location of the join point for error reporting
2173e0b90771SAaron Puchert /// \param EntryLEK The warning if a mutex is missing from \p EntrySet.
2174e0b90771SAaron Puchert /// \param ExitLEK The warning if a mutex is missing from \p ExitSet.
intersectAndWarn(FactSet & EntrySet,const FactSet & ExitSet,SourceLocation JoinLoc,LockErrorKind EntryLEK,LockErrorKind ExitLEK)2175e0b90771SAaron Puchert void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &EntrySet,
2176e0b90771SAaron Puchert const FactSet &ExitSet,
2177ebbf7701SDeLesley Hutchins SourceLocation JoinLoc,
2178e0b90771SAaron Puchert LockErrorKind EntryLEK,
2179e0b90771SAaron Puchert LockErrorKind ExitLEK) {
2180e0b90771SAaron Puchert FactSet EntrySetOrig = EntrySet;
2181ebbf7701SDeLesley Hutchins
2182e0b90771SAaron Puchert // Find locks in ExitSet that conflict or are not in EntrySet, and warn.
2183e0b90771SAaron Puchert for (const auto &Fact : ExitSet) {
2184e0b90771SAaron Puchert const FactEntry &ExitFact = FactMan[Fact];
2185c9776faaSDeLesley Hutchins
2186e0b90771SAaron Puchert FactSet::iterator EntryIt = EntrySet.findLockIter(FactMan, ExitFact);
2187e0b90771SAaron Puchert if (EntryIt != EntrySet.end()) {
21889b889f82SAaron Puchert if (join(FactMan[*EntryIt], ExitFact,
21899b889f82SAaron Puchert EntryLEK != LEK_LockedSomeLoopIterations))
2190e0b90771SAaron Puchert *EntryIt = Fact;
2191e0b90771SAaron Puchert } else if (!ExitFact.managed()) {
2192e0b90771SAaron Puchert ExitFact.handleRemovalFromIntersection(ExitSet, FactMan, JoinLoc,
2193e0b90771SAaron Puchert EntryLEK, Handler);
219433208340SCaitlin Sadowski }
219533208340SCaitlin Sadowski }
219633208340SCaitlin Sadowski
2197e0b90771SAaron Puchert // Find locks in EntrySet that are not in ExitSet, and remove them.
2198e0b90771SAaron Puchert for (const auto &Fact : EntrySetOrig) {
2199e0b90771SAaron Puchert const FactEntry *EntryFact = &FactMan[Fact];
2200e0b90771SAaron Puchert const FactEntry *ExitFact = ExitSet.findLock(FactMan, *EntryFact);
2201d162c91bSDeLesley Hutchins
2202e0b90771SAaron Puchert if (!ExitFact) {
2203e0b90771SAaron Puchert if (!EntryFact->managed() || ExitLEK == LEK_LockedSomeLoopIterations)
2204e0b90771SAaron Puchert EntryFact->handleRemovalFromIntersection(EntrySetOrig, FactMan, JoinLoc,
2205e0b90771SAaron Puchert ExitLEK, Handler);
2206e0b90771SAaron Puchert if (ExitLEK == LEK_LockedSomePredecessors)
2207e0b90771SAaron Puchert EntrySet.removeLock(FactMan, *EntryFact);
220833208340SCaitlin Sadowski }
220933208340SCaitlin Sadowski }
221033208340SCaitlin Sadowski }
221133208340SCaitlin Sadowski
22129fa426a6SDeLesley Hutchins // Return true if block B never continues to its successors.
neverReturns(const CFGBlock * B)221366a97ee9SBenjamin Kramer static bool neverReturns(const CFGBlock *B) {
22149fa426a6SDeLesley Hutchins if (B->hasNoReturnElement())
22159fa426a6SDeLesley Hutchins return true;
22169fa426a6SDeLesley Hutchins if (B->empty())
22179fa426a6SDeLesley Hutchins return false;
22189fa426a6SDeLesley Hutchins
22199fa426a6SDeLesley Hutchins CFGElement Last = B->back();
222000be69abSDavid Blaikie if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
222100be69abSDavid Blaikie if (isa<CXXThrowExpr>(S->getStmt()))
22229fa426a6SDeLesley Hutchins return true;
22239fa426a6SDeLesley Hutchins }
22249fa426a6SDeLesley Hutchins return false;
22259fa426a6SDeLesley Hutchins }
22269fa426a6SDeLesley Hutchins
22279fc8faf9SAdrian Prantl /// Check a function's CFG for thread-safety violations.
222833208340SCaitlin Sadowski ///
222933208340SCaitlin Sadowski /// We traverse the blocks in the CFG, compute the set of mutexes that are held
223033208340SCaitlin Sadowski /// at the end of each block, and issue warnings for thread safety violations.
223133208340SCaitlin Sadowski /// Each block in the CFG is traversed exactly once.
runAnalysis(AnalysisDeclContext & AC)223281ce1c8aSTed Kremenek void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2233b2213910SDeLesley Hutchins // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2234b2213910SDeLesley Hutchins // For now, we just use the walker to set things up.
2235b2213910SDeLesley Hutchins threadSafety::CFGWalker walker;
2236b2213910SDeLesley Hutchins if (!walker.init(AC))
2237b2213910SDeLesley Hutchins return;
2238a088f67bSDeLesley Hutchins
2239ebbf7701SDeLesley Hutchins // AC.dumpCFG(true);
2240b2213910SDeLesley Hutchins // threadSafety::printSCFG(walker);
2241ebbf7701SDeLesley Hutchins
2242e80bfcd0SAaron Ballman CFG *CFGraph = walker.getGraph();
2243e80bfcd0SAaron Ballman const NamedDecl *D = walker.getDecl();
2244bbe25317SEugene Zelenko const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
22454266522aSDeLesley Hutchins CurrentMethod = dyn_cast<CXXMethodDecl>(D);
2246b2213910SDeLesley Hutchins
22479ead1243SAaron Ballman if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
2248a088f67bSDeLesley Hutchins return;
2249b2213910SDeLesley Hutchins
2250c2286f64SDeLesley Hutchins // FIXME: Do something a bit more intelligent inside constructor and
2251c2286f64SDeLesley Hutchins // destructor code. Constructors and destructors must assume unique access
2252c2286f64SDeLesley Hutchins // to 'this', so checks on member variable access is disabled, but we should
2253c2286f64SDeLesley Hutchins // still enable checks on other objects.
2254c2286f64SDeLesley Hutchins if (isa<CXXConstructorDecl>(D))
2255c2286f64SDeLesley Hutchins return; // Don't check inside constructors.
2256c2286f64SDeLesley Hutchins if (isa<CXXDestructorDecl>(D))
2257c2286f64SDeLesley Hutchins return; // Don't check inside destructors.
225833208340SCaitlin Sadowski
2259eb0ea5f4SDeLesley Hutchins Handler.enterFunction(CurrentFunction);
2260eb0ea5f4SDeLesley Hutchins
22618c9d9579SDeLesley Hutchins BlockInfo.resize(CFGraph->getNumBlockIDs(),
2262c9776faaSDeLesley Hutchins CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
226333208340SCaitlin Sadowski
226433208340SCaitlin Sadowski // We need to explore the CFG via a "topological" ordering.
226533208340SCaitlin Sadowski // That way, we will be guaranteed to have information about required
226633208340SCaitlin Sadowski // predecessor locksets when exploring a new block.
2267e80bfcd0SAaron Ballman const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
22684b4c51c3STed Kremenek PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
226933208340SCaitlin Sadowski
227010958caeSDeLesley Hutchins // Mark entry block as reachable
227110958caeSDeLesley Hutchins BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
227210958caeSDeLesley Hutchins
22739b7022e5SDeLesley Hutchins // Compute SSA names for local variables
22749b7022e5SDeLesley Hutchins LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
22759b7022e5SDeLesley Hutchins
227692286678SRichard Smith // Fill in source locations for all CFGBlocks.
227792286678SRichard Smith findBlockLocations(CFGraph, SortedGraph, BlockInfo);
227892286678SRichard Smith
22794266522aSDeLesley Hutchins CapExprSet ExclusiveLocksAcquired;
22804266522aSDeLesley Hutchins CapExprSet SharedLocksAcquired;
22814266522aSDeLesley Hutchins CapExprSet LocksReleased;
2282fd374bb3SDeLesley Hutchins
22833d312b17SDeLesley Hutchins // Add locks from exclusive_locks_required and shared_locks_required
2284c2286f64SDeLesley Hutchins // to initial lockset. Also turn off checking for lock and unlock functions.
2285c2286f64SDeLesley Hutchins // FIXME: is there a more intelligent way to check lock/unlock functions?
22864b4c51c3STed Kremenek if (!SortedGraph->empty() && D->hasAttrs()) {
22874b4c51c3STed Kremenek const CFGBlock *FirstBlock = *SortedGraph->begin();
2288c9776faaSDeLesley Hutchins FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
228909bcefcbSDeLesley Hutchins
22904266522aSDeLesley Hutchins CapExprSet ExclusiveLocksToAdd;
22914266522aSDeLesley Hutchins CapExprSet SharedLocksToAdd;
229209bcefcbSDeLesley Hutchins
229309bcefcbSDeLesley Hutchins SourceLocation Loc = D->getLocation();
2294ab1dc2d5SDeLesley Hutchins for (const auto *Attr : D->attrs()) {
229509bcefcbSDeLesley Hutchins Loc = Attr->getLocation();
22960491afafSAaron Ballman if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2297efe348ecSAaron Ballman getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
229825542943SCraig Topper nullptr, D);
22990491afafSAaron Ballman } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
2300fd374bb3SDeLesley Hutchins // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2301fd374bb3SDeLesley Hutchins // We must ignore such methods.
2302fd374bb3SDeLesley Hutchins if (A->args_size() == 0)
2303c2286f64SDeLesley Hutchins return;
2304eaa18e60SAaron Ballman getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2305eaa18e60SAaron Ballman nullptr, D);
23060491afafSAaron Ballman getMutexIDs(LocksReleased, A, nullptr, D);
23070491afafSAaron Ballman } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
2308fd374bb3SDeLesley Hutchins if (A->args_size() == 0)
2309fd374bb3SDeLesley Hutchins return;
231018d85aedSAaron Ballman getMutexIDs(A->isShared() ? SharedLocksAcquired
231118d85aedSAaron Ballman : ExclusiveLocksAcquired,
231218d85aedSAaron Ballman A, nullptr, D);
2313c4a6e515SDeLesley Hutchins } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
231481d07fc2SAaron Ballman // Don't try to check trylock functions for now.
2315c4a6e515SDeLesley Hutchins return;
2316c4a6e515SDeLesley Hutchins } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
231781d07fc2SAaron Ballman // Don't try to check trylock functions for now.
231881d07fc2SAaron Ballman return;
231981d07fc2SAaron Ballman } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
232081d07fc2SAaron Ballman // Don't try to check trylock functions for now.
2321c4a6e515SDeLesley Hutchins return;
23226525fb25SCaitlin Sadowski }
23236525fb25SCaitlin Sadowski }
232409bcefcbSDeLesley Hutchins
232509bcefcbSDeLesley Hutchins // FIXME -- Loc can be wrong here.
2326ab1dc2d5SDeLesley Hutchins for (const auto &Mu : ExclusiveLocksToAdd) {
2327530e074fSAaron Puchert auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc,
2328530e074fSAaron Puchert FactEntry::Declared);
2329f8afb8fdSAaron Puchert addLock(InitialLockset, std::move(Entry), true);
2330ab1dc2d5SDeLesley Hutchins }
2331ab1dc2d5SDeLesley Hutchins for (const auto &Mu : SharedLocksToAdd) {
2332530e074fSAaron Puchert auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc,
2333530e074fSAaron Puchert FactEntry::Declared);
2334f8afb8fdSAaron Puchert addLock(InitialLockset, std::move(Entry), true);
2335ab1dc2d5SDeLesley Hutchins }
23366525fb25SCaitlin Sadowski }
23376525fb25SCaitlin Sadowski
2338e80bfcd0SAaron Ballman for (const auto *CurrBlock : *SortedGraph) {
233988d85365SAaron Puchert unsigned CurrBlockID = CurrBlock->getBlockID();
23409b7022e5SDeLesley Hutchins CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
234133208340SCaitlin Sadowski
234233208340SCaitlin Sadowski // Use the default initial lockset in case there are no predecessors.
23439b7022e5SDeLesley Hutchins VisitedBlocks.insert(CurrBlock);
234433208340SCaitlin Sadowski
234533208340SCaitlin Sadowski // Iterate through the predecessor blocks and warn if the lockset for all
234633208340SCaitlin Sadowski // predecessors is not the same. We take the entry lockset of the current
234733208340SCaitlin Sadowski // block to be the intersection of all previous locksets.
234833208340SCaitlin Sadowski // FIXME: By keeping the intersection, we may output more errors in future
234933208340SCaitlin Sadowski // for a lock which is not in the intersection, but was in the union. We
235033208340SCaitlin Sadowski // may want to also keep the union in future. As an example, let's say
235133208340SCaitlin Sadowski // the intersection contains Mutex L, and the union contains L and M.
235233208340SCaitlin Sadowski // Later we unlock M. At this point, we would output an error because we
235333208340SCaitlin Sadowski // never locked M; although the real error is probably that we forgot to
235433208340SCaitlin Sadowski // lock M on all code paths. Conversely, let's say that later we lock M.
235533208340SCaitlin Sadowski // In this case, we should compare against the intersection instead of the
235633208340SCaitlin Sadowski // union because the real error is probably that we forgot to unlock M on
235733208340SCaitlin Sadowski // all code paths.
235833208340SCaitlin Sadowski bool LocksetInitialized = false;
235933208340SCaitlin Sadowski for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
236033208340SCaitlin Sadowski PE = CurrBlock->pred_end(); PI != PE; ++PI) {
236133208340SCaitlin Sadowski // if *PI -> CurrBlock is a back edge
23620491afafSAaron Ballman if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
236333208340SCaitlin Sadowski continue;
236433208340SCaitlin Sadowski
236588d85365SAaron Puchert unsigned PrevBlockID = (*PI)->getBlockID();
236610958caeSDeLesley Hutchins CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
236710958caeSDeLesley Hutchins
2368a2587ef2SDeLesley Hutchins // Ignore edges from blocks that can't return.
23699fa426a6SDeLesley Hutchins if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
2370a2587ef2SDeLesley Hutchins continue;
2371a2587ef2SDeLesley Hutchins
237210958caeSDeLesley Hutchins // Okay, we can reach this block from the entry.
237310958caeSDeLesley Hutchins CurrBlockInfo->Reachable = true;
237410958caeSDeLesley Hutchins
2375c9776faaSDeLesley Hutchins FactSet PrevLockset;
2376c9776faaSDeLesley Hutchins getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
23779b7022e5SDeLesley Hutchins
237833208340SCaitlin Sadowski if (!LocksetInitialized) {
2379ebbf7701SDeLesley Hutchins CurrBlockInfo->EntrySet = PrevLockset;
238033208340SCaitlin Sadowski LocksetInitialized = true;
238133208340SCaitlin Sadowski } else {
23826de19ea4SAaron Puchert // Surprisingly 'continue' doesn't always produce back edges, because
23836de19ea4SAaron Puchert // the CFG has empty "transition" blocks where they meet with the end
23846de19ea4SAaron Puchert // of the regular loop body. We still want to diagnose them as loop.
23856de19ea4SAaron Puchert intersectAndWarn(
23866de19ea4SAaron Puchert CurrBlockInfo->EntrySet, PrevLockset, CurrBlockInfo->EntryLoc,
23876de19ea4SAaron Puchert isa_and_nonnull<ContinueStmt>((*PI)->getTerminatorStmt())
23886de19ea4SAaron Puchert ? LEK_LockedSomeLoopIterations
23896de19ea4SAaron Puchert : LEK_LockedSomePredecessors);
239033208340SCaitlin Sadowski }
239133208340SCaitlin Sadowski }
239233208340SCaitlin Sadowski
239310958caeSDeLesley Hutchins // Skip rest of block if it's not reachable.
239410958caeSDeLesley Hutchins if (!CurrBlockInfo->Reachable)
239510958caeSDeLesley Hutchins continue;
239610958caeSDeLesley Hutchins
23978c9d9579SDeLesley Hutchins BuildLockset LocksetBuilder(this, *CurrBlockInfo);
23988c9d9579SDeLesley Hutchins
23999b7022e5SDeLesley Hutchins // Visit all the statements in the basic block.
2400bbe25317SEugene Zelenko for (const auto &BI : *CurrBlock) {
2401bbe25317SEugene Zelenko switch (BI.getKind()) {
2402f893e8abSDeLesley Hutchins case CFGElement::Statement: {
2403bbe25317SEugene Zelenko CFGStmt CS = BI.castAs<CFGStmt>();
2404cd37c091SAaron Puchert LocksetBuilder.Visit(CS.getStmt());
2405f893e8abSDeLesley Hutchins break;
2406f893e8abSDeLesley Hutchins }
2407f893e8abSDeLesley Hutchins // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2408f893e8abSDeLesley Hutchins case CFGElement::AutomaticObjectDtor: {
2409bbe25317SEugene Zelenko CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
2410cd37c091SAaron Puchert const auto *DD = AD.getDestructorDecl(AC.getASTContext());
2411f893e8abSDeLesley Hutchins if (!DD->hasAttrs())
2412f893e8abSDeLesley Hutchins break;
2413f893e8abSDeLesley Hutchins
2414f893e8abSDeLesley Hutchins // Create a dummy expression,
2415bbe25317SEugene Zelenko auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
24165fc4db75SBruno Ricci DeclRefExpr DRE(VD->getASTContext(), VD, false,
24175fc4db75SBruno Ricci VD->getType().getNonReferenceType(), VK_LValue,
24185fc4db75SBruno Ricci AD.getTriggerStmt()->getEndLoc());
2419f893e8abSDeLesley Hutchins LocksetBuilder.handleCall(&DRE, DD);
2420f893e8abSDeLesley Hutchins break;
2421f893e8abSDeLesley Hutchins }
2422f893e8abSDeLesley Hutchins default:
2423f893e8abSDeLesley Hutchins break;
2424f893e8abSDeLesley Hutchins }
242533208340SCaitlin Sadowski }
2426c9776faaSDeLesley Hutchins CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
242733208340SCaitlin Sadowski
242833208340SCaitlin Sadowski // For every back edge from CurrBlock (the end of the loop) to another block
242933208340SCaitlin Sadowski // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
243033208340SCaitlin Sadowski // the one held at the beginning of FirstLoopBlock. We can look up the
243133208340SCaitlin Sadowski // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
243233208340SCaitlin Sadowski for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
243333208340SCaitlin Sadowski SE = CurrBlock->succ_end(); SI != SE; ++SI) {
243433208340SCaitlin Sadowski // if CurrBlock -> *SI is *not* a back edge
243525542943SCraig Topper if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
243633208340SCaitlin Sadowski continue;
243733208340SCaitlin Sadowski
243833208340SCaitlin Sadowski CFGBlock *FirstLoopBlock = *SI;
2439ebbf7701SDeLesley Hutchins CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2440ebbf7701SDeLesley Hutchins CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2441f664e2ecSAaron Puchert intersectAndWarn(PreLoop->EntrySet, LoopEnd->ExitSet, PreLoop->EntryLoc,
2442d21e1b79SAaron Puchert LEK_LockedSomeLoopIterations);
244333208340SCaitlin Sadowski }
244433208340SCaitlin Sadowski }
244533208340SCaitlin Sadowski
2446ebbf7701SDeLesley Hutchins CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2447ebbf7701SDeLesley Hutchins CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
2448086fb95dSCaitlin Sadowski
244910958caeSDeLesley Hutchins // Skip the final check if the exit block is unreachable.
245010958caeSDeLesley Hutchins if (!Final->Reachable)
245110958caeSDeLesley Hutchins return;
245210958caeSDeLesley Hutchins
2453fd374bb3SDeLesley Hutchins // By default, we expect all locks held on entry to be held on exit.
2454fd374bb3SDeLesley Hutchins FactSet ExpectedExitSet = Initial->EntrySet;
2455fd374bb3SDeLesley Hutchins
2456fd374bb3SDeLesley Hutchins // Adjust the expected exit set by adding or removing locks, as declared
2457fd374bb3SDeLesley Hutchins // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2458fd374bb3SDeLesley Hutchins // issue the appropriate warning.
2459fd374bb3SDeLesley Hutchins // FIXME: the location here is not quite right.
24600491afafSAaron Ballman for (const auto &Lock : ExclusiveLocksAcquired)
24612b3d49b6SJonas Devlieghere ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2462ca988749SEd Schouten Lock, LK_Exclusive, D->getLocation()));
24630491afafSAaron Ballman for (const auto &Lock : SharedLocksAcquired)
24642b3d49b6SJonas Devlieghere ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2465ca988749SEd Schouten Lock, LK_Shared, D->getLocation()));
24660491afafSAaron Ballman for (const auto &Lock : LocksReleased)
24670491afafSAaron Ballman ExpectedExitSet.removeLock(FactMan, Lock);
2468fd374bb3SDeLesley Hutchins
2469086fb95dSCaitlin Sadowski // FIXME: Should we call this function for all blocks which exit the function?
2470d21e1b79SAaron Puchert intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
2471d21e1b79SAaron Puchert LEK_LockedAtEndOfFunction, LEK_NotLockedAtEndOfFunction);
2472eb0ea5f4SDeLesley Hutchins
2473eb0ea5f4SDeLesley Hutchins Handler.leaveFunction(CurrentFunction);
24743d312b17SDeLesley Hutchins }
24753d312b17SDeLesley Hutchins
24769fc8faf9SAdrian Prantl /// Check a function's CFG for thread-safety violations.
24773d312b17SDeLesley Hutchins ///
24783d312b17SDeLesley Hutchins /// We traverse the blocks in the CFG, compute the set of mutexes that are held
24793d312b17SDeLesley Hutchins /// at the end of each block, and issue warnings for thread safety violations.
24803d312b17SDeLesley Hutchins /// Each block in the CFG is traversed exactly once.
runThreadSafetyAnalysis(AnalysisDeclContext & AC,ThreadSafetyHandler & Handler,BeforeSet ** BSet)248166a97ee9SBenjamin Kramer void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2482ab1dc2d5SDeLesley Hutchins ThreadSafetyHandler &Handler,
2483ab1dc2d5SDeLesley Hutchins BeforeSet **BSet) {
2484ab1dc2d5SDeLesley Hutchins if (!*BSet)
2485ab1dc2d5SDeLesley Hutchins *BSet = new BeforeSet;
2486ab1dc2d5SDeLesley Hutchins ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
24873d312b17SDeLesley Hutchins Analyzer.runAnalysis(AC);
248833208340SCaitlin Sadowski }
248933208340SCaitlin Sadowski
threadSafetyCleanup(BeforeSet * Cache)249066a97ee9SBenjamin Kramer void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
2491ab1dc2d5SDeLesley Hutchins
24929fc8faf9SAdrian Prantl /// Helper function that returns a LockKind required for the given level
249333208340SCaitlin Sadowski /// of access.
getLockKindFromAccessKind(AccessKind AK)249466a97ee9SBenjamin Kramer LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
249533208340SCaitlin Sadowski switch (AK) {
249633208340SCaitlin Sadowski case AK_Read :
249733208340SCaitlin Sadowski return LK_Shared;
249833208340SCaitlin Sadowski case AK_Written :
249933208340SCaitlin Sadowski return LK_Exclusive;
250033208340SCaitlin Sadowski }
25018a8051f2SBenjamin Kramer llvm_unreachable("Unknown AccessKind");
250233208340SCaitlin Sadowski }
2503