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