blob: a8c17d5070dca9a09857a2902d25bf2ffef47df9 [file] [log] [blame]
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001//===- ThreadSafety.cpp ---------------------------------------------------===//
Caitlin Sadowski33208342011-09-09 16:11:56 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// A intra-procedural analysis for thread safety (e.g. deadlocks and race
11// conditions), based off of an annotation system.
12//
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000013// See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
Aaron Ballmanfcd5b7e2013-06-26 19:17:19 +000014// for more information.
Caitlin Sadowski33208342011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
Mehdi Amini9670f842016-07-18 19:02:11 +000018#include "clang/Analysis/Analyses/ThreadSafety.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000019#include "clang/AST/Attr.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000020#include "clang/AST/Decl.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000021#include "clang/AST/DeclCXX.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000022#include "clang/AST/DeclGroup.h"
23#include "clang/AST/Expr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000024#include "clang/AST/ExprCXX.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000025#include "clang/AST/OperationKinds.h"
26#include "clang/AST/Stmt.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000027#include "clang/AST/StmtVisitor.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000028#include "clang/AST/Type.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000030#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000031#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000032#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000033#include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
George Karpenkov50657f62017-09-06 21:45:03 +000034#include "clang/Analysis/AnalysisDeclContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Analysis/CFG.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000036#include "clang/Basic/LLVM.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000037#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000038#include "clang/Basic/SourceLocation.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000039#include "clang/Basic/Specifiers.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseMap.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000042#include "llvm/ADT/ImmutableMap.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000043#include "llvm/ADT/Optional.h"
44#include "llvm/ADT/STLExtras.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000045#include "llvm/ADT/SmallVector.h"
46#include "llvm/ADT/StringRef.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000047#include "llvm/Support/Allocator.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/ErrorHandling.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000050#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000051#include <algorithm>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000052#include <cassert>
53#include <functional>
54#include <iterator>
55#include <memory>
56#include <string>
57#include <type_traits>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000058#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000059#include <vector>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000060
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000061using namespace clang;
62using namespace threadSafety;
Caitlin Sadowski33208342011-09-09 16:11:56 +000063
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000064// Key method definition
Eugene Zelenkobbe25312018-03-16 21:22:42 +000065ThreadSafetyHandler::~ThreadSafetyHandler() = default;
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000066
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000067namespace {
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000068
Eugene Zelenkobbe25312018-03-16 21:22:42 +000069class TILPrinter :
70 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
71
72} // namespace
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000073
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000074/// Issue a warning about an invalid lock expression
75static void warnInvalidLock(ThreadSafetyHandler &Handler,
76 const Expr *MutexExp, const NamedDecl *D,
77 const Expr *DeclExp, StringRef Kind) {
78 SourceLocation Loc;
79 if (DeclExp)
80 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000081
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000082 // FIXME: add a note about the attribute location in MutexExp or D
83 if (Loc.isValid())
84 Handler.handleInvalidLockExp(Kind, Loc);
85}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000086
Eugene Zelenkobbe25312018-03-16 21:22:42 +000087namespace {
88
Haojian Wu74e0f402018-08-13 12:50:30 +000089/// A set of CapabilityInfo objects, which are compiled from the
90/// requires attributes on a function.
DeLesley Hutchins42665222014-08-04 16:10:59 +000091class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000092public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000093 /// Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000094 void push_back_nodup(const CapabilityExpr &CapE) {
95 iterator It = std::find_if(begin(), end(),
96 [=](const CapabilityExpr &CapE2) {
97 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000098 });
99 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +0000100 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000101 }
102};
103
Ed Schoutenca988742014-09-03 06:00:11 +0000104class FactManager;
105class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000107/// This is a helper class that stores a fact that is known at a
DeLesley Hutchins42665222014-08-04 16:10:59 +0000108/// particular point in program execution. Currently, a fact is a capability,
109/// along with additional information, such as where it was acquired, whether
110/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +0000111///
Aaron Ballman1b587592018-07-26 13:03:16 +0000112/// FIXME: this analysis does not currently support re-entrant locking.
DeLesley Hutchins42665222014-08-04 16:10:59 +0000113class FactEntry : public CapabilityExpr {
114private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000115 /// Exclusive or shared.
116 LockKind LKind;
117
118 /// Where it was acquired.
119 SourceLocation AcquireLoc;
120
121 /// True if the lock was asserted.
122 bool Asserted;
123
124 /// True if the lock was declared.
125 bool Declared;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000126
DeLesley Hutchins42665222014-08-04 16:10:59 +0000127public:
128 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000129 bool Asrt, bool Declrd = false)
130 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
131 Declared(Declrd) {}
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000132 virtual ~FactEntry() = default;
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000133
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000134 LockKind kind() const { return LKind; }
135 SourceLocation loc() const { return AcquireLoc; }
136 bool asserted() const { return Asserted; }
137 bool declared() const { return Declared; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000138
139 void setDeclared(bool D) { Declared = D; }
Ed Schoutenca988742014-09-03 06:00:11 +0000140
141 virtual void
142 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
143 SourceLocation JoinLoc, LockErrorKind LEK,
144 ThreadSafetyHandler &Handler) const = 0;
145 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
146 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
147 bool FullyRemove, ThreadSafetyHandler &Handler,
148 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000149
DeLesley Hutchins42665222014-08-04 16:10:59 +0000150 // Return true if LKind >= LK, where exclusive > shared
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000151 bool isAtLeast(LockKind LK) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000152 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000153 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000154};
155
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000156using FactID = unsigned short;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000157
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000158/// FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000159/// the analysis of a single routine.
160class FactManager {
161private:
Ed Schoutenca988742014-09-03 06:00:11 +0000162 std::vector<std::unique_ptr<FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000163
164public:
Ed Schoutenca988742014-09-03 06:00:11 +0000165 FactID newFact(std::unique_ptr<FactEntry> Entry) {
166 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000167 return static_cast<unsigned short>(Facts.size() - 1);
168 }
169
Ed Schoutenca988742014-09-03 06:00:11 +0000170 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
171 FactEntry &operator[](FactID F) { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000172};
173
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000174/// A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000175/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000176/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000177/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000178/// locks, so we can get away with doing a linear search for lookup. Note
179/// that a hashtable or map is inappropriate in this case, because lookups
180/// may involve partial pattern matches, rather than exact matches.
181class FactSet {
182private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000183 using FactVec = SmallVector<FactID, 4>;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000184
185 FactVec FactIDs;
186
187public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000188 using iterator = FactVec::iterator;
189 using const_iterator = FactVec::const_iterator;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000190
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000191 iterator begin() { return FactIDs.begin(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000192 const_iterator begin() const { return FactIDs.begin(); }
193
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000194 iterator end() { return FactIDs.end(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000195 const_iterator end() const { return FactIDs.end(); }
196
197 bool isEmpty() const { return FactIDs.size() == 0; }
198
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000199 // Return true if the set contains only negative facts
200 bool isEmpty(FactManager &FactMan) const {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000201 for (const auto FID : *this) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000202 if (!FactMan[FID].negative())
203 return false;
204 }
205 return true;
206 }
207
208 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
209
Ed Schoutenca988742014-09-03 06:00:11 +0000210 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
211 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000212 FactIDs.push_back(F);
213 return F;
214 }
215
DeLesley Hutchins42665222014-08-04 16:10:59 +0000216 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000217 unsigned n = FactIDs.size();
218 if (n == 0)
219 return false;
220
221 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000222 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000223 FactIDs[i] = FactIDs[n-1];
224 FactIDs.pop_back();
225 return true;
226 }
227 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000228 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000229 FactIDs.pop_back();
230 return true;
231 }
232 return false;
233 }
234
DeLesley Hutchins42665222014-08-04 16:10:59 +0000235 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000236 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000237 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000238 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000239 }
240
DeLesley Hutchins42665222014-08-04 16:10:59 +0000241 FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000242 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000243 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000244 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000245 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000246 }
247
DeLesley Hutchins42665222014-08-04 16:10:59 +0000248 FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000249 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000250 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000251 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000252 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000253 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000254
DeLesley Hutchins42665222014-08-04 16:10:59 +0000255 FactEntry *findPartialMatch(FactManager &FM,
256 const CapabilityExpr &CapE) const {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000257 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000258 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000259 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000260 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000261 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000262
263 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
264 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
265 return FM[ID].valueDecl() == Vd;
266 });
267 return I != end();
268 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000269};
270
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000271class ThreadSafetyAnalyzer;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000272
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000273} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000274
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000275namespace clang {
276namespace threadSafety {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000277
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000278class BeforeSet {
279private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000280 using BeforeVect = SmallVector<const ValueDecl *, 4>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000281
282 struct BeforeInfo {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000283 BeforeVect Vect;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000284 int Visited = 0;
285
286 BeforeInfo() = default;
287 BeforeInfo(BeforeInfo &&) = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000288 };
289
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000290 using BeforeMap =
291 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
292 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000293
294public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000295 BeforeSet() = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000296
297 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
298 ThreadSafetyAnalyzer& Analyzer);
299
Reid Kleckner19ff5602015-11-20 19:08:30 +0000300 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
301 ThreadSafetyAnalyzer &Analyzer);
302
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000303 void checkBeforeAfter(const ValueDecl* Vd,
304 const FactSet& FSet,
305 ThreadSafetyAnalyzer& Analyzer,
306 SourceLocation Loc, StringRef CapKind);
307
308private:
309 BeforeMap BMap;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000310 CycleMap CycMap;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000311};
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000312
313} // namespace threadSafety
314} // namespace clang
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000315
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000316namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000317
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000318class LocalVariableMap;
319
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000320using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
321
Richard Smith92286672012-02-03 04:45:26 +0000322/// A side (entry or exit) of a CFG node.
323enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000324
325/// CFGBlockInfo is a struct which contains all the information that is
326/// maintained for each block in the CFG. See LocalVariableMap for more
327/// information about the contexts.
328struct CFGBlockInfo {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000329 // Lockset held at entry to block
330 FactSet EntrySet;
331
332 // Lockset held at exit from block
333 FactSet ExitSet;
334
335 // Context held at entry to block
336 LocalVarContext EntryContext;
337
338 // Context held at exit from block
339 LocalVarContext ExitContext;
340
341 // Location of first statement in block
342 SourceLocation EntryLoc;
343
344 // Location of last statement in block.
345 SourceLocation ExitLoc;
346
347 // Used to replay contexts later
348 unsigned EntryIndex;
349
350 // Is this block reachable?
351 bool Reachable = false;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000352
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000353 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000354 return Side == CBS_Entry ? EntrySet : ExitSet;
355 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000356
Richard Smith92286672012-02-03 04:45:26 +0000357 SourceLocation getLocation(CFGBlockSide Side) const {
358 return Side == CBS_Entry ? EntryLoc : ExitLoc;
359 }
360
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000361private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000362 CFGBlockInfo(LocalVarContext EmptyCtx)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000363 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000364
365public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000366 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000367};
368
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000369// A LocalVariableMap maintains a map from local variables to their currently
370// valid definitions. It provides SSA-like functionality when traversing the
371// CFG. Like SSA, each definition or assignment to a variable is assigned a
372// unique name (an integer), which acts as the SSA name for that definition.
373// The total set of names is shared among all CFG basic blocks.
374// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
375// with their SSA-names. Instead, we compute a Context for each point in the
376// code, which maps local variables to the appropriate SSA-name. This map
377// changes with each assignment.
378//
379// The map is computed in a single pass over the CFG. Subsequent analyses can
380// then query the map to find the appropriate Context for a statement, and use
381// that Context to look up the definitions of variables.
382class LocalVariableMap {
383public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000384 using Context = LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000385
386 /// A VarDefinition consists of an expression, representing the value of the
387 /// variable, along with the context in which that expression should be
388 /// interpreted. A reference VarDefinition does not itself contain this
389 /// information, but instead contains a pointer to a previous VarDefinition.
390 struct VarDefinition {
391 public:
392 friend class LocalVariableMap;
393
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000394 // The original declaration for this variable.
395 const NamedDecl *Dec;
396
397 // The expression for this variable, OR
398 const Expr *Exp = nullptr;
399
400 // Reference to another VarDefinition
401 unsigned Ref = 0;
402
403 // The map with which Exp should be interpreted.
404 Context Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000405
406 bool isReference() { return !Exp; }
407
408 private:
409 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000410 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000411 : Dec(D), Exp(E), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000412
413 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000414 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000415 : Dec(D), Ref(R), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000416 };
417
418private:
419 Context::Factory ContextFactory;
420 std::vector<VarDefinition> VarDefinitions;
421 std::vector<unsigned> CtxIndices;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000422 std::vector<std::pair<Stmt *, Context>> SavedContexts;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000423
424public:
425 LocalVariableMap() {
426 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000427 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000428 }
429
430 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000431 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000432 const unsigned *i = Ctx.lookup(D);
433 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000434 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000435 assert(*i < VarDefinitions.size());
436 return &VarDefinitions[*i];
437 }
438
439 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000440 /// NULL if the expression is not statically known. If successful, also
441 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000442 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000443 const unsigned *P = Ctx.lookup(D);
444 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000445 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000446
447 unsigned i = *P;
448 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000449 if (VarDefinitions[i].Exp) {
450 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000451 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000452 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000453 i = VarDefinitions[i].Ref;
454 }
Craig Topper25542942014-05-20 04:30:07 +0000455 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000456 }
457
458 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
459
460 /// Return the next context after processing S. This function is used by
461 /// clients of the class to get the appropriate context when traversing the
462 /// CFG. It must be called for every assignment or DeclStmt.
463 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
464 if (SavedContexts[CtxIndex+1].first == S) {
465 CtxIndex++;
466 Context Result = SavedContexts[CtxIndex].second;
467 return Result;
468 }
469 return C;
470 }
471
472 void dumpVarDefinitionName(unsigned i) {
473 if (i == 0) {
474 llvm::errs() << "Undefined";
475 return;
476 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000477 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000478 if (!Dec) {
479 llvm::errs() << "<<NULL>>";
480 return;
481 }
482 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000483 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000484 }
485
486 /// Dumps an ASCII representation of the variable map to llvm::errs()
487 void dump() {
488 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000489 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000490 unsigned Ref = VarDefinitions[i].Ref;
491
492 dumpVarDefinitionName(i);
493 llvm::errs() << " = ";
494 if (Exp) Exp->dump();
495 else {
496 dumpVarDefinitionName(Ref);
497 llvm::errs() << "\n";
498 }
499 }
500 }
501
502 /// Dumps an ASCII representation of a Context to llvm::errs()
503 void dumpContext(Context C) {
504 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000505 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000506 D->printName(llvm::errs());
507 const unsigned *i = C.lookup(D);
508 llvm::errs() << " -> ";
509 dumpVarDefinitionName(*i);
510 llvm::errs() << "\n";
511 }
512 }
513
514 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000515 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
516 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000517
518protected:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000519 friend class VarMapBuilder;
520
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000521 // Get the current context index
522 unsigned getContextIndex() { return SavedContexts.size()-1; }
523
524 // Save the current context for later replay
525 void saveContext(Stmt *S, Context C) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000526 SavedContexts.push_back(std::make_pair(S, C));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000527 }
528
529 // Adds a new definition to the given context, and returns a new context.
530 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000531 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000532 assert(!Ctx.contains(D));
533 unsigned newID = VarDefinitions.size();
534 Context NewCtx = ContextFactory.add(Ctx, D, newID);
535 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
536 return NewCtx;
537 }
538
539 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000540 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000541 unsigned newID = VarDefinitions.size();
542 Context NewCtx = ContextFactory.add(Ctx, D, newID);
543 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
544 return NewCtx;
545 }
546
547 // Updates a definition only if that definition is already in the map.
548 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000549 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000550 if (Ctx.contains(D)) {
551 unsigned newID = VarDefinitions.size();
552 Context NewCtx = ContextFactory.remove(Ctx, D);
553 NewCtx = ContextFactory.add(NewCtx, D, newID);
554 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
555 return NewCtx;
556 }
557 return Ctx;
558 }
559
560 // Removes a definition from the context, but keeps the variable name
561 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000562 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000563 Context NewCtx = Ctx;
564 if (NewCtx.contains(D)) {
565 NewCtx = ContextFactory.remove(NewCtx, D);
566 NewCtx = ContextFactory.add(NewCtx, D, 0);
567 }
568 return NewCtx;
569 }
570
571 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000572 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000573 Context NewCtx = Ctx;
574 if (NewCtx.contains(D)) {
575 NewCtx = ContextFactory.remove(NewCtx, D);
576 }
577 return NewCtx;
578 }
579
580 Context intersectContexts(Context C1, Context C2);
581 Context createReferenceContext(Context C);
582 void intersectBackEdge(Context C1, Context C2);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000583};
584
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000585} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000586
587// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000588CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
589 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000590}
591
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000592namespace {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000593
594/// Visitor which builds a LocalVariableMap
595class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
596public:
597 LocalVariableMap* VMap;
598 LocalVariableMap::Context Ctx;
599
600 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000601 : VMap(VM), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000602
603 void VisitDeclStmt(DeclStmt *S);
604 void VisitBinaryOperator(BinaryOperator *BO);
605};
606
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000607} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000608
609// Add new local variables to the variable map
610void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
611 bool modifiedCtx = false;
612 DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000613 for (const auto *D : DGrp) {
614 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
615 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000616
617 // Add local variables with trivial type to the variable map
618 QualType T = VD->getType();
619 if (T.isTrivialType(VD->getASTContext())) {
620 Ctx = VMap->addDefinition(VD, E, Ctx);
621 modifiedCtx = true;
622 }
623 }
624 }
625 if (modifiedCtx)
626 VMap->saveContext(S, Ctx);
627}
628
629// Update local variable definitions in variable map
630void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
631 if (!BO->isAssignmentOp())
632 return;
633
634 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
635
636 // Update the variable map and current context.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000637 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
638 const ValueDecl *VDec = DRE->getDecl();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000639 if (Ctx.lookup(VDec)) {
640 if (BO->getOpcode() == BO_Assign)
641 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
642 else
643 // FIXME -- handle compound assignment operators
644 Ctx = VMap->clearDefinition(VDec, Ctx);
645 VMap->saveContext(BO, Ctx);
646 }
647 }
648}
649
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000650// Computes the intersection of two contexts. The intersection is the
651// set of variables which have the same definition in both contexts;
652// variables with different definitions are discarded.
653LocalVariableMap::Context
654LocalVariableMap::intersectContexts(Context C1, Context C2) {
655 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000656 for (const auto &P : C1) {
657 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000658 const unsigned *i2 = C2.lookup(Dec);
659 if (!i2) // variable doesn't exist on second path
660 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000661 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000662 Result = clearDefinition(Dec, Result);
663 }
664 return Result;
665}
666
667// For every variable in C, create a new variable that refers to the
668// definition in C. Return a new context that contains these new variables.
669// (We use this for a naive implementation of SSA on loop back-edges.)
670LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
671 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000672 for (const auto &P : C)
673 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000674 return Result;
675}
676
677// This routine also takes the intersection of C1 and C2, but it does so by
678// altering the VarDefinitions. C1 must be the result of an earlier call to
679// createReferenceContext.
680void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000681 for (const auto &P : C1) {
682 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000683 VarDefinition *VDef = &VarDefinitions[i1];
684 assert(VDef->isReference());
685
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000686 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000687 if (!i2 || (*i2 != i1))
688 VDef->Ref = 0; // Mark this variable as undefined
689 }
690}
691
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000692// Traverse the CFG in topological order, so all predecessors of a block
693// (excluding back-edges) are visited before the block itself. At
694// each point in the code, we calculate a Context, which holds the set of
695// variable definitions which are visible at that point in execution.
696// Visible variables are mapped to their definitions using an array that
697// contains all definitions.
698//
699// At join points in the CFG, the set is computed as the intersection of
700// the incoming sets along each edge, E.g.
701//
702// { Context | VarDefinitions }
703// int x = 0; { x -> x1 | x1 = 0 }
704// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
705// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
706// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
707// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
708//
709// This is essentially a simpler and more naive version of the standard SSA
710// algorithm. Those definitions that remain in the intersection are from blocks
711// that strictly dominate the current block. We do not bother to insert proper
712// phi nodes, because they are not used in our analysis; instead, wherever
713// a phi node would be required, we simply remove that definition from the
714// context (E.g. x above).
715//
716// The initial traversal does not capture back-edges, so those need to be
717// handled on a separate pass. Whenever the first pass encounters an
718// incoming back edge, it duplicates the context, creating new definitions
719// that refer back to the originals. (These correspond to places where SSA
720// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000721// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000722// node was actually required.) E.g.
723//
724// { Context | VarDefinitions }
725// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
726// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
727// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
728// ... { y -> y1 | x3 = 2, x2 = 1, ... }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000729void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000730 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000731 std::vector<CFGBlockInfo> &BlockInfo) {
732 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
733
734 CtxIndices.resize(CFGraph->getNumBlockIDs());
735
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000736 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000737 int CurrBlockID = CurrBlock->getBlockID();
738 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
739
740 VisitedBlocks.insert(CurrBlock);
741
742 // Calculate the entry context for the current block
743 bool HasBackEdges = false;
744 bool CtxInit = true;
745 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
746 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
747 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000748 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000749 HasBackEdges = true;
750 continue;
751 }
752
753 int PrevBlockID = (*PI)->getBlockID();
754 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
755
756 if (CtxInit) {
757 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
758 CtxInit = false;
759 }
760 else {
761 CurrBlockInfo->EntryContext =
762 intersectContexts(CurrBlockInfo->EntryContext,
763 PrevBlockInfo->ExitContext);
764 }
765 }
766
767 // Duplicate the context if we have back-edges, so we can call
768 // intersectBackEdges later.
769 if (HasBackEdges)
770 CurrBlockInfo->EntryContext =
771 createReferenceContext(CurrBlockInfo->EntryContext);
772
773 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000774 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000775 CurrBlockInfo->EntryIndex = getContextIndex();
776
777 // Visit all the statements in the basic block.
778 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000779 for (const auto &BI : *CurrBlock) {
780 switch (BI.getKind()) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000781 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000782 CFGStmt CS = BI.castAs<CFGStmt>();
783 VMapBuilder.Visit(const_cast<Stmt *>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000784 break;
785 }
786 default:
787 break;
788 }
789 }
790 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
791
792 // Mark variables on back edges as "unknown" if they've been changed.
793 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
794 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
795 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000796 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000797 continue;
798
799 CFGBlock *FirstLoopBlock = *SI;
800 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
801 Context LoopEnd = CurrBlockInfo->ExitContext;
802 intersectBackEdge(LoopBegin, LoopEnd);
803 }
804 }
805
806 // Put an extra entry at the end of the indexed context array
807 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000808 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000809}
810
Richard Smith92286672012-02-03 04:45:26 +0000811/// Find the appropriate source locations to use when producing diagnostics for
812/// each block in the CFG.
813static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000814 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000815 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000816 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000817 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
818
819 // Find the source location of the last statement in the block, if the
820 // block is not empty.
821 if (const Stmt *S = CurrBlock->getTerminator()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000822 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000823 } else {
824 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
825 BE = CurrBlock->rend(); BI != BE; ++BI) {
826 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000827 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000828 CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000829 break;
830 }
831 }
832 }
833
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000834 if (CurrBlockInfo->ExitLoc.isValid()) {
Richard Smith92286672012-02-03 04:45:26 +0000835 // This block contains at least one statement. Find the source location
836 // of the first statement in the block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000837 for (const auto &BI : *CurrBlock) {
Richard Smith92286672012-02-03 04:45:26 +0000838 // FIXME: Handle other CFGElement kinds.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000839 if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000840 CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000841 break;
842 }
843 }
844 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
845 CurrBlock != &CFGraph->getExit()) {
846 // The block is empty, and has a single predecessor. Use its exit
847 // location.
848 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
849 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
850 }
851 }
852}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000853
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000854namespace {
855
Ed Schoutenca988742014-09-03 06:00:11 +0000856class LockableFactEntry : public FactEntry {
857private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000858 /// managed by ScopedLockable object
859 bool Managed;
Ed Schoutenca988742014-09-03 06:00:11 +0000860
861public:
862 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
863 bool Mng = false, bool Asrt = false)
864 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
865
866 void
867 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
868 SourceLocation JoinLoc, LockErrorKind LEK,
869 ThreadSafetyHandler &Handler) const override {
870 if (!Managed && !asserted() && !negative() && !isUniversal()) {
871 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
872 LEK);
873 }
874 }
875
876 void handleUnlock(FactSet &FSet, FactManager &FactMan,
877 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
878 bool FullyRemove, ThreadSafetyHandler &Handler,
879 StringRef DiagKind) const override {
880 FSet.removeLock(FactMan, Cp);
881 if (!Cp.negative()) {
882 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
883 !Cp, LK_Exclusive, UnlockLoc));
884 }
885 }
886};
887
888class ScopedLockableFactEntry : public FactEntry {
889private:
890 SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
891
892public:
893 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
894 const CapExprSet &Excl, const CapExprSet &Shrd)
895 : FactEntry(CE, LK_Exclusive, Loc, false) {
896 for (const auto &M : Excl)
897 UnderlyingMutexes.push_back(M.sexpr());
898 for (const auto &M : Shrd)
899 UnderlyingMutexes.push_back(M.sexpr());
900 }
901
902 void
903 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
904 SourceLocation JoinLoc, LockErrorKind LEK,
905 ThreadSafetyHandler &Handler) const override {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000906 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
Ed Schoutenca988742014-09-03 06:00:11 +0000907 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
908 // If this scoped lock manages another mutex, and if the underlying
909 // mutex is still held, then warn about the underlying mutex.
910 Handler.handleMutexHeldEndOfScope(
911 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
912 }
913 }
914 }
915
916 void handleUnlock(FactSet &FSet, FactManager &FactMan,
917 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
918 bool FullyRemove, ThreadSafetyHandler &Handler,
919 StringRef DiagKind) const override {
920 assert(!Cp.negative() && "Managing object cannot be negative.");
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000921 for (const auto *UnderlyingMutex : UnderlyingMutexes) {
Ed Schoutenca988742014-09-03 06:00:11 +0000922 CapabilityExpr UnderCp(UnderlyingMutex, false);
923 auto UnderEntry = llvm::make_unique<LockableFactEntry>(
924 !UnderCp, LK_Exclusive, UnlockLoc);
925
926 if (FullyRemove) {
927 // We're destroying the managing object.
928 // Remove the underlying mutex if it exists; but don't warn.
929 if (FSet.findLock(FactMan, UnderCp)) {
930 FSet.removeLock(FactMan, UnderCp);
931 FSet.addLock(FactMan, std::move(UnderEntry));
932 }
933 } else {
934 // We're releasing the underlying mutex, but not destroying the
935 // managing object. Warn on dual release.
936 if (!FSet.findLock(FactMan, UnderCp)) {
937 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
938 UnlockLoc);
939 }
940 FSet.removeLock(FactMan, UnderCp);
941 FSet.addLock(FactMan, std::move(UnderEntry));
942 }
943 }
944 if (FullyRemove)
945 FSet.removeLock(FactMan, Cp);
946 }
947};
948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000949/// Class which implements the core thread safety analysis routines.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000950class ThreadSafetyAnalyzer {
951 friend class BuildLockset;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000952 friend class threadSafety::BeforeSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000953
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000954 llvm::BumpPtrAllocator Bpa;
955 threadSafety::til::MemRegionRef Arena;
956 threadSafety::SExprBuilder SxBuilder;
957
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000958 ThreadSafetyHandler &Handler;
959 const CXXMethodDecl *CurrentMethod;
960 LocalVariableMap LocalVarMap;
961 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000962 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000963
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000964 BeforeSet *GlobalBeforeSet;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000965
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000966public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000967 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000968 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000969
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000970 bool inCurrentScope(const CapabilityExpr &CapE);
971
Ed Schoutenca988742014-09-03 06:00:11 +0000972 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
973 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +0000974 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000975 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
976 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000977
978 template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000979 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +0000980 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000981
982 template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000983 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000984 const NamedDecl *D,
985 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
986 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000987
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000988 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
989 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000990
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000991 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
992 const CFGBlock* PredBlock,
993 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +0000994
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000995 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
996 SourceLocation JoinLoc,
997 LockErrorKind LEK1, LockErrorKind LEK2,
998 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000999
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001000 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1001 SourceLocation JoinLoc, LockErrorKind LEK1,
1002 bool Modify=true) {
1003 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001004 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001005
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001006 void runAnalysis(AnalysisDeclContext &AC);
1007};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001008
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001009} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001010
1011/// Process acquired_before and acquired_after attributes on Vd.
1012BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1013 ThreadSafetyAnalyzer& Analyzer) {
1014 // Create a new entry for Vd.
Reid Kleckner19ff5602015-11-20 19:08:30 +00001015 BeforeInfo *Info = nullptr;
1016 {
1017 // Keep InfoPtr in its own scope in case BMap is modified later and the
1018 // reference becomes invalid.
1019 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1020 if (!InfoPtr)
1021 InfoPtr.reset(new BeforeInfo());
1022 Info = InfoPtr.get();
1023 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001024
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001025 for (const auto *At : Vd->attrs()) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001026 switch (At->getKind()) {
1027 case attr::AcquiredBefore: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001028 const auto *A = cast<AcquiredBeforeAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001029
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001030 // Read exprs from the attribute, and add them to BeforeVect.
1031 for (const auto *Arg : A->args()) {
1032 CapabilityExpr Cp =
1033 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1034 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
Reid Kleckner19ff5602015-11-20 19:08:30 +00001035 Info->Vect.push_back(Cpvd);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001036 const auto It = BMap.find(Cpvd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001037 if (It == BMap.end())
1038 insertAttrExprs(Cpvd, Analyzer);
1039 }
1040 }
1041 break;
1042 }
1043 case attr::AcquiredAfter: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001044 const auto *A = cast<AcquiredAfterAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001045
1046 // Read exprs from the attribute, and add them to BeforeVect.
1047 for (const auto *Arg : A->args()) {
1048 CapabilityExpr Cp =
1049 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1050 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1051 // Get entry for mutex listed in attribute
Reid Kleckner19ff5602015-11-20 19:08:30 +00001052 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1053 ArgInfo->Vect.push_back(Vd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001054 }
1055 }
1056 break;
1057 }
1058 default:
1059 break;
1060 }
1061 }
1062
1063 return Info;
1064}
1065
Reid Kleckner19ff5602015-11-20 19:08:30 +00001066BeforeSet::BeforeInfo *
1067BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1068 ThreadSafetyAnalyzer &Analyzer) {
1069 auto It = BMap.find(Vd);
1070 BeforeInfo *Info = nullptr;
1071 if (It == BMap.end())
1072 Info = insertAttrExprs(Vd, Analyzer);
1073 else
1074 Info = It->second.get();
1075 assert(Info && "BMap contained nullptr?");
1076 return Info;
1077}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001078
1079/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1080void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1081 const FactSet& FSet,
1082 ThreadSafetyAnalyzer& Analyzer,
1083 SourceLocation Loc, StringRef CapKind) {
1084 SmallVector<BeforeInfo*, 8> InfoVect;
1085
1086 // Do a depth-first traversal of Vd.
1087 // Return true if there are cycles.
1088 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1089 if (!Vd)
1090 return false;
1091
Reid Kleckner19ff5602015-11-20 19:08:30 +00001092 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001093
1094 if (Info->Visited == 1)
1095 return true;
1096
1097 if (Info->Visited == 2)
1098 return false;
1099
Reid Kleckner19ff5602015-11-20 19:08:30 +00001100 if (Info->Vect.empty())
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001101 return false;
1102
1103 InfoVect.push_back(Info);
1104 Info->Visited = 1;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001105 for (const auto *Vdb : Info->Vect) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001106 // Exclude mutexes in our immediate before set.
1107 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1108 StringRef L1 = StartVd->getName();
1109 StringRef L2 = Vdb->getName();
1110 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1111 }
1112 // Transitively search other before sets, and warn on cycles.
1113 if (traverse(Vdb)) {
1114 if (CycMap.find(Vd) == CycMap.end()) {
1115 CycMap.insert(std::make_pair(Vd, true));
1116 StringRef L1 = Vd->getName();
1117 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1118 }
1119 }
1120 }
1121 Info->Visited = 2;
1122 return false;
1123 };
1124
1125 traverse(StartVd);
1126
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001127 for (auto *Info : InfoVect)
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001128 Info->Visited = 0;
1129}
1130
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001131/// Gets the value decl pointer from DeclRefExprs or MemberExprs.
Aaron Ballmane0449042014-04-01 21:43:23 +00001132static const ValueDecl *getValueDecl(const Expr *Exp) {
1133 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1134 return getValueDecl(CE->getSubExpr());
1135
1136 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1137 return DR->getDecl();
1138
1139 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1140 return ME->getMemberDecl();
1141
1142 return nullptr;
1143}
1144
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001145namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001146
Aaron Ballmane0449042014-04-01 21:43:23 +00001147template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001148class has_arg_iterator_range {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001149 using yes = char[1];
1150 using no = char[2];
Aaron Ballmane0449042014-04-01 21:43:23 +00001151
1152 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001153 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001154
1155 template <typename>
1156 static no& test(...);
1157
1158public:
1159 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1160};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001161
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001162} // namespace
Aaron Ballmane0449042014-04-01 21:43:23 +00001163
1164static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1165 return A->getName();
1166}
1167
1168static StringRef ClassifyDiagnostic(QualType VDT) {
1169 // We need to look at the declaration of the type of the value to determine
1170 // which it is. The type should either be a record or a typedef, or a pointer
1171 // or reference thereof.
1172 if (const auto *RT = VDT->getAs<RecordType>()) {
1173 if (const auto *RD = RT->getDecl())
1174 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1175 return ClassifyDiagnostic(CA);
1176 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1177 if (const auto *TD = TT->getDecl())
1178 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1179 return ClassifyDiagnostic(CA);
1180 } else if (VDT->isPointerType() || VDT->isReferenceType())
1181 return ClassifyDiagnostic(VDT->getPointeeType());
1182
1183 return "mutex";
1184}
1185
1186static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1187 assert(VD && "No ValueDecl passed");
1188
1189 // The ValueDecl is the declaration of a mutex or role (hopefully).
1190 return ClassifyDiagnostic(VD->getType());
1191}
1192
1193template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001194static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001195 StringRef>::type
1196ClassifyDiagnostic(const AttrTy *A) {
1197 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1198 return ClassifyDiagnostic(VD);
1199 return "mutex";
1200}
1201
1202template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001203static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001204 StringRef>::type
1205ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001206 for (const auto *Arg : A->args()) {
1207 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001208 return ClassifyDiagnostic(VD);
1209 }
1210 return "mutex";
1211}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001212
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001213bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001214 if (!CurrentMethod)
1215 return false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001216 if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1217 const auto *VD = P->clangDecl();
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001218 if (VD)
1219 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1220 }
1221 return false;
1222}
1223
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001224/// Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001225/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001226void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1227 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001228 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001229 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001230 return;
1231
Ed Schoutenca988742014-09-03 06:00:11 +00001232 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001233 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001234 CapabilityExpr NegC = !*Entry;
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001235 FactEntry *Nen = FSet.findLock(FactMan, NegC);
1236 if (Nen) {
1237 FSet.removeLock(FactMan, NegC);
1238 }
1239 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001240 if (inCurrentScope(*Entry) && !Entry->asserted())
1241 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1242 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001243 }
1244 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001245
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001246 // Check before/after constraints
1247 if (Handler.issueBetaWarnings() &&
1248 !Entry->asserted() && !Entry->declared()) {
1249 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1250 Entry->loc(), DiagKind);
1251 }
1252
DeLesley Hutchins42665222014-08-04 16:10:59 +00001253 // FIXME: Don't always warn when we have support for reentrant locks.
Ed Schoutenca988742014-09-03 06:00:11 +00001254 if (FSet.findLock(FactMan, *Entry)) {
1255 if (!Entry->asserted())
1256 Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001257 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001258 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001259 }
1260}
1261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001262/// Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001263/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001264void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001265 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001266 bool FullyRemove, LockKind ReceivedKind,
1267 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001268 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001269 return;
1270
DeLesley Hutchins42665222014-08-04 16:10:59 +00001271 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001272 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001273 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001274 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001275 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001276
Aaron Ballmandf115d92014-03-21 14:48:48 +00001277 // Generic lock removal doesn't care about lock kind mismatches, but
1278 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001279 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1280 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1281 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001282 }
1283
Ed Schoutenca988742014-09-03 06:00:11 +00001284 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1285 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001286}
1287
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001288/// Extract the list of mutexIDs from the attribute on an expression,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001289/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001290template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001291void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001292 Expr *Exp, const NamedDecl *D,
1293 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001294 if (Attr->args_size() == 0) {
1295 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001296 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1297 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001298 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1299 return;
1300 }
1301 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001302 if (!Cp.shouldIgnore())
1303 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001304 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001305 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001306
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001307 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001308 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1309 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001310 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001311 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001312 }
1313 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001314 if (!Cp.shouldIgnore())
1315 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001316 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001317}
1318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001319/// Extract the list of mutexIDs from a trylock attribute. If the
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001320/// trylock applies to the given edge, then push them onto Mtxs, discarding
1321/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001322template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001323void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001324 Expr *Exp, const NamedDecl *D,
1325 const CFGBlock *PredBlock,
1326 const CFGBlock *CurrBlock,
1327 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001328 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001329 bool branch = false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001330 if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001331 branch = BLE->getValue();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001332 else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001333 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001334
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001335 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001336 if (Neg)
1337 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001338
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001339 // If we've taken the trylock branch, then add the lock
1340 int i = 0;
1341 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1342 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001343 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001344 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001345 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001346}
1347
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001348static bool getStaticBooleanValue(Expr *E, bool &TCond) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001349 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1350 TCond = false;
1351 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001352 } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001353 TCond = BLE->getValue();
1354 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001355 } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001356 TCond = ILE->getValue().getBoolValue();
1357 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001358 } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001359 return getStaticBooleanValue(CE->getSubExpr(), TCond);
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001360 return false;
1361}
1362
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001363// If Cond can be traced back to a function call, return the call expression.
1364// The negate variable should be called with false, and will be set to true
1365// if the function call is negated, e.g. if (!mu.tryLock(...))
1366const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1367 LocalVarContext C,
1368 bool &Negate) {
1369 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001370 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001371
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001372 if (const auto *CallExp = dyn_cast<CallExpr>(Cond))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001373 return CallExp;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001374 else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001375 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001376 else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001377 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001378 else if (const auto *EWC = dyn_cast<ExprWithCleanups>(Cond))
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001379 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001380 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001381 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1382 return getTrylockCallExpr(E, C, Negate);
1383 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001384 else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001385 if (UOP->getOpcode() == UO_LNot) {
1386 Negate = !Negate;
1387 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1388 }
Craig Topper25542942014-05-20 04:30:07 +00001389 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001390 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001391 else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001392 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1393 if (BOP->getOpcode() == BO_NE)
1394 Negate = !Negate;
1395
1396 bool TCond = false;
1397 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1398 if (!TCond) Negate = !Negate;
1399 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1400 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001401 TCond = false;
1402 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001403 if (!TCond) Negate = !Negate;
1404 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1405 }
Craig Topper25542942014-05-20 04:30:07 +00001406 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001407 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001408 if (BOP->getOpcode() == BO_LAnd) {
1409 // LHS must have been evaluated in a different block.
1410 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1411 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001412 if (BOP->getOpcode() == BO_LOr)
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001413 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
Craig Topper25542942014-05-20 04:30:07 +00001414 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001415 }
Craig Topper25542942014-05-20 04:30:07 +00001416 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001417}
1418
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001419/// Find the lockset that holds on the edge between PredBlock
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001420/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1421/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001422void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1423 const FactSet &ExitSet,
1424 const CFGBlock *PredBlock,
1425 const CFGBlock *CurrBlock) {
1426 Result = ExitSet;
1427
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001428 const Stmt *Cond = PredBlock->getTerminatorCondition();
1429 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001430 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001431
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001432 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001433 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1434 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001435 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001436
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001437 auto *Exp = const_cast<CallExpr *>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001438 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001439 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001440
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001441 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001442 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001443 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001444
DeLesley Hutchins42665222014-08-04 16:10:59 +00001445 CapExprSet ExclusiveLocksToAdd;
1446 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001447
1448 // If the condition is a call to a Trylock function, then grab the attributes
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001449 for (const auto *Attr : FunDecl->attrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001450 switch (Attr->getKind()) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00001451 case attr::TryAcquireCapability: {
1452 auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1453 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1454 Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1455 Negate);
1456 CapDiagKind = ClassifyDiagnostic(A);
1457 break;
1458 };
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001459 case attr::ExclusiveTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001460 const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001461 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1462 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001463 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001464 break;
1465 }
1466 case attr::SharedTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001467 const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001468 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001469 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001470 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001471 break;
1472 }
1473 default:
1474 break;
1475 }
1476 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001477
1478 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001479 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001480 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001481 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1482 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001483 CapDiagKind);
1484 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001485 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1486 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001487 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001488}
1489
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001490namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001492/// We use this class to visit different types of expressions in
Caitlin Sadowski33208342011-09-09 16:11:56 +00001493/// CFGBlocks, and build up the lockset.
1494/// An expression may cause us to add or remove locks from the lockset, or else
1495/// output error messages related to missing locks.
1496/// FIXME: In future, we may be able to not inherit from a visitor.
1497class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001498 friend class ThreadSafetyAnalyzer;
1499
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001500 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001501 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001502 LocalVariableMap::Context LVarCtx;
1503 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001504
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001505 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001506 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001507 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001508 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001509 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1510 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001511
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001512 void checkAccess(const Expr *Exp, AccessKind AK,
1513 ProtectedOperationKind POK = POK_VarAccess);
1514 void checkPtAccess(const Expr *Exp, AccessKind AK,
1515 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001516
Craig Topper25542942014-05-20 04:30:07 +00001517 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001518
Caitlin Sadowski33208342011-09-09 16:11:56 +00001519public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001520 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001521 : StmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
1522 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001523
1524 void VisitUnaryOperator(UnaryOperator *UO);
1525 void VisitBinaryOperator(BinaryOperator *BO);
1526 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001527 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001528 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001529 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001530};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001531
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001532} // namespace
DeLesley Hutchins42665222014-08-04 16:10:59 +00001533
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001534/// Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001535/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001536void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001537 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001538 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001539 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001540 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001541
DeLesley Hutchins42665222014-08-04 16:10:59 +00001542 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1543 if (Cp.isInvalid()) {
1544 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001545 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001546 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001547 return;
1548 }
1549
DeLesley Hutchins42665222014-08-04 16:10:59 +00001550 if (Cp.negative()) {
1551 // Negative capabilities act like locks excluded
1552 FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1553 if (LDat) {
1554 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001555 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001556 return;
1557 }
1558
1559 // If this does not refer to a negative capability in the same class,
1560 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001561 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001562 return;
1563
1564 // Otherwise the negative requirement must be propagated to the caller.
1565 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1566 if (!LDat) {
1567 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001568 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001569 }
1570 return;
1571 }
1572
1573 FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001574 bool NoError = true;
1575 if (!LDat) {
1576 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001577 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1578 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001579 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001580 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001581 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001582 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1583 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001584 } else {
1585 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001586 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1587 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001588 }
1589 NoError = false;
1590 }
1591 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001592 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001593 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1594 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001595 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001596}
1597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001598/// Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001599void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001600 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001601 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1602 if (Cp.isInvalid()) {
1603 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1604 return;
1605 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001606 return;
1607 }
1608
DeLesley Hutchins42665222014-08-04 16:10:59 +00001609 FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
1610 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001611 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001612 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1613 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001614}
1615
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001616/// Checks guarded_by and pt_guarded_by attributes.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001617/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1618/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1619/// Similarly, we check if the access is to an expression that dereferences
1620/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001621void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1622 ProtectedOperationKind POK) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00001623 Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001624
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001625 SourceLocation Loc = Exp->getExprLoc();
1626
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001627 // Local variables of reference type cannot be re-assigned;
1628 // map them to their initializer.
1629 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1630 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1631 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1632 if (const auto *E = VD->getInit()) {
1633 Exp = E;
1634 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001635 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001636 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001637 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001638 }
1639
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001640 if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001641 // For dereferences
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001642 if (UO->getOpcode() == UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001643 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001644 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001645 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001646
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001647 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001648 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001649 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001650 }
1651
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001652 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001653 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001654 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001655 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001656 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001657 }
1658
Caitlin Sadowski33208342011-09-09 16:11:56 +00001659 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001660 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001661 return;
1662
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001663 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001664 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001665 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001666
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001667 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001668 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001669 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001670}
1671
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001672/// Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001673/// POK is the same operationKind that was passed to checkAccess.
1674void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1675 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001676 while (true) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001677 if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001678 Exp = PE->getSubExpr();
1679 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001680 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001681 if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001682 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1683 // If it's an actual array, and not a pointer, then it's elements
1684 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001685 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001686 return;
1687 }
1688 Exp = CE->getSubExpr();
1689 continue;
1690 }
1691 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001692 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001693
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001694 // Pass by reference warnings are under a different flag.
1695 ProtectedOperationKind PtPOK = POK_VarDereference;
1696 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1697
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001698 const ValueDecl *D = getValueDecl(Exp);
1699 if (!D || !D->hasAttrs())
1700 return;
1701
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001702 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001703 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001704 Exp->getExprLoc());
1705
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001706 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001707 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001708 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001709}
1710
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001711/// Process a function call, method call, constructor call,
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001712/// or destructor call. This involves looking at the attributes on the
1713/// corresponding function/method/constructor/destructor, issuing warnings,
1714/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001715///
1716/// FIXME: For classes annotated with one of the guarded annotations, we need
1717/// to treat const method calls as reads and non-const method calls as writes,
1718/// and check that the appropriate locks are held. Non-const method calls with
1719/// the same signature as const method calls can be also treated as reads.
1720///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001721void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001722 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001723 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1724 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001725 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
Aaron Ballmane0449042014-04-01 21:43:23 +00001726 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001727
Richard Smithe97654b2018-01-11 22:13:57 +00001728 // Figure out if we're constructing an object of scoped lockable class
Haojian Wu74e0f402018-08-13 12:50:30 +00001729 bool isScopedVar = false;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001730 if (VD) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001731 if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001732 const CXXRecordDecl* PD = CD->getParent();
1733 if (PD && PD->hasAttr<ScopedLockableAttr>())
Haojian Wu74e0f402018-08-13 12:50:30 +00001734 isScopedVar = true;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001735 }
1736 }
1737
Aaron Ballman1b587592018-07-26 13:03:16 +00001738 for(const Attr *At : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001739 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001740 // When we encounter a lock function, we need to add the lock to our
1741 // lockset.
1742 case attr::AcquireCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001743 const auto *A = cast<AcquireCapabilityAttr>(At);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001744 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1745 : ExclusiveLocksToAdd,
1746 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001747
1748 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001749 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001750 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001751
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001752 // An assert will add a lock to the lockset, but will not generate
1753 // a warning if it is already there, and will not generate a warning
1754 // if it is not removed.
1755 case attr::AssertExclusiveLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001756 const auto *A = cast<AssertExclusiveLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001757
DeLesley Hutchins42665222014-08-04 16:10:59 +00001758 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001759 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001760 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001761 Analyzer->addLock(FSet,
1762 llvm::make_unique<LockableFactEntry>(
1763 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001764 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001765 break;
1766 }
1767 case attr::AssertSharedLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001768 const auto *A = cast<AssertSharedLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001769
DeLesley Hutchins42665222014-08-04 16:10:59 +00001770 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001771 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001772 for (const auto &AssertLock : AssertLocks)
Josh Gaoec1369e2017-08-08 19:44:34 +00001773 Analyzer->addLock(FSet,
1774 llvm::make_unique<LockableFactEntry>(
1775 AssertLock, LK_Shared, Loc, false, true),
1776 ClassifyDiagnostic(A));
1777 break;
1778 }
1779
1780 case attr::AssertCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001781 const auto *A = cast<AssertCapabilityAttr>(At);
Josh Gaoec1369e2017-08-08 19:44:34 +00001782 CapExprSet AssertLocks;
1783 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1784 for (const auto &AssertLock : AssertLocks)
1785 Analyzer->addLock(FSet,
1786 llvm::make_unique<LockableFactEntry>(
1787 AssertLock,
1788 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1789 false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001790 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001791 break;
1792 }
1793
Caitlin Sadowski33208342011-09-09 16:11:56 +00001794 // When we encounter an unlock function, we need to remove unlocked
1795 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001796 case attr::ReleaseCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001797 const auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001798 if (A->isGeneric())
1799 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1800 else if (A->isShared())
1801 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1802 else
1803 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001804
1805 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001806 break;
1807 }
1808
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001809 case attr::RequiresCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001810 const auto *A = cast<RequiresCapabilityAttr>(At);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001811 for (auto *Arg : A->args()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001812 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001813 POK_FunctionCall, ClassifyDiagnostic(A),
1814 Exp->getExprLoc());
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001815 // use for adopting a lock
Haojian Wu74e0f402018-08-13 12:50:30 +00001816 if (isScopedVar) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001817 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1818 : ScopedExclusiveReqs,
1819 A, Exp, D, VD);
1820 }
1821 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001822 break;
1823 }
1824
1825 case attr::LocksExcluded: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001826 const auto *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001827 for (auto *Arg : A->args())
1828 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001829 break;
1830 }
1831
Alp Tokerd4733632013-12-05 04:47:09 +00001832 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001833 default:
1834 break;
1835 }
1836 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001837
Aaron Ballman1b587592018-07-26 13:03:16 +00001838 // Remove locks first to allow lock upgrading/downgrading.
1839 // FIXME -- should only fully remove if the attribute refers to 'this'.
1840 bool Dtor = isa<CXXDestructorDecl>(D);
1841 for (const auto &M : ExclusiveLocksToRemove)
1842 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1843 for (const auto &M : SharedLocksToRemove)
1844 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1845 for (const auto &M : GenericLocksToRemove)
1846 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1847
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001848 // Add locks.
Haojian Wu74e0f402018-08-13 12:50:30 +00001849 for (const auto &M : ExclusiveLocksToAdd)
1850 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1851 M, LK_Exclusive, Loc, isScopedVar),
1852 CapDiagKind);
1853 for (const auto &M : SharedLocksToAdd)
1854 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1855 M, LK_Shared, Loc, isScopedVar),
1856 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001857
Haojian Wu74e0f402018-08-13 12:50:30 +00001858 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001859 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001860 SourceLocation MLoc = VD->getLocation();
1861 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001862 // FIXME: does this store a pointer to DRE?
1863 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001864
1865 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1866 std::back_inserter(ExclusiveLocksToAdd));
1867 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1868 std::back_inserter(SharedLocksToAdd));
Ed Schoutenca988742014-09-03 06:00:11 +00001869 Analyzer->addLock(FSet,
1870 llvm::make_unique<ScopedLockableFactEntry>(
1871 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1872 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001873 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001874}
1875
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001876/// For unary operations which read and write a variable, we need to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001877/// check whether we hold any required mutexes. Reads are checked in
1878/// VisitCastExpr.
1879void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1880 switch (UO->getOpcode()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001881 case UO_PostDec:
1882 case UO_PostInc:
1883 case UO_PreDec:
1884 case UO_PreInc:
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001885 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001886 break;
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001887 default:
1888 break;
1889 }
1890}
1891
1892/// For binary operations which assign to a variable (writes), we need to check
1893/// whether we hold any required mutexes.
1894/// FIXME: Deal with non-primitive types.
1895void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1896 if (!BO->isAssignmentOp())
1897 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001898
1899 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001900 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001901
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001902 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001903}
1904
1905/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1906/// need to ensure we hold any required mutexes.
1907/// FIXME: Deal with non-primitive types.
1908void BuildLockset::VisitCastExpr(CastExpr *CE) {
1909 if (CE->getCastKind() != CK_LValueToRValue)
1910 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001911 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001912}
1913
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001914void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001915 bool ExamineArgs = true;
1916 bool OperatorFun = false;
1917
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001918 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1919 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001920 // ME can be null when calling a method pointer
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001921 const CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001922
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001923 if (ME && MD) {
1924 if (ME->isArrow()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001925 if (MD->isConst())
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001926 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001927 else // FIXME -- should be AK_Written
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001928 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001929 } else {
1930 if (MD->isConst())
1931 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1932 else // FIXME -- should be AK_Written
1933 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001934 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001935 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001936 } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001937 OperatorFun = true;
1938
1939 auto OEop = OE->getOperator();
1940 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001941 case OO_Equal: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001942 ExamineArgs = false;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001943 const Expr *Target = OE->getArg(0);
1944 const Expr *Source = OE->getArg(1);
1945 checkAccess(Target, AK_Written);
1946 checkAccess(Source, AK_Read);
1947 break;
1948 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001949 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001950 case OO_Arrow:
1951 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001952 const Expr *Obj = OE->getArg(0);
1953 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001954 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1955 // Grrr. operator* can be multiplication...
1956 checkPtAccess(Obj, AK_Read);
1957 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001958 break;
1959 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001960 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001961 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001962 const Expr *Obj = OE->getArg(0);
1963 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001964 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001965 }
1966 }
1967 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001968
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001969 if (ExamineArgs) {
1970 if (FunctionDecl *FD = Exp->getDirectCallee()) {
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001971 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
1972 // only turns off checking within the body of a function, but we also
1973 // use it to turn off checking in arguments to the function. This
1974 // could result in some false negatives, but the alternative is to
1975 // create yet another attribute.
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001976 if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
1977 unsigned Fn = FD->getNumParams();
1978 unsigned Cn = Exp->getNumArgs();
1979 unsigned Skip = 0;
1980
1981 unsigned i = 0;
1982 if (OperatorFun) {
1983 if (isa<CXXMethodDecl>(FD)) {
1984 // First arg in operator call is implicit self argument,
1985 // and doesn't appear in the FunctionDecl.
1986 Skip = 1;
1987 Cn--;
1988 } else {
1989 // Ignore the first argument of operators; it's been checked above.
1990 i = 1;
1991 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001992 }
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001993 // Ignore default arguments
1994 unsigned n = (Fn < Cn) ? Fn : Cn;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001995
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001996 for (; i < n; ++i) {
1997 ParmVarDecl* Pvd = FD->getParamDecl(i);
1998 Expr* Arg = Exp->getArg(i+Skip);
1999 QualType Qt = Pvd->getType();
2000 if (Qt->isReferenceType())
2001 checkAccess(Arg, AK_Read, POK_PassByRef);
2002 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002003 }
2004 }
2005 }
2006
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002007 auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002008 if(!D || !D->hasAttrs())
2009 return;
2010 handleCall(Exp, D);
2011}
2012
2013void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002014 const CXXConstructorDecl *D = Exp->getConstructor();
2015 if (D && D->isCopyConstructor()) {
2016 const Expr* Source = Exp->getArg(0);
2017 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002018 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002019 // FIXME -- only handles constructors in DeclStmt below.
2020}
2021
Richard Smithe97654b2018-01-11 22:13:57 +00002022static CXXConstructorDecl *
2023findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2024 // Prefer a move constructor over a copy constructor. If there's more than
2025 // one copy constructor or more than one move constructor, we arbitrarily
2026 // pick the first declared such constructor rather than trying to guess which
2027 // one is more appropriate.
2028 CXXConstructorDecl *CopyCtor = nullptr;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002029 for (auto *Ctor : RD->ctors()) {
Richard Smithe97654b2018-01-11 22:13:57 +00002030 if (Ctor->isDeleted())
2031 continue;
2032 if (Ctor->isMoveConstructor())
2033 return Ctor;
2034 if (!CopyCtor && Ctor->isCopyConstructor())
2035 CopyCtor = Ctor;
2036 }
2037 return CopyCtor;
2038}
2039
2040static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2041 SourceLocation Loc) {
2042 ASTContext &Ctx = CD->getASTContext();
2043 return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2044 CD, true, Args, false, false, false, false,
2045 CXXConstructExpr::CK_Complete,
2046 SourceRange(Loc, Loc));
2047}
2048
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002049void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002050 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002051 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002052
Aaron Ballman9ee54d12014-05-14 20:42:13 +00002053 for (auto *D : S->getDeclGroup()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002054 if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002055 Expr *E = VD->getInit();
Richard Smithe97654b2018-01-11 22:13:57 +00002056 if (!E)
2057 continue;
2058 E = E->IgnoreParens();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002059
Richard Smithe97654b2018-01-11 22:13:57 +00002060 // handle constructors that involve temporaries
2061 if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2062 E = EWC->getSubExpr();
2063 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2064 E = BTE->getSubExpr();
2065
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002066 if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2067 const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002068 if (!CtorD || !CtorD->hasAttrs())
Richard Smithe97654b2018-01-11 22:13:57 +00002069 continue;
2070 handleCall(E, CtorD, VD);
2071 } else if (isa<CallExpr>(E) && E->isRValue()) {
2072 // If the object is initialized by a function call that returns a
2073 // scoped lockable by value, use the attributes on the copy or move
2074 // constructor to figure out what effect that should have on the
2075 // lockset.
2076 // FIXME: Is this really the best way to handle this situation?
2077 auto *RD = E->getType()->getAsCXXRecordDecl();
2078 if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2079 continue;
2080 CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2081 if (!CtorD || !CtorD->hasAttrs())
2082 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002083 handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002084 }
2085 }
2086 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002087}
2088
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002089/// Compute the intersection of two locksets and issue warnings for any
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002090/// locks in the symmetric difference.
2091///
2092/// This function is used at a merge point in the CFG when comparing the lockset
2093/// of each branch being merged. For example, given the following sequence:
2094/// A; if () then B; else C; D; we need to check that the lockset after B and C
2095/// are the same. In the event of a difference, we use the intersection of these
2096/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002097///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002098/// \param FSet1 The first lockset.
2099/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002100/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002101/// \param LEK1 The error message to report if a mutex is missing from LSet1
2102/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002103void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2104 const FactSet &FSet2,
2105 SourceLocation JoinLoc,
2106 LockErrorKind LEK1,
2107 LockErrorKind LEK2,
2108 bool Modify) {
2109 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002110
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002111 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002112 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002113 const FactEntry *LDat1 = nullptr;
2114 const FactEntry *LDat2 = &FactMan[Fact];
2115 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2116 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002117
DeLesley Hutchins42665222014-08-04 16:10:59 +00002118 if (LDat1) {
2119 if (LDat1->kind() != LDat2->kind()) {
2120 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2121 LDat2->loc(), LDat1->loc());
2122 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002123 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002124 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002125 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002126 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00002127 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002128 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002129 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002130 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002131 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00002132 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2133 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002134 }
2135 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002136
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002137 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002138 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002139 const FactEntry *LDat1 = &FactMan[Fact];
2140 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002141
DeLesley Hutchins42665222014-08-04 16:10:59 +00002142 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00002143 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2144 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002145 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00002146 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002147 }
2148 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002149}
2150
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002151// Return true if block B never continues to its successors.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002152static bool neverReturns(const CFGBlock *B) {
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002153 if (B->hasNoReturnElement())
2154 return true;
2155 if (B->empty())
2156 return false;
2157
2158 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002159 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2160 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002161 return true;
2162 }
2163 return false;
2164}
2165
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002166/// Check a function's CFG for thread-safety violations.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002167///
2168/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2169/// at the end of each block, and issue warnings for thread safety violations.
2170/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002171void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002172 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2173 // For now, we just use the walker to set things up.
2174 threadSafety::CFGWalker walker;
2175 if (!walker.init(AC))
2176 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002177
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002178 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002179 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002180
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002181 CFG *CFGraph = walker.getGraph();
2182 const NamedDecl *D = walker.getDecl();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002183 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00002184 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002185
Aaron Ballman9ead1242013-12-19 02:39:40 +00002186 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002187 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002188
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002189 // FIXME: Do something a bit more intelligent inside constructor and
2190 // destructor code. Constructors and destructors must assume unique access
2191 // to 'this', so checks on member variable access is disabled, but we should
2192 // still enable checks on other objects.
2193 if (isa<CXXConstructorDecl>(D))
2194 return; // Don't check inside constructors.
2195 if (isa<CXXDestructorDecl>(D))
2196 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002197
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002198 Handler.enterFunction(CurrentFunction);
2199
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002200 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002201 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002202
2203 // We need to explore the CFG via a "topological" ordering.
2204 // That way, we will be guaranteed to have information about required
2205 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002206 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002207 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002208
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002209 // Mark entry block as reachable
2210 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2211
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002212 // Compute SSA names for local variables
2213 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2214
Richard Smith92286672012-02-03 04:45:26 +00002215 // Fill in source locations for all CFGBlocks.
2216 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2217
DeLesley Hutchins42665222014-08-04 16:10:59 +00002218 CapExprSet ExclusiveLocksAcquired;
2219 CapExprSet SharedLocksAcquired;
2220 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002221
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002222 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002223 // to initial lockset. Also turn off checking for lock and unlock functions.
2224 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002225 if (!SortedGraph->empty() && D->hasAttrs()) {
2226 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002227 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002228
DeLesley Hutchins42665222014-08-04 16:10:59 +00002229 CapExprSet ExclusiveLocksToAdd;
2230 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002231 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002232
2233 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002234 for (const auto *Attr : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002235 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002236 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002237 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00002238 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002239 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002240 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002241 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2242 // We must ignore such methods.
2243 if (A->args_size() == 0)
2244 return;
Aaron Ballmaneaa18e62018-08-03 19:37:45 +00002245 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2246 nullptr, D);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002247 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002248 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002249 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002250 if (A->args_size() == 0)
2251 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002252 getMutexIDs(A->isShared() ? SharedLocksAcquired
2253 : ExclusiveLocksAcquired,
2254 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002255 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002256 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002257 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002258 return;
2259 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002260 // Don't try to check trylock functions for now.
2261 return;
2262 } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2263 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002264 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002265 }
2266 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002267
2268 // FIXME -- Loc can be wrong here.
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002269 for (const auto &Mu : ExclusiveLocksToAdd) {
2270 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2271 Entry->setDeclared(true);
2272 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2273 }
2274 for (const auto &Mu : SharedLocksToAdd) {
2275 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2276 Entry->setDeclared(true);
2277 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2278 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002279 }
2280
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002281 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002282 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002283 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002284
2285 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002286 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002287
2288 // Iterate through the predecessor blocks and warn if the lockset for all
2289 // predecessors is not the same. We take the entry lockset of the current
2290 // block to be the intersection of all previous locksets.
2291 // FIXME: By keeping the intersection, we may output more errors in future
2292 // for a lock which is not in the intersection, but was in the union. We
2293 // may want to also keep the union in future. As an example, let's say
2294 // the intersection contains Mutex L, and the union contains L and M.
2295 // Later we unlock M. At this point, we would output an error because we
2296 // never locked M; although the real error is probably that we forgot to
2297 // lock M on all code paths. Conversely, let's say that later we lock M.
2298 // In this case, we should compare against the intersection instead of the
2299 // union because the real error is probably that we forgot to unlock M on
2300 // all code paths.
2301 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002302 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002303 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2304 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002305 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002306 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002307 continue;
2308
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002309 int PrevBlockID = (*PI)->getBlockID();
2310 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2311
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002312 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002313 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002314 continue;
2315
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002316 // Okay, we can reach this block from the entry.
2317 CurrBlockInfo->Reachable = true;
2318
Richard Smith815b29d2012-02-03 03:30:07 +00002319 // If the previous block ended in a 'continue' or 'break' statement, then
2320 // a difference in locksets is probably due to a bug in that block, rather
2321 // than in some other predecessor. In that case, keep the other
2322 // predecessor's lockset.
2323 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2324 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2325 SpecialBlocks.push_back(*PI);
2326 continue;
2327 }
2328 }
2329
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002330 FactSet PrevLockset;
2331 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002332
Caitlin Sadowski33208342011-09-09 16:11:56 +00002333 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002334 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002335 LocksetInitialized = true;
2336 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002337 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2338 CurrBlockInfo->EntryLoc,
2339 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002340 }
2341 }
2342
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002343 // Skip rest of block if it's not reachable.
2344 if (!CurrBlockInfo->Reachable)
2345 continue;
2346
Richard Smith815b29d2012-02-03 03:30:07 +00002347 // Process continue and break blocks. Assume that the lockset for the
2348 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002349 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00002350 int PrevBlockID = PrevBlock->getBlockID();
2351 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2352
2353 if (!LocksetInitialized) {
2354 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2355 LocksetInitialized = true;
2356 } else {
2357 // Determine whether this edge is a loop terminator for diagnostic
2358 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2359 // it might also be part of a switch. Also, a subsequent destructor
2360 // might add to the lockset, in which case the real issue might be a
2361 // double lock on the other path.
2362 const Stmt *Terminator = PrevBlock->getTerminator();
2363 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2364
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002365 FactSet PrevLockset;
2366 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2367 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002368
Richard Smith815b29d2012-02-03 03:30:07 +00002369 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002370 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2371 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002372 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002373 : LEK_LockedSomePredecessors,
2374 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002375 }
2376 }
2377
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002378 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2379
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002380 // Visit all the statements in the basic block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002381 for (const auto &BI : *CurrBlock) {
2382 switch (BI.getKind()) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002383 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002384 CFGStmt CS = BI.castAs<CFGStmt>();
2385 LocksetBuilder.Visit(const_cast<Stmt *>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002386 break;
2387 }
2388 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2389 case CFGElement::AutomaticObjectDtor: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002390 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
2391 auto *DD = const_cast<CXXDestructorDecl *>(
David Blaikie2a01f5d2013-02-21 20:58:29 +00002392 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002393 if (!DD->hasAttrs())
2394 break;
2395
2396 // Create a dummy expression,
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002397 auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
Richard Trieua1877592015-03-16 21:49:43 +00002398 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002399 VK_LValue, AD.getTriggerStmt()->getEndLoc());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002400 LocksetBuilder.handleCall(&DRE, DD);
2401 break;
2402 }
2403 default:
2404 break;
2405 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002406 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002407 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002408
2409 // For every back edge from CurrBlock (the end of the loop) to another block
2410 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2411 // the one held at the beginning of FirstLoopBlock. We can look up the
2412 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2413 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2414 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002415 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002416 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002417 continue;
2418
2419 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002420 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2421 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2422 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2423 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002424 LEK_LockedSomeLoopIterations,
2425 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002426 }
2427 }
2428
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002429 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2430 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002431
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002432 // Skip the final check if the exit block is unreachable.
2433 if (!Final->Reachable)
2434 return;
2435
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002436 // By default, we expect all locks held on entry to be held on exit.
2437 FactSet ExpectedExitSet = Initial->EntrySet;
2438
2439 // Adjust the expected exit set by adding or removing locks, as declared
2440 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2441 // issue the appropriate warning.
2442 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002443 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002444 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2445 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002446 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002447 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2448 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002449 for (const auto &Lock : LocksReleased)
2450 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002451
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002452 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002453 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002454 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002455 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002456 LEK_NotLockedAtEndOfFunction,
2457 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002458
2459 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002460}
2461
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002462/// Check a function's CFG for thread-safety violations.
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002463///
2464/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2465/// at the end of each block, and issue warnings for thread safety violations.
2466/// Each block in the CFG is traversed exactly once.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002467void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2468 ThreadSafetyHandler &Handler,
2469 BeforeSet **BSet) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002470 if (!*BSet)
2471 *BSet = new BeforeSet;
2472 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002473 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002474}
2475
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002476void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002477
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002478/// Helper function that returns a LockKind required for the given level
Caitlin Sadowski33208342011-09-09 16:11:56 +00002479/// of access.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002480LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002481 switch (AK) {
2482 case AK_Read :
2483 return LK_Shared;
2484 case AK_Written :
2485 return LK_Exclusive;
2486 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002487 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002488}