blob: ca146a83c6c2e7cea4051f1e26bd199afe15d7b7 [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"
Aaron Puchert7146b002018-10-03 11:58:19 +000036#include "clang/Basic/Builtins.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000037#include "clang/Basic/LLVM.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000038#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000039#include "clang/Basic/SourceLocation.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000040#include "clang/Basic/Specifiers.h"
41#include "llvm/ADT/ArrayRef.h"
42#include "llvm/ADT/DenseMap.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000043#include "llvm/ADT/ImmutableMap.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000044#include "llvm/ADT/Optional.h"
Aaron Puchert6a68efc2018-12-16 14:15:30 +000045#include "llvm/ADT/PointerIntPair.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000046#include "llvm/ADT/STLExtras.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000047#include "llvm/ADT/SmallVector.h"
48#include "llvm/ADT/StringRef.h"
Eugene Zelenkobbe25312018-03-16 21:22:42 +000049#include "llvm/Support/Allocator.h"
50#include "llvm/Support/Casting.h"
51#include "llvm/Support/ErrorHandling.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000052#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000053#include <algorithm>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000054#include <cassert>
55#include <functional>
56#include <iterator>
57#include <memory>
58#include <string>
59#include <type_traits>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000060#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000061#include <vector>
Eugene Zelenkobbe25312018-03-16 21:22:42 +000062
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000063using namespace clang;
64using namespace threadSafety;
Caitlin Sadowski33208342011-09-09 16:11:56 +000065
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000066// Key method definition
Eugene Zelenkobbe25312018-03-16 21:22:42 +000067ThreadSafetyHandler::~ThreadSafetyHandler() = default;
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000068
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000069/// Issue a warning about an invalid lock expression
70static void warnInvalidLock(ThreadSafetyHandler &Handler,
71 const Expr *MutexExp, const NamedDecl *D,
72 const Expr *DeclExp, StringRef Kind) {
73 SourceLocation Loc;
74 if (DeclExp)
75 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000076
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000077 // FIXME: add a note about the attribute location in MutexExp or D
78 if (Loc.isValid())
79 Handler.handleInvalidLockExp(Kind, Loc);
80}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000081
Eugene Zelenkobbe25312018-03-16 21:22:42 +000082namespace {
83
Aaron Puchert78619432018-08-22 21:06:04 +000084/// A set of CapabilityExpr objects, which are compiled from thread safety
85/// attributes on a function.
DeLesley Hutchins42665222014-08-04 16:10:59 +000086class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000087public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000088 /// Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000089 void push_back_nodup(const CapabilityExpr &CapE) {
90 iterator It = std::find_if(begin(), end(),
91 [=](const CapabilityExpr &CapE2) {
92 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000093 });
94 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +000095 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000096 }
97};
98
Ed Schoutenca988742014-09-03 06:00:11 +000099class FactManager;
100class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000102/// This is a helper class that stores a fact that is known at a
DeLesley Hutchins42665222014-08-04 16:10:59 +0000103/// particular point in program execution. Currently, a fact is a capability,
104/// along with additional information, such as where it was acquired, whether
105/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +0000106///
Aaron Ballman1b587592018-07-26 13:03:16 +0000107/// FIXME: this analysis does not currently support re-entrant locking.
DeLesley Hutchins42665222014-08-04 16:10:59 +0000108class FactEntry : public CapabilityExpr {
109private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000110 /// Exclusive or shared.
111 LockKind LKind;
112
113 /// Where it was acquired.
114 SourceLocation AcquireLoc;
115
116 /// True if the lock was asserted.
117 bool Asserted;
118
119 /// True if the lock was declared.
120 bool Declared;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000121
DeLesley Hutchins42665222014-08-04 16:10:59 +0000122public:
123 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000124 bool Asrt, bool Declrd = false)
125 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
126 Declared(Declrd) {}
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000127 virtual ~FactEntry() = default;
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000128
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000129 LockKind kind() const { return LKind; }
130 SourceLocation loc() const { return AcquireLoc; }
131 bool asserted() const { return Asserted; }
132 bool declared() const { return Declared; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000133
134 void setDeclared(bool D) { Declared = D; }
Ed Schoutenca988742014-09-03 06:00:11 +0000135
136 virtual void
137 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
138 SourceLocation JoinLoc, LockErrorKind LEK,
139 ThreadSafetyHandler &Handler) const = 0;
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000140 virtual void handleLock(FactSet &FSet, FactManager &FactMan,
141 const FactEntry &entry, ThreadSafetyHandler &Handler,
142 StringRef DiagKind) const = 0;
Ed Schoutenca988742014-09-03 06:00:11 +0000143 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
144 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
145 bool FullyRemove, ThreadSafetyHandler &Handler,
146 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000147
DeLesley Hutchins42665222014-08-04 16:10:59 +0000148 // Return true if LKind >= LK, where exclusive > shared
Aaron Puchert969f32d2018-09-21 23:08:30 +0000149 bool isAtLeast(LockKind LK) const {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000150 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000151 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000152};
153
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000154using FactID = unsigned short;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000155
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000156/// FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000157/// the analysis of a single routine.
158class FactManager {
159private:
Aaron Puchert969f32d2018-09-21 23:08:30 +0000160 std::vector<std::unique_ptr<const FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000161
162public:
Ed Schoutenca988742014-09-03 06:00:11 +0000163 FactID newFact(std::unique_ptr<FactEntry> Entry) {
164 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000165 return static_cast<unsigned short>(Facts.size() - 1);
166 }
167
Ed Schoutenca988742014-09-03 06:00:11 +0000168 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000169};
170
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000171/// A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000172/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000173/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000174/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000175/// locks, so we can get away with doing a linear search for lookup. Note
176/// that a hashtable or map is inappropriate in this case, because lookups
177/// may involve partial pattern matches, rather than exact matches.
178class FactSet {
179private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000180 using FactVec = SmallVector<FactID, 4>;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000181
182 FactVec FactIDs;
183
184public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000185 using iterator = FactVec::iterator;
186 using const_iterator = FactVec::const_iterator;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000187
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000188 iterator begin() { return FactIDs.begin(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000189 const_iterator begin() const { return FactIDs.begin(); }
190
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000191 iterator end() { return FactIDs.end(); }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000192 const_iterator end() const { return FactIDs.end(); }
193
194 bool isEmpty() const { return FactIDs.size() == 0; }
195
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000196 // Return true if the set contains only negative facts
197 bool isEmpty(FactManager &FactMan) const {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000198 for (const auto FID : *this) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000199 if (!FactMan[FID].negative())
200 return false;
201 }
202 return true;
203 }
204
205 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
206
Ed Schoutenca988742014-09-03 06:00:11 +0000207 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
208 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000209 FactIDs.push_back(F);
210 return F;
211 }
212
DeLesley Hutchins42665222014-08-04 16:10:59 +0000213 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000214 unsigned n = FactIDs.size();
215 if (n == 0)
216 return false;
217
218 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000219 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000220 FactIDs[i] = FactIDs[n-1];
221 FactIDs.pop_back();
222 return true;
223 }
224 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000225 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000226 FactIDs.pop_back();
227 return true;
228 }
229 return false;
230 }
231
DeLesley Hutchins42665222014-08-04 16:10:59 +0000232 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000233 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000234 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000235 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000236 }
237
Aaron Puchert969f32d2018-09-21 23:08:30 +0000238 const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000239 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000240 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000241 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000242 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000243 }
244
Aaron Puchert969f32d2018-09-21 23:08:30 +0000245 const FactEntry *findLockUniv(FactManager &FM,
246 const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000247 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000248 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000249 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000250 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000251 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000252
Aaron Puchert969f32d2018-09-21 23:08:30 +0000253 const FactEntry *findPartialMatch(FactManager &FM,
254 const CapabilityExpr &CapE) const {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000255 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000256 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000257 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000258 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000259 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000260
261 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
262 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
263 return FM[ID].valueDecl() == Vd;
264 });
265 return I != end();
266 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000267};
268
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000269class ThreadSafetyAnalyzer;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000270
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000271} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000272
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000273namespace clang {
274namespace threadSafety {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000275
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000276class BeforeSet {
277private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000278 using BeforeVect = SmallVector<const ValueDecl *, 4>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000279
280 struct BeforeInfo {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000281 BeforeVect Vect;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000282 int Visited = 0;
283
284 BeforeInfo() = default;
285 BeforeInfo(BeforeInfo &&) = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000286 };
287
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000288 using BeforeMap =
289 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
290 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000291
292public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000293 BeforeSet() = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000294
295 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
296 ThreadSafetyAnalyzer& Analyzer);
297
Reid Kleckner19ff5602015-11-20 19:08:30 +0000298 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
299 ThreadSafetyAnalyzer &Analyzer);
300
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000301 void checkBeforeAfter(const ValueDecl* Vd,
302 const FactSet& FSet,
303 ThreadSafetyAnalyzer& Analyzer,
304 SourceLocation Loc, StringRef CapKind);
305
306private:
307 BeforeMap BMap;
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000308 CycleMap CycMap;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000309};
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000310
311} // namespace threadSafety
312} // namespace clang
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000313
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000314namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000315
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000316class LocalVariableMap;
317
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000318using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
319
Richard Smith92286672012-02-03 04:45:26 +0000320/// A side (entry or exit) of a CFG node.
321enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000322
323/// CFGBlockInfo is a struct which contains all the information that is
324/// maintained for each block in the CFG. See LocalVariableMap for more
325/// information about the contexts.
326struct CFGBlockInfo {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000327 // Lockset held at entry to block
328 FactSet EntrySet;
329
330 // Lockset held at exit from block
331 FactSet ExitSet;
332
333 // Context held at entry to block
334 LocalVarContext EntryContext;
335
336 // Context held at exit from block
337 LocalVarContext ExitContext;
338
339 // Location of first statement in block
340 SourceLocation EntryLoc;
341
342 // Location of last statement in block.
343 SourceLocation ExitLoc;
344
345 // Used to replay contexts later
346 unsigned EntryIndex;
347
348 // Is this block reachable?
349 bool Reachable = false;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000350
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000351 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000352 return Side == CBS_Entry ? EntrySet : ExitSet;
353 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000354
Richard Smith92286672012-02-03 04:45:26 +0000355 SourceLocation getLocation(CFGBlockSide Side) const {
356 return Side == CBS_Entry ? EntryLoc : ExitLoc;
357 }
358
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000359private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000360 CFGBlockInfo(LocalVarContext EmptyCtx)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000361 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000362
363public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000364 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000365};
366
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000367// A LocalVariableMap maintains a map from local variables to their currently
368// valid definitions. It provides SSA-like functionality when traversing the
369// CFG. Like SSA, each definition or assignment to a variable is assigned a
370// unique name (an integer), which acts as the SSA name for that definition.
371// The total set of names is shared among all CFG basic blocks.
372// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
373// with their SSA-names. Instead, we compute a Context for each point in the
374// code, which maps local variables to the appropriate SSA-name. This map
375// changes with each assignment.
376//
377// The map is computed in a single pass over the CFG. Subsequent analyses can
378// then query the map to find the appropriate Context for a statement, and use
379// that Context to look up the definitions of variables.
380class LocalVariableMap {
381public:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000382 using Context = LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000383
384 /// A VarDefinition consists of an expression, representing the value of the
385 /// variable, along with the context in which that expression should be
386 /// interpreted. A reference VarDefinition does not itself contain this
387 /// information, but instead contains a pointer to a previous VarDefinition.
388 struct VarDefinition {
389 public:
390 friend class LocalVariableMap;
391
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000392 // The original declaration for this variable.
393 const NamedDecl *Dec;
394
395 // The expression for this variable, OR
396 const Expr *Exp = nullptr;
397
398 // Reference to another VarDefinition
399 unsigned Ref = 0;
400
401 // The map with which Exp should be interpreted.
402 Context Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000403
404 bool isReference() { return !Exp; }
405
406 private:
407 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000408 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000409 : Dec(D), Exp(E), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000410
411 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000412 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000413 : Dec(D), Ref(R), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000414 };
415
416private:
417 Context::Factory ContextFactory;
418 std::vector<VarDefinition> VarDefinitions;
419 std::vector<unsigned> CtxIndices;
Aaron Puchertcd37c092018-08-23 21:53:04 +0000420 std::vector<std::pair<const Stmt *, Context>> SavedContexts;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000421
422public:
423 LocalVariableMap() {
424 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000425 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000426 }
427
428 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000429 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000430 const unsigned *i = Ctx.lookup(D);
431 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000432 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000433 assert(*i < VarDefinitions.size());
434 return &VarDefinitions[*i];
435 }
436
437 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000438 /// NULL if the expression is not statically known. If successful, also
439 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000440 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000441 const unsigned *P = Ctx.lookup(D);
442 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000443 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000444
445 unsigned i = *P;
446 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000447 if (VarDefinitions[i].Exp) {
448 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000449 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000450 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000451 i = VarDefinitions[i].Ref;
452 }
Craig Topper25542942014-05-20 04:30:07 +0000453 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000454 }
455
456 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
457
458 /// Return the next context after processing S. This function is used by
459 /// clients of the class to get the appropriate context when traversing the
460 /// CFG. It must be called for every assignment or DeclStmt.
Aaron Puchertcd37c092018-08-23 21:53:04 +0000461 Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000462 if (SavedContexts[CtxIndex+1].first == S) {
463 CtxIndex++;
464 Context Result = SavedContexts[CtxIndex].second;
465 return Result;
466 }
467 return C;
468 }
469
470 void dumpVarDefinitionName(unsigned i) {
471 if (i == 0) {
472 llvm::errs() << "Undefined";
473 return;
474 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000475 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000476 if (!Dec) {
477 llvm::errs() << "<<NULL>>";
478 return;
479 }
480 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000481 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000482 }
483
484 /// Dumps an ASCII representation of the variable map to llvm::errs()
485 void dump() {
486 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000487 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000488 unsigned Ref = VarDefinitions[i].Ref;
489
490 dumpVarDefinitionName(i);
491 llvm::errs() << " = ";
492 if (Exp) Exp->dump();
493 else {
494 dumpVarDefinitionName(Ref);
495 llvm::errs() << "\n";
496 }
497 }
498 }
499
500 /// Dumps an ASCII representation of a Context to llvm::errs()
501 void dumpContext(Context C) {
502 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000503 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000504 D->printName(llvm::errs());
505 const unsigned *i = C.lookup(D);
506 llvm::errs() << " -> ";
507 dumpVarDefinitionName(*i);
508 llvm::errs() << "\n";
509 }
510 }
511
512 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000513 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
514 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000515
516protected:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000517 friend class VarMapBuilder;
518
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000519 // Get the current context index
520 unsigned getContextIndex() { return SavedContexts.size()-1; }
521
522 // Save the current context for later replay
Aaron Puchertcd37c092018-08-23 21:53:04 +0000523 void saveContext(const Stmt *S, Context C) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000524 SavedContexts.push_back(std::make_pair(S, C));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000525 }
526
527 // Adds a new definition to the given context, and returns a new context.
528 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000529 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000530 assert(!Ctx.contains(D));
531 unsigned newID = VarDefinitions.size();
532 Context NewCtx = ContextFactory.add(Ctx, D, newID);
533 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
534 return NewCtx;
535 }
536
537 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000538 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000539 unsigned newID = VarDefinitions.size();
540 Context NewCtx = ContextFactory.add(Ctx, D, newID);
541 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
542 return NewCtx;
543 }
544
545 // Updates a definition only if that definition is already in the map.
546 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000547 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000548 if (Ctx.contains(D)) {
549 unsigned newID = VarDefinitions.size();
550 Context NewCtx = ContextFactory.remove(Ctx, D);
551 NewCtx = ContextFactory.add(NewCtx, D, newID);
552 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
553 return NewCtx;
554 }
555 return Ctx;
556 }
557
558 // Removes a definition from the context, but keeps the variable name
559 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000560 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000561 Context NewCtx = Ctx;
562 if (NewCtx.contains(D)) {
563 NewCtx = ContextFactory.remove(NewCtx, D);
564 NewCtx = ContextFactory.add(NewCtx, D, 0);
565 }
566 return NewCtx;
567 }
568
569 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000570 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000571 Context NewCtx = Ctx;
572 if (NewCtx.contains(D)) {
573 NewCtx = ContextFactory.remove(NewCtx, D);
574 }
575 return NewCtx;
576 }
577
578 Context intersectContexts(Context C1, Context C2);
579 Context createReferenceContext(Context C);
580 void intersectBackEdge(Context C1, Context C2);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000581};
582
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000583} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000584
585// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000586CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
587 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000588}
589
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000590namespace {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000591
592/// Visitor which builds a LocalVariableMap
Aaron Puchertcd37c092018-08-23 21:53:04 +0000593class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000594public:
595 LocalVariableMap* VMap;
596 LocalVariableMap::Context Ctx;
597
598 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000599 : VMap(VM), Ctx(C) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000600
Aaron Puchertcd37c092018-08-23 21:53:04 +0000601 void VisitDeclStmt(const DeclStmt *S);
602 void VisitBinaryOperator(const BinaryOperator *BO);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000603};
604
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000605} // namespace
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000606
607// Add new local variables to the variable map
Aaron Puchertcd37c092018-08-23 21:53:04 +0000608void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000609 bool modifiedCtx = false;
Aaron Puchertcd37c092018-08-23 21:53:04 +0000610 const DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000611 for (const auto *D : DGrp) {
612 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
613 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000614
615 // Add local variables with trivial type to the variable map
616 QualType T = VD->getType();
617 if (T.isTrivialType(VD->getASTContext())) {
618 Ctx = VMap->addDefinition(VD, E, Ctx);
619 modifiedCtx = true;
620 }
621 }
622 }
623 if (modifiedCtx)
624 VMap->saveContext(S, Ctx);
625}
626
627// Update local variable definitions in variable map
Aaron Puchertcd37c092018-08-23 21:53:04 +0000628void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000629 if (!BO->isAssignmentOp())
630 return;
631
632 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
633
634 // Update the variable map and current context.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000635 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
636 const ValueDecl *VDec = DRE->getDecl();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000637 if (Ctx.lookup(VDec)) {
638 if (BO->getOpcode() == BO_Assign)
639 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
640 else
641 // FIXME -- handle compound assignment operators
642 Ctx = VMap->clearDefinition(VDec, Ctx);
643 VMap->saveContext(BO, Ctx);
644 }
645 }
646}
647
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000648// Computes the intersection of two contexts. The intersection is the
649// set of variables which have the same definition in both contexts;
650// variables with different definitions are discarded.
651LocalVariableMap::Context
652LocalVariableMap::intersectContexts(Context C1, Context C2) {
653 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000654 for (const auto &P : C1) {
655 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000656 const unsigned *i2 = C2.lookup(Dec);
657 if (!i2) // variable doesn't exist on second path
658 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000659 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000660 Result = clearDefinition(Dec, Result);
661 }
662 return Result;
663}
664
665// For every variable in C, create a new variable that refers to the
666// definition in C. Return a new context that contains these new variables.
667// (We use this for a naive implementation of SSA on loop back-edges.)
668LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
669 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000670 for (const auto &P : C)
671 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000672 return Result;
673}
674
675// This routine also takes the intersection of C1 and C2, but it does so by
676// altering the VarDefinitions. C1 must be the result of an earlier call to
677// createReferenceContext.
678void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000679 for (const auto &P : C1) {
680 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000681 VarDefinition *VDef = &VarDefinitions[i1];
682 assert(VDef->isReference());
683
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000684 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000685 if (!i2 || (*i2 != i1))
686 VDef->Ref = 0; // Mark this variable as undefined
687 }
688}
689
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000690// Traverse the CFG in topological order, so all predecessors of a block
691// (excluding back-edges) are visited before the block itself. At
692// each point in the code, we calculate a Context, which holds the set of
693// variable definitions which are visible at that point in execution.
694// Visible variables are mapped to their definitions using an array that
695// contains all definitions.
696//
697// At join points in the CFG, the set is computed as the intersection of
698// the incoming sets along each edge, E.g.
699//
700// { Context | VarDefinitions }
701// int x = 0; { x -> x1 | x1 = 0 }
702// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
703// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
704// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
705// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
706//
707// This is essentially a simpler and more naive version of the standard SSA
708// algorithm. Those definitions that remain in the intersection are from blocks
709// that strictly dominate the current block. We do not bother to insert proper
710// phi nodes, because they are not used in our analysis; instead, wherever
711// a phi node would be required, we simply remove that definition from the
712// context (E.g. x above).
713//
714// The initial traversal does not capture back-edges, so those need to be
715// handled on a separate pass. Whenever the first pass encounters an
716// incoming back edge, it duplicates the context, creating new definitions
717// that refer back to the originals. (These correspond to places where SSA
718// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000719// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000720// node was actually required.) E.g.
721//
722// { Context | VarDefinitions }
723// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
724// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
725// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
726// ... { y -> y1 | x3 = 2, x2 = 1, ... }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000727void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000728 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000729 std::vector<CFGBlockInfo> &BlockInfo) {
730 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
731
732 CtxIndices.resize(CFGraph->getNumBlockIDs());
733
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000734 for (const auto *CurrBlock : *SortedGraph) {
Aaron Puchert88d85362018-09-22 21:56:16 +0000735 unsigned CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000736 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
737
738 VisitedBlocks.insert(CurrBlock);
739
740 // Calculate the entry context for the current block
741 bool HasBackEdges = false;
742 bool CtxInit = true;
743 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
744 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
745 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000746 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000747 HasBackEdges = true;
748 continue;
749 }
750
Aaron Puchert88d85362018-09-22 21:56:16 +0000751 unsigned PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000752 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
753
754 if (CtxInit) {
755 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
756 CtxInit = false;
757 }
758 else {
759 CurrBlockInfo->EntryContext =
760 intersectContexts(CurrBlockInfo->EntryContext,
761 PrevBlockInfo->ExitContext);
762 }
763 }
764
765 // Duplicate the context if we have back-edges, so we can call
766 // intersectBackEdges later.
767 if (HasBackEdges)
768 CurrBlockInfo->EntryContext =
769 createReferenceContext(CurrBlockInfo->EntryContext);
770
771 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000772 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000773 CurrBlockInfo->EntryIndex = getContextIndex();
774
775 // Visit all the statements in the basic block.
776 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000777 for (const auto &BI : *CurrBlock) {
778 switch (BI.getKind()) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000779 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000780 CFGStmt CS = BI.castAs<CFGStmt>();
Aaron Puchertcd37c092018-08-23 21:53:04 +0000781 VMapBuilder.Visit(CS.getStmt());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000782 break;
783 }
784 default:
785 break;
786 }
787 }
788 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
789
790 // Mark variables on back edges as "unknown" if they've been changed.
791 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
792 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
793 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000794 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000795 continue;
796
797 CFGBlock *FirstLoopBlock = *SI;
798 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
799 Context LoopEnd = CurrBlockInfo->ExitContext;
800 intersectBackEdge(LoopBegin, LoopEnd);
801 }
802 }
803
804 // Put an extra entry at the end of the indexed context array
805 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000806 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000807}
808
Richard Smith92286672012-02-03 04:45:26 +0000809/// Find the appropriate source locations to use when producing diagnostics for
810/// each block in the CFG.
811static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000812 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000813 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000814 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000815 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
816
817 // Find the source location of the last statement in the block, if the
818 // block is not empty.
819 if (const Stmt *S = CurrBlock->getTerminator()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000820 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000821 } else {
822 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
823 BE = CurrBlock->rend(); BI != BE; ++BI) {
824 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000825 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000826 CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000827 break;
828 }
829 }
830 }
831
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000832 if (CurrBlockInfo->ExitLoc.isValid()) {
Richard Smith92286672012-02-03 04:45:26 +0000833 // This block contains at least one statement. Find the source location
834 // of the first statement in the block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000835 for (const auto &BI : *CurrBlock) {
Richard Smith92286672012-02-03 04:45:26 +0000836 // FIXME: Handle other CFGElement kinds.
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000837 if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000838 CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
Richard Smith92286672012-02-03 04:45:26 +0000839 break;
840 }
841 }
842 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
843 CurrBlock != &CFGraph->getExit()) {
844 // The block is empty, and has a single predecessor. Use its exit
845 // location.
846 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
847 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
848 }
849 }
850}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000851
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000852namespace {
853
Ed Schoutenca988742014-09-03 06:00:11 +0000854class LockableFactEntry : public FactEntry {
855private:
Eugene Zelenkobbe25312018-03-16 21:22:42 +0000856 /// managed by ScopedLockable object
857 bool Managed;
Ed Schoutenca988742014-09-03 06:00:11 +0000858
859public:
860 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
861 bool Mng = false, bool Asrt = false)
862 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
863
864 void
865 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
866 SourceLocation JoinLoc, LockErrorKind LEK,
867 ThreadSafetyHandler &Handler) const override {
868 if (!Managed && !asserted() && !negative() && !isUniversal()) {
869 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
870 LEK);
871 }
872 }
873
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000874 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
875 ThreadSafetyHandler &Handler,
876 StringRef DiagKind) const override {
877 Handler.handleDoubleLock(DiagKind, entry.toString(), entry.loc());
878 }
879
Ed Schoutenca988742014-09-03 06:00:11 +0000880 void handleUnlock(FactSet &FSet, FactManager &FactMan,
881 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
882 bool FullyRemove, ThreadSafetyHandler &Handler,
883 StringRef DiagKind) const override {
884 FSet.removeLock(FactMan, Cp);
885 if (!Cp.negative()) {
886 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
887 !Cp, LK_Exclusive, UnlockLoc));
888 }
889 }
890};
891
892class ScopedLockableFactEntry : public FactEntry {
893private:
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000894 enum UnderlyingCapabilityKind {
895 UCK_Acquired, ///< Any kind of acquired capability.
896 UCK_ReleasedShared, ///< Shared capability that was released.
897 UCK_ReleasedExclusive, ///< Exclusive capability that was released.
898 };
899
900 using UnderlyingCapability =
901 llvm::PointerIntPair<const til::SExpr *, 2, UnderlyingCapabilityKind>;
902
903 SmallVector<UnderlyingCapability, 4> UnderlyingMutexes;
Ed Schoutenca988742014-09-03 06:00:11 +0000904
905public:
906 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000907 const CapExprSet &Excl, const CapExprSet &Shrd,
908 const CapExprSet &ExclRel, const CapExprSet &ShrdRel)
Ed Schoutenca988742014-09-03 06:00:11 +0000909 : FactEntry(CE, LK_Exclusive, Loc, false) {
910 for (const auto &M : Excl)
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000911 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
Ed Schoutenca988742014-09-03 06:00:11 +0000912 for (const auto &M : Shrd)
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000913 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
914 for (const auto &M : ExclRel)
915 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedExclusive);
916 for (const auto &M : ShrdRel)
917 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedShared);
Ed Schoutenca988742014-09-03 06:00:11 +0000918 }
919
920 void
921 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
922 SourceLocation JoinLoc, LockErrorKind LEK,
923 ThreadSafetyHandler &Handler) const override {
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000924 for (const auto &UnderlyingMutex : UnderlyingMutexes) {
925 const auto *Entry = FSet.findLock(
926 FactMan, CapabilityExpr(UnderlyingMutex.getPointer(), false));
927 if ((UnderlyingMutex.getInt() == UCK_Acquired && Entry) ||
928 (UnderlyingMutex.getInt() != UCK_Acquired && !Entry)) {
Ed Schoutenca988742014-09-03 06:00:11 +0000929 // If this scoped lock manages another mutex, and if the underlying
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000930 // mutex is still/not held, then warn about the underlying mutex.
Ed Schoutenca988742014-09-03 06:00:11 +0000931 Handler.handleMutexHeldEndOfScope(
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000932 "mutex", sx::toString(UnderlyingMutex.getPointer()), loc(), JoinLoc,
933 LEK);
Ed Schoutenca988742014-09-03 06:00:11 +0000934 }
935 }
936 }
937
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000938 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
939 ThreadSafetyHandler &Handler,
940 StringRef DiagKind) const override {
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000941 for (const auto &UnderlyingMutex : UnderlyingMutexes) {
942 CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000943
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000944 if (UnderlyingMutex.getInt() == UCK_Acquired)
945 lock(FSet, FactMan, UnderCp, entry.kind(), entry.loc(), &Handler,
946 DiagKind);
947 else
948 unlock(FSet, FactMan, UnderCp, entry.loc(), &Handler, DiagKind);
Aaron Puchertc3e37b72018-08-22 22:14:53 +0000949 }
950 }
951
Ed Schoutenca988742014-09-03 06:00:11 +0000952 void handleUnlock(FactSet &FSet, FactManager &FactMan,
953 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
954 bool FullyRemove, ThreadSafetyHandler &Handler,
955 StringRef DiagKind) const override {
956 assert(!Cp.negative() && "Managing object cannot be negative.");
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000957 for (const auto &UnderlyingMutex : UnderlyingMutexes) {
958 CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
Ed Schoutenca988742014-09-03 06:00:11 +0000959
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000960 // Remove/lock the underlying mutex if it exists/is still unlocked; warn
961 // on double unlocking/locking if we're not destroying the scoped object.
962 ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler;
963 if (UnderlyingMutex.getInt() == UCK_Acquired) {
964 unlock(FSet, FactMan, UnderCp, UnlockLoc, TSHandler, DiagKind);
Ed Schoutenca988742014-09-03 06:00:11 +0000965 } else {
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000966 LockKind kind = UnderlyingMutex.getInt() == UCK_ReleasedShared
967 ? LK_Shared
968 : LK_Exclusive;
969 lock(FSet, FactMan, UnderCp, kind, UnlockLoc, TSHandler, DiagKind);
Ed Schoutenca988742014-09-03 06:00:11 +0000970 }
971 }
972 if (FullyRemove)
973 FSet.removeLock(FactMan, Cp);
974 }
Aaron Puchert6a68efc2018-12-16 14:15:30 +0000975
976private:
977 void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
978 LockKind kind, SourceLocation loc, ThreadSafetyHandler *Handler,
979 StringRef DiagKind) const {
980 if (!FSet.findLock(FactMan, Cp)) {
981 FSet.removeLock(FactMan, !Cp);
982 FSet.addLock(FactMan,
983 llvm::make_unique<LockableFactEntry>(Cp, kind, loc));
984 } else if (Handler) {
985 Handler->handleDoubleLock(DiagKind, Cp.toString(), loc);
986 }
987 }
988
989 void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
990 SourceLocation loc, ThreadSafetyHandler *Handler,
991 StringRef DiagKind) const {
992 if (FSet.findLock(FactMan, Cp)) {
993 FSet.removeLock(FactMan, Cp);
994 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
995 !Cp, LK_Exclusive, loc));
996 } else if (Handler) {
997 Handler->handleUnmatchedUnlock(DiagKind, Cp.toString(), loc);
998 }
999 }
Ed Schoutenca988742014-09-03 06:00:11 +00001000};
1001
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001002/// Class which implements the core thread safety analysis routines.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001003class ThreadSafetyAnalyzer {
1004 friend class BuildLockset;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001005 friend class threadSafety::BeforeSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001006
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001007 llvm::BumpPtrAllocator Bpa;
1008 threadSafety::til::MemRegionRef Arena;
1009 threadSafety::SExprBuilder SxBuilder;
1010
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001011 ThreadSafetyHandler &Handler;
1012 const CXXMethodDecl *CurrentMethod;
1013 LocalVariableMap LocalVarMap;
1014 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001015 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001016
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001017 BeforeSet *GlobalBeforeSet;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001018
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001019public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001020 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001021 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001022
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001023 bool inCurrentScope(const CapabilityExpr &CapE);
1024
Ed Schoutenca988742014-09-03 06:00:11 +00001025 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
1026 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001027 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001028 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
1029 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001030
1031 template <typename AttrType>
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001032 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +00001033 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001034
1035 template <class AttrType>
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001036 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001037 const NamedDecl *D,
1038 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1039 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001040
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001041 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1042 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001043
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001044 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1045 const CFGBlock* PredBlock,
1046 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001047
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001048 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1049 SourceLocation JoinLoc,
1050 LockErrorKind LEK1, LockErrorKind LEK2,
1051 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001052
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001053 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1054 SourceLocation JoinLoc, LockErrorKind LEK1,
1055 bool Modify=true) {
1056 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001057 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001058
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001059 void runAnalysis(AnalysisDeclContext &AC);
1060};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001061
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001062} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001063
1064/// Process acquired_before and acquired_after attributes on Vd.
1065BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1066 ThreadSafetyAnalyzer& Analyzer) {
1067 // Create a new entry for Vd.
Reid Kleckner19ff5602015-11-20 19:08:30 +00001068 BeforeInfo *Info = nullptr;
1069 {
1070 // Keep InfoPtr in its own scope in case BMap is modified later and the
1071 // reference becomes invalid.
1072 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1073 if (!InfoPtr)
1074 InfoPtr.reset(new BeforeInfo());
1075 Info = InfoPtr.get();
1076 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001077
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001078 for (const auto *At : Vd->attrs()) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001079 switch (At->getKind()) {
1080 case attr::AcquiredBefore: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001081 const auto *A = cast<AcquiredBeforeAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001082
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001083 // Read exprs from the attribute, and add them to BeforeVect.
1084 for (const auto *Arg : A->args()) {
1085 CapabilityExpr Cp =
1086 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1087 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
Reid Kleckner19ff5602015-11-20 19:08:30 +00001088 Info->Vect.push_back(Cpvd);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001089 const auto It = BMap.find(Cpvd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001090 if (It == BMap.end())
1091 insertAttrExprs(Cpvd, Analyzer);
1092 }
1093 }
1094 break;
1095 }
1096 case attr::AcquiredAfter: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001097 const auto *A = cast<AcquiredAfterAttr>(At);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001098
1099 // Read exprs from the attribute, and add them to BeforeVect.
1100 for (const auto *Arg : A->args()) {
1101 CapabilityExpr Cp =
1102 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1103 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1104 // Get entry for mutex listed in attribute
Reid Kleckner19ff5602015-11-20 19:08:30 +00001105 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1106 ArgInfo->Vect.push_back(Vd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001107 }
1108 }
1109 break;
1110 }
1111 default:
1112 break;
1113 }
1114 }
1115
1116 return Info;
1117}
1118
Reid Kleckner19ff5602015-11-20 19:08:30 +00001119BeforeSet::BeforeInfo *
1120BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1121 ThreadSafetyAnalyzer &Analyzer) {
1122 auto It = BMap.find(Vd);
1123 BeforeInfo *Info = nullptr;
1124 if (It == BMap.end())
1125 Info = insertAttrExprs(Vd, Analyzer);
1126 else
1127 Info = It->second.get();
1128 assert(Info && "BMap contained nullptr?");
1129 return Info;
1130}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001131
1132/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1133void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1134 const FactSet& FSet,
1135 ThreadSafetyAnalyzer& Analyzer,
1136 SourceLocation Loc, StringRef CapKind) {
1137 SmallVector<BeforeInfo*, 8> InfoVect;
1138
1139 // Do a depth-first traversal of Vd.
1140 // Return true if there are cycles.
1141 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1142 if (!Vd)
1143 return false;
1144
Reid Kleckner19ff5602015-11-20 19:08:30 +00001145 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001146
1147 if (Info->Visited == 1)
1148 return true;
1149
1150 if (Info->Visited == 2)
1151 return false;
1152
Reid Kleckner19ff5602015-11-20 19:08:30 +00001153 if (Info->Vect.empty())
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001154 return false;
1155
1156 InfoVect.push_back(Info);
1157 Info->Visited = 1;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001158 for (const auto *Vdb : Info->Vect) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001159 // Exclude mutexes in our immediate before set.
1160 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1161 StringRef L1 = StartVd->getName();
1162 StringRef L2 = Vdb->getName();
1163 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1164 }
1165 // Transitively search other before sets, and warn on cycles.
1166 if (traverse(Vdb)) {
1167 if (CycMap.find(Vd) == CycMap.end()) {
1168 CycMap.insert(std::make_pair(Vd, true));
1169 StringRef L1 = Vd->getName();
1170 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1171 }
1172 }
1173 }
1174 Info->Visited = 2;
1175 return false;
1176 };
1177
1178 traverse(StartVd);
1179
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001180 for (auto *Info : InfoVect)
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001181 Info->Visited = 0;
1182}
1183
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001184/// Gets the value decl pointer from DeclRefExprs or MemberExprs.
Aaron Ballmane0449042014-04-01 21:43:23 +00001185static const ValueDecl *getValueDecl(const Expr *Exp) {
1186 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1187 return getValueDecl(CE->getSubExpr());
1188
1189 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1190 return DR->getDecl();
1191
1192 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1193 return ME->getMemberDecl();
1194
1195 return nullptr;
1196}
1197
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001198namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001199
Aaron Ballmane0449042014-04-01 21:43:23 +00001200template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001201class has_arg_iterator_range {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001202 using yes = char[1];
1203 using no = char[2];
Aaron Ballmane0449042014-04-01 21:43:23 +00001204
1205 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001206 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001207
1208 template <typename>
1209 static no& test(...);
1210
1211public:
1212 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1213};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001214
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001215} // namespace
Aaron Ballmane0449042014-04-01 21:43:23 +00001216
1217static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1218 return A->getName();
1219}
1220
1221static StringRef ClassifyDiagnostic(QualType VDT) {
1222 // We need to look at the declaration of the type of the value to determine
1223 // which it is. The type should either be a record or a typedef, or a pointer
1224 // or reference thereof.
1225 if (const auto *RT = VDT->getAs<RecordType>()) {
1226 if (const auto *RD = RT->getDecl())
1227 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1228 return ClassifyDiagnostic(CA);
1229 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1230 if (const auto *TD = TT->getDecl())
1231 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1232 return ClassifyDiagnostic(CA);
1233 } else if (VDT->isPointerType() || VDT->isReferenceType())
1234 return ClassifyDiagnostic(VDT->getPointeeType());
1235
1236 return "mutex";
1237}
1238
1239static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1240 assert(VD && "No ValueDecl passed");
1241
1242 // The ValueDecl is the declaration of a mutex or role (hopefully).
1243 return ClassifyDiagnostic(VD->getType());
1244}
1245
1246template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001247static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001248 StringRef>::type
1249ClassifyDiagnostic(const AttrTy *A) {
1250 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1251 return ClassifyDiagnostic(VD);
1252 return "mutex";
1253}
1254
1255template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001256static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001257 StringRef>::type
1258ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001259 for (const auto *Arg : A->args()) {
1260 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001261 return ClassifyDiagnostic(VD);
1262 }
1263 return "mutex";
1264}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001265
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001266bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001267 if (!CurrentMethod)
1268 return false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001269 if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1270 const auto *VD = P->clangDecl();
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001271 if (VD)
1272 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1273 }
1274 return false;
1275}
1276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001277/// Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001278/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001279void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1280 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001281 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001282 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001283 return;
1284
Ed Schoutenca988742014-09-03 06:00:11 +00001285 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001286 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001287 CapabilityExpr NegC = !*Entry;
Aaron Puchert969f32d2018-09-21 23:08:30 +00001288 const FactEntry *Nen = FSet.findLock(FactMan, NegC);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001289 if (Nen) {
1290 FSet.removeLock(FactMan, NegC);
1291 }
1292 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001293 if (inCurrentScope(*Entry) && !Entry->asserted())
1294 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1295 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001296 }
1297 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001298
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001299 // Check before/after constraints
1300 if (Handler.issueBetaWarnings() &&
1301 !Entry->asserted() && !Entry->declared()) {
1302 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1303 Entry->loc(), DiagKind);
1304 }
1305
DeLesley Hutchins42665222014-08-04 16:10:59 +00001306 // FIXME: Don't always warn when we have support for reentrant locks.
Aaron Puchert969f32d2018-09-21 23:08:30 +00001307 if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
Ed Schoutenca988742014-09-03 06:00:11 +00001308 if (!Entry->asserted())
Aaron Puchertc3e37b72018-08-22 22:14:53 +00001309 Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001310 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001311 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001312 }
1313}
1314
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001315/// Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001316/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001317void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001318 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001319 bool FullyRemove, LockKind ReceivedKind,
1320 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001321 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001322 return;
1323
DeLesley Hutchins42665222014-08-04 16:10:59 +00001324 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001325 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001326 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001327 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001328 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001329
Aaron Ballmandf115d92014-03-21 14:48:48 +00001330 // Generic lock removal doesn't care about lock kind mismatches, but
1331 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001332 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1333 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1334 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001335 }
1336
Ed Schoutenca988742014-09-03 06:00:11 +00001337 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1338 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001339}
1340
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001341/// Extract the list of mutexIDs from the attribute on an expression,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001342/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001343template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001344void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001345 const Expr *Exp, const NamedDecl *D,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001346 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001347 if (Attr->args_size() == 0) {
1348 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001349 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1350 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001351 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1352 return;
1353 }
1354 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001355 if (!Cp.shouldIgnore())
1356 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001357 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001358 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001359
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001360 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001361 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1362 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001363 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001364 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001365 }
1366 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001367 if (!Cp.shouldIgnore())
1368 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001369 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001370}
1371
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001372/// Extract the list of mutexIDs from a trylock attribute. If the
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001373/// trylock applies to the given edge, then push them onto Mtxs, discarding
1374/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001375template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001376void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001377 const Expr *Exp, const NamedDecl *D,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001378 const CFGBlock *PredBlock,
1379 const CFGBlock *CurrBlock,
1380 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001381 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001382 bool branch = false;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001383 if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001384 branch = BLE->getValue();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001385 else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001386 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001387
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001388 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001389 if (Neg)
1390 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001391
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001392 // If we've taken the trylock branch, then add the lock
1393 int i = 0;
1394 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1395 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001396 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001397 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001398 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001399}
1400
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001401static bool getStaticBooleanValue(Expr *E, bool &TCond) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001402 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1403 TCond = false;
1404 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001405 } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001406 TCond = BLE->getValue();
1407 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001408 } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001409 TCond = ILE->getValue().getBoolValue();
1410 return true;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001411 } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001412 return getStaticBooleanValue(CE->getSubExpr(), TCond);
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001413 return false;
1414}
1415
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001416// If Cond can be traced back to a function call, return the call expression.
1417// The negate variable should be called with false, and will be set to true
1418// if the function call is negated, e.g. if (!mu.tryLock(...))
1419const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1420 LocalVarContext C,
1421 bool &Negate) {
1422 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001423 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001424
Aaron Puchert7146b002018-10-03 11:58:19 +00001425 if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
1426 if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
1427 return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001428 return CallExp;
Aaron Puchert7146b002018-10-03 11:58:19 +00001429 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001430 else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001431 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001432 else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001433 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
Bill Wendling7c44da22018-10-31 03:48:47 +00001434 else if (const auto *FE = dyn_cast<FullExpr>(Cond))
1435 return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001436 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001437 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1438 return getTrylockCallExpr(E, C, Negate);
1439 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001440 else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001441 if (UOP->getOpcode() == UO_LNot) {
1442 Negate = !Negate;
1443 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1444 }
Craig Topper25542942014-05-20 04:30:07 +00001445 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001446 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001447 else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001448 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1449 if (BOP->getOpcode() == BO_NE)
1450 Negate = !Negate;
1451
1452 bool TCond = false;
1453 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1454 if (!TCond) Negate = !Negate;
1455 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1456 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001457 TCond = false;
1458 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001459 if (!TCond) Negate = !Negate;
1460 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1461 }
Craig Topper25542942014-05-20 04:30:07 +00001462 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001463 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001464 if (BOP->getOpcode() == BO_LAnd) {
1465 // LHS must have been evaluated in a different block.
1466 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1467 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001468 if (BOP->getOpcode() == BO_LOr)
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001469 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
Craig Topper25542942014-05-20 04:30:07 +00001470 return nullptr;
Aaron Puchertb0a2a0c2018-10-06 01:09:28 +00001471 } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
1472 bool TCond, FCond;
1473 if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
1474 getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
1475 if (TCond && !FCond)
1476 return getTrylockCallExpr(COP->getCond(), C, Negate);
1477 if (!TCond && FCond) {
1478 Negate = !Negate;
1479 return getTrylockCallExpr(COP->getCond(), C, Negate);
1480 }
1481 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001482 }
Craig Topper25542942014-05-20 04:30:07 +00001483 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001484}
1485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001486/// Find the lockset that holds on the edge between PredBlock
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001487/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1488/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001489void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1490 const FactSet &ExitSet,
1491 const CFGBlock *PredBlock,
1492 const CFGBlock *CurrBlock) {
1493 Result = ExitSet;
1494
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001495 const Stmt *Cond = PredBlock->getTerminatorCondition();
Aaron Puchertb0a2a0c2018-10-06 01:09:28 +00001496 // We don't acquire try-locks on ?: branches, only when its result is used.
1497 if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminator()))
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001498 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001499
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001500 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001501 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1502 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001503 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001504
Aaron Puchert68c7fcd2018-08-23 21:13:32 +00001505 const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001506 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001507 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001508
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001509 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001510 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001511 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001512
DeLesley Hutchins42665222014-08-04 16:10:59 +00001513 CapExprSet ExclusiveLocksToAdd;
1514 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001515
1516 // If the condition is a call to a Trylock function, then grab the attributes
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001517 for (const auto *Attr : FunDecl->attrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001518 switch (Attr->getKind()) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00001519 case attr::TryAcquireCapability: {
1520 auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1521 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1522 Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1523 Negate);
1524 CapDiagKind = ClassifyDiagnostic(A);
1525 break;
1526 };
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001527 case attr::ExclusiveTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001528 const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001529 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1530 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001531 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001532 break;
1533 }
1534 case attr::SharedTrylockFunction: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001535 const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001536 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001537 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001538 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001539 break;
1540 }
1541 default:
1542 break;
1543 }
1544 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001545
1546 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001547 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001548 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001549 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1550 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001551 CapDiagKind);
1552 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001553 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1554 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001555 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001556}
1557
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001558namespace {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001559
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001560/// We use this class to visit different types of expressions in
Caitlin Sadowski33208342011-09-09 16:11:56 +00001561/// CFGBlocks, and build up the lockset.
1562/// An expression may cause us to add or remove locks from the lockset, or else
1563/// output error messages related to missing locks.
1564/// FIXME: In future, we may be able to not inherit from a visitor.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001565class BuildLockset : public ConstStmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001566 friend class ThreadSafetyAnalyzer;
1567
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001568 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001569 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001570 LocalVariableMap::Context LVarCtx;
1571 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001572
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001573 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001574 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001575 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001576 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001577 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1578 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001579
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001580 void checkAccess(const Expr *Exp, AccessKind AK,
1581 ProtectedOperationKind POK = POK_VarAccess);
1582 void checkPtAccess(const Expr *Exp, AccessKind AK,
1583 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001584
Aaron Puchertcd37c092018-08-23 21:53:04 +00001585 void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Aaron Puchert35389e52018-10-04 23:51:14 +00001586 void examineArguments(const FunctionDecl *FD,
1587 CallExpr::const_arg_iterator ArgBegin,
1588 CallExpr::const_arg_iterator ArgEnd,
1589 bool SkipFirstParam = false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001590
Caitlin Sadowski33208342011-09-09 16:11:56 +00001591public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001592 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
Aaron Puchertcd37c092018-08-23 21:53:04 +00001593 : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001594 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001595
Aaron Puchertcd37c092018-08-23 21:53:04 +00001596 void VisitUnaryOperator(const UnaryOperator *UO);
1597 void VisitBinaryOperator(const BinaryOperator *BO);
1598 void VisitCastExpr(const CastExpr *CE);
1599 void VisitCallExpr(const CallExpr *Exp);
1600 void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1601 void VisitDeclStmt(const DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001602};
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001603
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001604} // namespace
DeLesley Hutchins42665222014-08-04 16:10:59 +00001605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001606/// Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001607/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001608void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001609 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001610 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001611 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001612 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001613
DeLesley Hutchins42665222014-08-04 16:10:59 +00001614 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1615 if (Cp.isInvalid()) {
1616 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001617 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001618 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001619 return;
1620 }
1621
DeLesley Hutchins42665222014-08-04 16:10:59 +00001622 if (Cp.negative()) {
1623 // Negative capabilities act like locks excluded
Aaron Puchert969f32d2018-09-21 23:08:30 +00001624 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001625 if (LDat) {
1626 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001627 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001628 return;
1629 }
1630
1631 // If this does not refer to a negative capability in the same class,
1632 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001633 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001634 return;
1635
1636 // Otherwise the negative requirement must be propagated to the caller.
1637 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1638 if (!LDat) {
1639 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001640 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001641 }
1642 return;
1643 }
1644
Aaron Puchert969f32d2018-09-21 23:08:30 +00001645 const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001646 bool NoError = true;
1647 if (!LDat) {
1648 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001649 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1650 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001651 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001652 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001653 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001654 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1655 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001656 } else {
1657 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001658 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1659 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001660 }
1661 NoError = false;
1662 }
1663 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001664 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001665 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1666 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001667 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001668}
1669
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001670/// Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001671void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001672 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001673 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1674 if (Cp.isInvalid()) {
1675 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1676 return;
1677 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001678 return;
1679 }
1680
Aaron Puchert969f32d2018-09-21 23:08:30 +00001681 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001682 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001683 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001684 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1685 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001686}
1687
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001688/// Checks guarded_by and pt_guarded_by attributes.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001689/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1690/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1691/// Similarly, we check if the access is to an expression that dereferences
1692/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001693void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1694 ProtectedOperationKind POK) {
Richard Smith4baaa5a2016-12-03 01:14:32 +00001695 Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001696
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001697 SourceLocation Loc = Exp->getExprLoc();
1698
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001699 // Local variables of reference type cannot be re-assigned;
1700 // map them to their initializer.
1701 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1702 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1703 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1704 if (const auto *E = VD->getInit()) {
Aaron Ballman57deab72018-08-24 18:48:35 +00001705 // Guard against self-initialization. e.g., int &i = i;
1706 if (E == Exp)
1707 break;
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001708 Exp = E;
1709 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001710 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001711 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001712 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001713 }
1714
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001715 if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001716 // For dereferences
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001717 if (UO->getOpcode() == UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001718 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001719 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001720 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001721
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001722 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001723 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001724 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001725 }
1726
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001727 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001728 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001729 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001730 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001731 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001732 }
1733
Caitlin Sadowski33208342011-09-09 16:11:56 +00001734 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001735 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001736 return;
1737
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001738 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001739 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001740 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001741
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001742 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001743 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001744 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001745}
1746
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001747/// Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001748/// POK is the same operationKind that was passed to checkAccess.
1749void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1750 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001751 while (true) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001752 if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001753 Exp = PE->getSubExpr();
1754 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001755 }
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001756 if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001757 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1758 // If it's an actual array, and not a pointer, then it's elements
1759 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001760 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001761 return;
1762 }
1763 Exp = CE->getSubExpr();
1764 continue;
1765 }
1766 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001767 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001768
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001769 // Pass by reference warnings are under a different flag.
1770 ProtectedOperationKind PtPOK = POK_VarDereference;
1771 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1772
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001773 const ValueDecl *D = getValueDecl(Exp);
1774 if (!D || !D->hasAttrs())
1775 return;
1776
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001777 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001778 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001779 Exp->getExprLoc());
1780
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001781 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001782 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001783 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001784}
1785
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001786/// Process a function call, method call, constructor call,
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001787/// or destructor call. This involves looking at the attributes on the
1788/// corresponding function/method/constructor/destructor, issuing warnings,
1789/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001790///
1791/// FIXME: For classes annotated with one of the guarded annotations, we need
1792/// to treat const method calls as reads and non-const method calls as writes,
1793/// and check that the appropriate locks are held. Non-const method calls with
1794/// the same signature as const method calls can be also treated as reads.
1795///
Aaron Puchertcd37c092018-08-23 21:53:04 +00001796void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1797 VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001798 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001799 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1800 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001801 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
Aaron Ballmane0449042014-04-01 21:43:23 +00001802 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001803
Richard Smithe97654b2018-01-11 22:13:57 +00001804 // Figure out if we're constructing an object of scoped lockable class
Haojian Wu74e0f402018-08-13 12:50:30 +00001805 bool isScopedVar = false;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001806 if (VD) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001807 if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001808 const CXXRecordDecl* PD = CD->getParent();
1809 if (PD && PD->hasAttr<ScopedLockableAttr>())
Haojian Wu74e0f402018-08-13 12:50:30 +00001810 isScopedVar = true;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001811 }
1812 }
1813
Aaron Ballman1b587592018-07-26 13:03:16 +00001814 for(const Attr *At : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001815 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001816 // When we encounter a lock function, we need to add the lock to our
1817 // lockset.
1818 case attr::AcquireCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001819 const auto *A = cast<AcquireCapabilityAttr>(At);
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001820 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1821 : ExclusiveLocksToAdd,
1822 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001823
1824 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001825 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001826 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001827
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001828 // An assert will add a lock to the lockset, but will not generate
1829 // a warning if it is already there, and will not generate a warning
1830 // if it is not removed.
1831 case attr::AssertExclusiveLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001832 const auto *A = cast<AssertExclusiveLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001833
DeLesley Hutchins42665222014-08-04 16:10:59 +00001834 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001835 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001836 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001837 Analyzer->addLock(FSet,
1838 llvm::make_unique<LockableFactEntry>(
1839 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001840 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001841 break;
1842 }
1843 case attr::AssertSharedLock: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001844 const auto *A = cast<AssertSharedLockAttr>(At);
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001845
DeLesley Hutchins42665222014-08-04 16:10:59 +00001846 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001847 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001848 for (const auto &AssertLock : AssertLocks)
Josh Gaoec1369e2017-08-08 19:44:34 +00001849 Analyzer->addLock(FSet,
1850 llvm::make_unique<LockableFactEntry>(
1851 AssertLock, LK_Shared, Loc, false, true),
1852 ClassifyDiagnostic(A));
1853 break;
1854 }
1855
1856 case attr::AssertCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001857 const auto *A = cast<AssertCapabilityAttr>(At);
Josh Gaoec1369e2017-08-08 19:44:34 +00001858 CapExprSet AssertLocks;
1859 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1860 for (const auto &AssertLock : AssertLocks)
1861 Analyzer->addLock(FSet,
1862 llvm::make_unique<LockableFactEntry>(
1863 AssertLock,
1864 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1865 false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001866 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001867 break;
1868 }
1869
Caitlin Sadowski33208342011-09-09 16:11:56 +00001870 // When we encounter an unlock function, we need to remove unlocked
1871 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001872 case attr::ReleaseCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001873 const auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001874 if (A->isGeneric())
1875 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1876 else if (A->isShared())
1877 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1878 else
1879 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001880
1881 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001882 break;
1883 }
1884
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001885 case attr::RequiresCapability: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001886 const auto *A = cast<RequiresCapabilityAttr>(At);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001887 for (auto *Arg : A->args()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001888 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001889 POK_FunctionCall, ClassifyDiagnostic(A),
1890 Exp->getExprLoc());
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001891 // use for adopting a lock
Haojian Wu74e0f402018-08-13 12:50:30 +00001892 if (isScopedVar) {
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001893 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1894 : ScopedExclusiveReqs,
1895 A, Exp, D, VD);
1896 }
1897 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001898 break;
1899 }
1900
1901 case attr::LocksExcluded: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001902 const auto *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001903 for (auto *Arg : A->args())
1904 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001905 break;
1906 }
1907
Alp Tokerd4733632013-12-05 04:47:09 +00001908 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001909 default:
1910 break;
1911 }
1912 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001913
Aaron Ballman1b587592018-07-26 13:03:16 +00001914 // Remove locks first to allow lock upgrading/downgrading.
1915 // FIXME -- should only fully remove if the attribute refers to 'this'.
1916 bool Dtor = isa<CXXDestructorDecl>(D);
1917 for (const auto &M : ExclusiveLocksToRemove)
1918 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1919 for (const auto &M : SharedLocksToRemove)
1920 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1921 for (const auto &M : GenericLocksToRemove)
1922 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1923
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001924 // Add locks.
Haojian Wu74e0f402018-08-13 12:50:30 +00001925 for (const auto &M : ExclusiveLocksToAdd)
1926 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1927 M, LK_Exclusive, Loc, isScopedVar),
1928 CapDiagKind);
1929 for (const auto &M : SharedLocksToAdd)
1930 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1931 M, LK_Shared, Loc, isScopedVar),
1932 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001933
Haojian Wu74e0f402018-08-13 12:50:30 +00001934 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001935 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001936 SourceLocation MLoc = VD->getLocation();
1937 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001938 // FIXME: does this store a pointer to DRE?
1939 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001940
1941 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1942 std::back_inserter(ExclusiveLocksToAdd));
1943 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1944 std::back_inserter(SharedLocksToAdd));
Ed Schoutenca988742014-09-03 06:00:11 +00001945 Analyzer->addLock(FSet,
1946 llvm::make_unique<ScopedLockableFactEntry>(
Aaron Puchert6a68efc2018-12-16 14:15:30 +00001947 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd,
1948 ExclusiveLocksToRemove, SharedLocksToRemove),
Ed Schoutenca988742014-09-03 06:00:11 +00001949 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001950 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001951}
1952
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001953/// For unary operations which read and write a variable, we need to
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001954/// check whether we hold any required mutexes. Reads are checked in
1955/// VisitCastExpr.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001956void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001957 switch (UO->getOpcode()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00001958 case UO_PostDec:
1959 case UO_PostInc:
1960 case UO_PreDec:
1961 case UO_PreInc:
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001962 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001963 break;
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001964 default:
1965 break;
1966 }
1967}
1968
1969/// For binary operations which assign to a variable (writes), we need to check
1970/// whether we hold any required mutexes.
1971/// FIXME: Deal with non-primitive types.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001972void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001973 if (!BO->isAssignmentOp())
1974 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001975
1976 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001977 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001978
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001979 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001980}
1981
1982/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1983/// need to ensure we hold any required mutexes.
1984/// FIXME: Deal with non-primitive types.
Aaron Puchertcd37c092018-08-23 21:53:04 +00001985void BuildLockset::VisitCastExpr(const CastExpr *CE) {
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001986 if (CE->getCastKind() != CK_LValueToRValue)
1987 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001988 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001989}
1990
Aaron Puchert35389e52018-10-04 23:51:14 +00001991void BuildLockset::examineArguments(const FunctionDecl *FD,
1992 CallExpr::const_arg_iterator ArgBegin,
1993 CallExpr::const_arg_iterator ArgEnd,
1994 bool SkipFirstParam) {
1995 // Currently we can't do anything if we don't know the function declaration.
1996 if (!FD)
1997 return;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001998
Aaron Puchert35389e52018-10-04 23:51:14 +00001999 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
2000 // only turns off checking within the body of a function, but we also
2001 // use it to turn off checking in arguments to the function. This
2002 // could result in some false negatives, but the alternative is to
2003 // create yet another attribute.
2004 if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
2005 return;
2006
2007 const ArrayRef<ParmVarDecl *> Params = FD->parameters();
2008 auto Param = Params.begin();
2009 if (SkipFirstParam)
2010 ++Param;
2011
2012 // There can be default arguments, so we stop when one iterator is at end().
2013 for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd;
2014 ++Param, ++Arg) {
2015 QualType Qt = (*Param)->getType();
2016 if (Qt->isReferenceType())
2017 checkAccess(*Arg, AK_Read, POK_PassByRef);
2018 }
2019}
2020
2021void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002022 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2023 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002024 // ME can be null when calling a method pointer
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002025 const CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002026
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002027 if (ME && MD) {
2028 if (ME->isArrow()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002029 if (MD->isConst())
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002030 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002031 else // FIXME -- should be AK_Written
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002032 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002033 } else {
2034 if (MD->isConst())
2035 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2036 else // FIXME -- should be AK_Written
2037 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002038 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002039 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002040
Aaron Puchert35389e52018-10-04 23:51:14 +00002041 examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
2042 } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002043 auto OEop = OE->getOperator();
2044 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002045 case OO_Equal: {
2046 const Expr *Target = OE->getArg(0);
2047 const Expr *Source = OE->getArg(1);
2048 checkAccess(Target, AK_Written);
2049 checkAccess(Source, AK_Read);
2050 break;
2051 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00002052 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00002053 case OO_Arrow:
Aaron Puchert35389e52018-10-04 23:51:14 +00002054 case OO_Subscript:
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002055 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
2056 // Grrr. operator* can be multiplication...
Aaron Puchert35389e52018-10-04 23:51:14 +00002057 checkPtAccess(OE->getArg(0), AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002058 }
Aaron Puchert35389e52018-10-04 23:51:14 +00002059 LLVM_FALLTHROUGH;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002060 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002061 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00002062 const Expr *Obj = OE->getArg(0);
2063 checkAccess(Obj, AK_Read);
Aaron Puchert35389e52018-10-04 23:51:14 +00002064 // Check the remaining arguments. For method operators, the first
2065 // argument is the implicit self argument, and doesn't appear in the
2066 // FunctionDecl, but for non-methods it does.
2067 const FunctionDecl *FD = OE->getDirectCallee();
2068 examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
2069 /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002070 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002071 }
2072 }
Aaron Puchert35389e52018-10-04 23:51:14 +00002073 } else {
2074 examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00002075 }
2076
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002077 auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002078 if(!D || !D->hasAttrs())
2079 return;
2080 handleCall(Exp, D);
2081}
2082
Aaron Puchertcd37c092018-08-23 21:53:04 +00002083void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00002084 const CXXConstructorDecl *D = Exp->getConstructor();
2085 if (D && D->isCopyConstructor()) {
2086 const Expr* Source = Exp->getArg(0);
2087 checkAccess(Source, AK_Read);
Aaron Puchert35389e52018-10-04 23:51:14 +00002088 } else {
2089 examineArguments(D, Exp->arg_begin(), Exp->arg_end());
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00002090 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002091}
2092
Richard Smithe97654b2018-01-11 22:13:57 +00002093static CXXConstructorDecl *
2094findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2095 // Prefer a move constructor over a copy constructor. If there's more than
2096 // one copy constructor or more than one move constructor, we arbitrarily
2097 // pick the first declared such constructor rather than trying to guess which
2098 // one is more appropriate.
2099 CXXConstructorDecl *CopyCtor = nullptr;
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002100 for (auto *Ctor : RD->ctors()) {
Richard Smithe97654b2018-01-11 22:13:57 +00002101 if (Ctor->isDeleted())
2102 continue;
2103 if (Ctor->isMoveConstructor())
2104 return Ctor;
2105 if (!CopyCtor && Ctor->isCopyConstructor())
2106 CopyCtor = Ctor;
2107 }
2108 return CopyCtor;
2109}
2110
2111static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2112 SourceLocation Loc) {
2113 ASTContext &Ctx = CD->getASTContext();
2114 return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2115 CD, true, Args, false, false, false, false,
2116 CXXConstructExpr::CK_Complete,
2117 SourceRange(Loc, Loc));
2118}
2119
Aaron Puchertcd37c092018-08-23 21:53:04 +00002120void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002121 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002122 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002123
Aaron Ballman9ee54d12014-05-14 20:42:13 +00002124 for (auto *D : S->getDeclGroup()) {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002125 if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002126 Expr *E = VD->getInit();
Richard Smithe97654b2018-01-11 22:13:57 +00002127 if (!E)
2128 continue;
2129 E = E->IgnoreParens();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00002130
Richard Smithe97654b2018-01-11 22:13:57 +00002131 // handle constructors that involve temporaries
2132 if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2133 E = EWC->getSubExpr();
2134 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2135 E = BTE->getSubExpr();
2136
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002137 if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2138 const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002139 if (!CtorD || !CtorD->hasAttrs())
Richard Smithe97654b2018-01-11 22:13:57 +00002140 continue;
2141 handleCall(E, CtorD, VD);
2142 } else if (isa<CallExpr>(E) && E->isRValue()) {
2143 // If the object is initialized by a function call that returns a
2144 // scoped lockable by value, use the attributes on the copy or move
2145 // constructor to figure out what effect that should have on the
2146 // lockset.
2147 // FIXME: Is this really the best way to handle this situation?
2148 auto *RD = E->getType()->getAsCXXRecordDecl();
2149 if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2150 continue;
2151 CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2152 if (!CtorD || !CtorD->hasAttrs())
2153 continue;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002154 handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002155 }
2156 }
2157 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002158}
2159
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002160/// Compute the intersection of two locksets and issue warnings for any
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002161/// locks in the symmetric difference.
2162///
2163/// This function is used at a merge point in the CFG when comparing the lockset
2164/// of each branch being merged. For example, given the following sequence:
2165/// A; if () then B; else C; D; we need to check that the lockset after B and C
2166/// are the same. In the event of a difference, we use the intersection of these
2167/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002168///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002169/// \param FSet1 The first lockset.
2170/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002171/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002172/// \param LEK1 The error message to report if a mutex is missing from LSet1
2173/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002174void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2175 const FactSet &FSet2,
2176 SourceLocation JoinLoc,
2177 LockErrorKind LEK1,
2178 LockErrorKind LEK2,
2179 bool Modify) {
2180 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002181
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002182 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002183 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002184 const FactEntry *LDat1 = nullptr;
2185 const FactEntry *LDat2 = &FactMan[Fact];
2186 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2187 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002188
DeLesley Hutchins42665222014-08-04 16:10:59 +00002189 if (LDat1) {
2190 if (LDat1->kind() != LDat2->kind()) {
2191 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2192 LDat2->loc(), LDat1->loc());
2193 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002194 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002195 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002196 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002197 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00002198 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002199 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002200 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002201 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002202 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00002203 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2204 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002205 }
2206 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002207
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002208 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002209 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002210 const FactEntry *LDat1 = &FactMan[Fact];
2211 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002212
DeLesley Hutchins42665222014-08-04 16:10:59 +00002213 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00002214 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2215 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002216 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00002217 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002218 }
2219 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002220}
2221
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002222// Return true if block B never continues to its successors.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002223static bool neverReturns(const CFGBlock *B) {
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002224 if (B->hasNoReturnElement())
2225 return true;
2226 if (B->empty())
2227 return false;
2228
2229 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002230 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2231 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002232 return true;
2233 }
2234 return false;
2235}
2236
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002237/// Check a function's CFG for thread-safety violations.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002238///
2239/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2240/// at the end of each block, and issue warnings for thread safety violations.
2241/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002242void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002243 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2244 // For now, we just use the walker to set things up.
2245 threadSafety::CFGWalker walker;
2246 if (!walker.init(AC))
2247 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002248
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002249 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002250 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002251
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002252 CFG *CFGraph = walker.getGraph();
2253 const NamedDecl *D = walker.getDecl();
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002254 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00002255 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002256
Aaron Ballman9ead1242013-12-19 02:39:40 +00002257 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002258 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002259
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002260 // FIXME: Do something a bit more intelligent inside constructor and
2261 // destructor code. Constructors and destructors must assume unique access
2262 // to 'this', so checks on member variable access is disabled, but we should
2263 // still enable checks on other objects.
2264 if (isa<CXXConstructorDecl>(D))
2265 return; // Don't check inside constructors.
2266 if (isa<CXXDestructorDecl>(D))
2267 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002268
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002269 Handler.enterFunction(CurrentFunction);
2270
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002271 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002272 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002273
2274 // We need to explore the CFG via a "topological" ordering.
2275 // That way, we will be guaranteed to have information about required
2276 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002277 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002278 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002279
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002280 // Mark entry block as reachable
2281 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2282
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002283 // Compute SSA names for local variables
2284 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2285
Richard Smith92286672012-02-03 04:45:26 +00002286 // Fill in source locations for all CFGBlocks.
2287 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2288
DeLesley Hutchins42665222014-08-04 16:10:59 +00002289 CapExprSet ExclusiveLocksAcquired;
2290 CapExprSet SharedLocksAcquired;
2291 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002292
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002293 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002294 // to initial lockset. Also turn off checking for lock and unlock functions.
2295 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002296 if (!SortedGraph->empty() && D->hasAttrs()) {
2297 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002298 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002299
DeLesley Hutchins42665222014-08-04 16:10:59 +00002300 CapExprSet ExclusiveLocksToAdd;
2301 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002302 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002303
2304 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002305 for (const auto *Attr : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002306 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002307 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002308 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00002309 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002310 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002311 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002312 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2313 // We must ignore such methods.
2314 if (A->args_size() == 0)
2315 return;
Aaron Ballmaneaa18e62018-08-03 19:37:45 +00002316 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2317 nullptr, D);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002318 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002319 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002320 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002321 if (A->args_size() == 0)
2322 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002323 getMutexIDs(A->isShared() ? SharedLocksAcquired
2324 : ExclusiveLocksAcquired,
2325 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002326 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002327 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002328 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002329 return;
2330 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
Aaron Ballman81d07fc2018-04-12 17:53:21 +00002331 // Don't try to check trylock functions for now.
2332 return;
2333 } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2334 // Don't try to check trylock functions for now.
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002335 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002336 }
2337 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002338
2339 // FIXME -- Loc can be wrong here.
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002340 for (const auto &Mu : ExclusiveLocksToAdd) {
2341 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2342 Entry->setDeclared(true);
2343 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2344 }
2345 for (const auto &Mu : SharedLocksToAdd) {
2346 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2347 Entry->setDeclared(true);
2348 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2349 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002350 }
2351
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002352 for (const auto *CurrBlock : *SortedGraph) {
Aaron Puchert88d85362018-09-22 21:56:16 +00002353 unsigned CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002354 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002355
2356 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002357 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002358
2359 // Iterate through the predecessor blocks and warn if the lockset for all
2360 // predecessors is not the same. We take the entry lockset of the current
2361 // block to be the intersection of all previous locksets.
2362 // FIXME: By keeping the intersection, we may output more errors in future
2363 // for a lock which is not in the intersection, but was in the union. We
2364 // may want to also keep the union in future. As an example, let's say
2365 // the intersection contains Mutex L, and the union contains L and M.
2366 // Later we unlock M. At this point, we would output an error because we
2367 // never locked M; although the real error is probably that we forgot to
2368 // lock M on all code paths. Conversely, let's say that later we lock M.
2369 // In this case, we should compare against the intersection instead of the
2370 // union because the real error is probably that we forgot to unlock M on
2371 // all code paths.
2372 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002373 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002374 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2375 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002376 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002377 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002378 continue;
2379
Aaron Puchert88d85362018-09-22 21:56:16 +00002380 unsigned PrevBlockID = (*PI)->getBlockID();
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002381 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2382
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002383 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002384 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002385 continue;
2386
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002387 // Okay, we can reach this block from the entry.
2388 CurrBlockInfo->Reachable = true;
2389
Richard Smith815b29d2012-02-03 03:30:07 +00002390 // If the previous block ended in a 'continue' or 'break' statement, then
2391 // a difference in locksets is probably due to a bug in that block, rather
2392 // than in some other predecessor. In that case, keep the other
2393 // predecessor's lockset.
2394 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2395 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2396 SpecialBlocks.push_back(*PI);
2397 continue;
2398 }
2399 }
2400
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002401 FactSet PrevLockset;
2402 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002403
Caitlin Sadowski33208342011-09-09 16:11:56 +00002404 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002405 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002406 LocksetInitialized = true;
2407 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002408 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2409 CurrBlockInfo->EntryLoc,
2410 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002411 }
2412 }
2413
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002414 // Skip rest of block if it's not reachable.
2415 if (!CurrBlockInfo->Reachable)
2416 continue;
2417
Richard Smith815b29d2012-02-03 03:30:07 +00002418 // Process continue and break blocks. Assume that the lockset for the
2419 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002420 for (const auto *PrevBlock : SpecialBlocks) {
Aaron Puchert88d85362018-09-22 21:56:16 +00002421 unsigned PrevBlockID = PrevBlock->getBlockID();
Richard Smith815b29d2012-02-03 03:30:07 +00002422 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2423
2424 if (!LocksetInitialized) {
2425 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2426 LocksetInitialized = true;
2427 } else {
2428 // Determine whether this edge is a loop terminator for diagnostic
2429 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2430 // it might also be part of a switch. Also, a subsequent destructor
2431 // might add to the lockset, in which case the real issue might be a
2432 // double lock on the other path.
2433 const Stmt *Terminator = PrevBlock->getTerminator();
2434 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2435
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002436 FactSet PrevLockset;
2437 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2438 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002439
Richard Smith815b29d2012-02-03 03:30:07 +00002440 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002441 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2442 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002443 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002444 : LEK_LockedSomePredecessors,
2445 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002446 }
2447 }
2448
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002449 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2450
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002451 // Visit all the statements in the basic block.
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002452 for (const auto &BI : *CurrBlock) {
2453 switch (BI.getKind()) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002454 case CFGElement::Statement: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002455 CFGStmt CS = BI.castAs<CFGStmt>();
Aaron Puchertcd37c092018-08-23 21:53:04 +00002456 LocksetBuilder.Visit(CS.getStmt());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002457 break;
2458 }
2459 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2460 case CFGElement::AutomaticObjectDtor: {
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002461 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
Aaron Puchertcd37c092018-08-23 21:53:04 +00002462 const auto *DD = AD.getDestructorDecl(AC.getASTContext());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002463 if (!DD->hasAttrs())
2464 break;
2465
2466 // Create a dummy expression,
Eugene Zelenkobbe25312018-03-16 21:22:42 +00002467 auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
Richard Trieua1877592015-03-16 21:49:43 +00002468 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002469 VK_LValue, AD.getTriggerStmt()->getEndLoc());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002470 LocksetBuilder.handleCall(&DRE, DD);
2471 break;
2472 }
2473 default:
2474 break;
2475 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002476 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002477 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002478
2479 // For every back edge from CurrBlock (the end of the loop) to another block
2480 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2481 // the one held at the beginning of FirstLoopBlock. We can look up the
2482 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2483 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2484 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002485 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002486 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002487 continue;
2488
2489 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002490 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2491 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2492 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2493 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002494 LEK_LockedSomeLoopIterations,
2495 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002496 }
2497 }
2498
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002499 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2500 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002501
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002502 // Skip the final check if the exit block is unreachable.
2503 if (!Final->Reachable)
2504 return;
2505
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002506 // By default, we expect all locks held on entry to be held on exit.
2507 FactSet ExpectedExitSet = Initial->EntrySet;
2508
2509 // Adjust the expected exit set by adding or removing locks, as declared
2510 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2511 // issue the appropriate warning.
2512 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002513 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002514 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2515 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002516 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002517 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2518 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002519 for (const auto &Lock : LocksReleased)
2520 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002521
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002522 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002523 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002524 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002525 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002526 LEK_NotLockedAtEndOfFunction,
2527 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002528
2529 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002530}
2531
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002532/// Check a function's CFG for thread-safety violations.
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002533///
2534/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2535/// at the end of each block, and issue warnings for thread safety violations.
2536/// Each block in the CFG is traversed exactly once.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002537void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2538 ThreadSafetyHandler &Handler,
2539 BeforeSet **BSet) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002540 if (!*BSet)
2541 *BSet = new BeforeSet;
2542 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002543 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002544}
2545
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002546void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002548/// Helper function that returns a LockKind required for the given level
Caitlin Sadowski33208342011-09-09 16:11:56 +00002549/// of access.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002550LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002551 switch (AK) {
2552 case AK_Read :
2553 return LK_Shared;
2554 case AK_Written :
2555 return LK_Exclusive;
2556 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002557 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002558}