blob: 984a5d42adbf02e610defc818fc2e7e801f1deb6 [file] [log] [blame]
Caitlin Sadowski33208342011-09-09 16:11:56 +00001//===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
2//
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"
Caitlin Sadowski33208342011-09-09 16:11:56 +000020#include "clang/AST/DeclCXX.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Analysis/Analyses/PostOrderCFGView.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
Aaron Ballman7c192b42014-05-09 18:26:23 +000026#include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000027#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000028#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/AnalysisContext.h"
30#include "clang/Analysis/CFG.h"
31#include "clang/Analysis/CFGStmtMap.h"
DeLesley Hutchins3a8d6cf2012-07-03 19:47:18 +000032#include "clang/Basic/OperatorKinds.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000033#include "clang/Basic/SourceLocation.h"
34#include "clang/Basic/SourceManager.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000035#include "llvm/ADT/ImmutableMap.h"
36#include "llvm/ADT/PostOrderIterator.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000039#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000040#include <algorithm>
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000041#include <ostream>
42#include <sstream>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000043#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000044#include <vector>
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000045using namespace clang;
46using namespace threadSafety;
Caitlin Sadowski33208342011-09-09 16:11:56 +000047
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000048// Key method definition
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000049ThreadSafetyHandler::~ThreadSafetyHandler() {}
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000050
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000051namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000052class TILPrinter :
53 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000054
55
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000056/// Issue a warning about an invalid lock expression
57static void warnInvalidLock(ThreadSafetyHandler &Handler,
58 const Expr *MutexExp, const NamedDecl *D,
59 const Expr *DeclExp, StringRef Kind) {
60 SourceLocation Loc;
61 if (DeclExp)
62 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000063
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000064 // FIXME: add a note about the attribute location in MutexExp or D
65 if (Loc.isValid())
66 Handler.handleInvalidLockExp(Kind, Loc);
67}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000068
DeLesley Hutchins42665222014-08-04 16:10:59 +000069/// \brief A set of CapabilityInfo objects, which are compiled from the
70/// requires attributes on a function.
71class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000072public:
Aaron Ballmancea26092014-03-06 19:10:16 +000073 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000074 void push_back_nodup(const CapabilityExpr &CapE) {
75 iterator It = std::find_if(begin(), end(),
76 [=](const CapabilityExpr &CapE2) {
77 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000078 });
79 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +000080 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000081 }
82};
83
Ed Schoutenca988742014-09-03 06:00:11 +000084class FactManager;
85class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +000086
87/// \brief This is a helper class that stores a fact that is known at a
88/// particular point in program execution. Currently, a fact is a capability,
89/// along with additional information, such as where it was acquired, whether
90/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +000091///
DeLesley Hutchins42665222014-08-04 16:10:59 +000092/// FIXME: this analysis does not currently support either re-entrant
93/// locking or lock "upgrading" and "downgrading" between exclusive and
94/// shared.
95class FactEntry : public CapabilityExpr {
96private:
NAKAMURA Takumie9882cf2014-08-04 22:48:36 +000097 LockKind LKind; ///< exclusive or shared
98 SourceLocation AcquireLoc; ///< where it was acquired.
NAKAMURA Takumie9882cf2014-08-04 22:48:36 +000099 bool Asserted; ///< true if the lock was asserted
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000100 bool Declared; ///< true if the lock was declared
Caitlin Sadowski33208342011-09-09 16:11:56 +0000101
DeLesley Hutchins42665222014-08-04 16:10:59 +0000102public:
103 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000104 bool Asrt, bool Declrd = false)
105 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
106 Declared(Declrd) {}
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000107
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000108 virtual ~FactEntry() {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000109
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000110 LockKind kind() const { return LKind; }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000111 SourceLocation loc() const { return AcquireLoc; }
112 bool asserted() const { return Asserted; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000113 bool declared() const { return Declared; }
114
115 void setDeclared(bool D) { Declared = D; }
Ed Schoutenca988742014-09-03 06:00:11 +0000116
117 virtual void
118 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
119 SourceLocation JoinLoc, LockErrorKind LEK,
120 ThreadSafetyHandler &Handler) const = 0;
121 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
122 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
123 bool FullyRemove, ThreadSafetyHandler &Handler,
124 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000125
DeLesley Hutchins42665222014-08-04 16:10:59 +0000126 // Return true if LKind >= LK, where exclusive > shared
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000127 bool isAtLeast(LockKind LK) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000128 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000129 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000130};
131
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000132
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000133typedef unsigned short FactID;
134
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000135/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000136/// the analysis of a single routine.
137class FactManager {
138private:
Ed Schoutenca988742014-09-03 06:00:11 +0000139 std::vector<std::unique_ptr<FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000140
141public:
Ed Schoutenca988742014-09-03 06:00:11 +0000142 FactID newFact(std::unique_ptr<FactEntry> Entry) {
143 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000144 return static_cast<unsigned short>(Facts.size() - 1);
145 }
146
Ed Schoutenca988742014-09-03 06:00:11 +0000147 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
148 FactEntry &operator[](FactID F) { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000149};
150
151
152/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000153/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000154/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000155/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000156/// locks, so we can get away with doing a linear search for lookup. Note
157/// that a hashtable or map is inappropriate in this case, because lookups
158/// may involve partial pattern matches, rather than exact matches.
159class FactSet {
160private:
161 typedef SmallVector<FactID, 4> FactVec;
162
163 FactVec FactIDs;
164
165public:
166 typedef FactVec::iterator iterator;
167 typedef FactVec::const_iterator const_iterator;
168
169 iterator begin() { return FactIDs.begin(); }
170 const_iterator begin() const { return FactIDs.begin(); }
171
172 iterator end() { return FactIDs.end(); }
173 const_iterator end() const { return FactIDs.end(); }
174
175 bool isEmpty() const { return FactIDs.size() == 0; }
176
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000177 // Return true if the set contains only negative facts
178 bool isEmpty(FactManager &FactMan) const {
179 for (FactID FID : *this) {
180 if (!FactMan[FID].negative())
181 return false;
182 }
183 return true;
184 }
185
186 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
187
Ed Schoutenca988742014-09-03 06:00:11 +0000188 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
189 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000190 FactIDs.push_back(F);
191 return F;
192 }
193
DeLesley Hutchins42665222014-08-04 16:10:59 +0000194 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000195 unsigned n = FactIDs.size();
196 if (n == 0)
197 return false;
198
199 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000200 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000201 FactIDs[i] = FactIDs[n-1];
202 FactIDs.pop_back();
203 return true;
204 }
205 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000206 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000207 FactIDs.pop_back();
208 return true;
209 }
210 return false;
211 }
212
DeLesley Hutchins42665222014-08-04 16:10:59 +0000213 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000214 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000215 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000216 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000217 }
218
DeLesley Hutchins42665222014-08-04 16:10:59 +0000219 FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000220 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000221 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000222 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000223 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000224 }
225
DeLesley Hutchins42665222014-08-04 16:10:59 +0000226 FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000227 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000228 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000229 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000230 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000231 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000232
DeLesley Hutchins42665222014-08-04 16:10:59 +0000233 FactEntry *findPartialMatch(FactManager &FM,
234 const CapabilityExpr &CapE) const {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000235 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000236 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000237 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000238 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000239 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000240
241 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
242 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
243 return FM[ID].valueDecl() == Vd;
244 });
245 return I != end();
246 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000247};
248
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000249class ThreadSafetyAnalyzer;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000250} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000251
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000252namespace clang {
253namespace threadSafety {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000254class BeforeSet {
255private:
256 typedef SmallVector<const ValueDecl*, 4> BeforeVect;
257
258 struct BeforeInfo {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000259 BeforeInfo() : Visited(0) {}
Benjamin Kramer33e97602016-10-21 18:55:07 +0000260 BeforeInfo(BeforeInfo &&) = default;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000261
Reid Kleckner19ff5602015-11-20 19:08:30 +0000262 BeforeVect Vect;
263 int Visited;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000264 };
265
Reid Kleckner19ff5602015-11-20 19:08:30 +0000266 typedef llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>
267 BeforeMap;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000268 typedef llvm::DenseMap<const ValueDecl*, bool> CycleMap;
269
270public:
271 BeforeSet() { }
272
273 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
274 ThreadSafetyAnalyzer& Analyzer);
275
Reid Kleckner19ff5602015-11-20 19:08:30 +0000276 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
277 ThreadSafetyAnalyzer &Analyzer);
278
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000279 void checkBeforeAfter(const ValueDecl* Vd,
280 const FactSet& FSet,
281 ThreadSafetyAnalyzer& Analyzer,
282 SourceLocation Loc, StringRef CapKind);
283
284private:
285 BeforeMap BMap;
286 CycleMap CycMap;
287};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000288} // end namespace threadSafety
289} // end namespace clang
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000290
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000291namespace {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000292typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000293class LocalVariableMap;
294
Richard Smith92286672012-02-03 04:45:26 +0000295/// A side (entry or exit) of a CFG node.
296enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000297
298/// CFGBlockInfo is a struct which contains all the information that is
299/// maintained for each block in the CFG. See LocalVariableMap for more
300/// information about the contexts.
301struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000302 FactSet EntrySet; // Lockset held at entry to block
303 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000304 LocalVarContext EntryContext; // Context held at entry to block
305 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000306 SourceLocation EntryLoc; // Location of first statement in block
307 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000308 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000309 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000310
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000311 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000312 return Side == CBS_Entry ? EntrySet : ExitSet;
313 }
314 SourceLocation getLocation(CFGBlockSide Side) const {
315 return Side == CBS_Entry ? EntryLoc : ExitLoc;
316 }
317
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000318private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000319 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000320 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000321 { }
322
323public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000324 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000325};
326
327
328
329// A LocalVariableMap maintains a map from local variables to their currently
330// valid definitions. It provides SSA-like functionality when traversing the
331// CFG. Like SSA, each definition or assignment to a variable is assigned a
332// unique name (an integer), which acts as the SSA name for that definition.
333// The total set of names is shared among all CFG basic blocks.
334// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
335// with their SSA-names. Instead, we compute a Context for each point in the
336// code, which maps local variables to the appropriate SSA-name. This map
337// changes with each assignment.
338//
339// The map is computed in a single pass over the CFG. Subsequent analyses can
340// then query the map to find the appropriate Context for a statement, and use
341// that Context to look up the definitions of variables.
342class LocalVariableMap {
343public:
344 typedef LocalVarContext Context;
345
346 /// A VarDefinition consists of an expression, representing the value of the
347 /// variable, along with the context in which that expression should be
348 /// interpreted. A reference VarDefinition does not itself contain this
349 /// information, but instead contains a pointer to a previous VarDefinition.
350 struct VarDefinition {
351 public:
352 friend class LocalVariableMap;
353
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000354 const NamedDecl *Dec; // The original declaration for this variable.
355 const Expr *Exp; // The expression for this variable, OR
356 unsigned Ref; // Reference to another VarDefinition
357 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000358
359 bool isReference() { return !Exp; }
360
361 private:
362 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000363 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000364 : Dec(D), Exp(E), Ref(0), Ctx(C)
365 { }
366
367 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000368 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Craig Topper25542942014-05-20 04:30:07 +0000369 : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000370 { }
371 };
372
373private:
374 Context::Factory ContextFactory;
375 std::vector<VarDefinition> VarDefinitions;
376 std::vector<unsigned> CtxIndices;
377 std::vector<std::pair<Stmt*, Context> > SavedContexts;
378
379public:
380 LocalVariableMap() {
381 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000382 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000383 }
384
385 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000386 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000387 const unsigned *i = Ctx.lookup(D);
388 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000389 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000390 assert(*i < VarDefinitions.size());
391 return &VarDefinitions[*i];
392 }
393
394 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000395 /// NULL if the expression is not statically known. If successful, also
396 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000397 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000398 const unsigned *P = Ctx.lookup(D);
399 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000400 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000401
402 unsigned i = *P;
403 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000404 if (VarDefinitions[i].Exp) {
405 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000406 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000407 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000408 i = VarDefinitions[i].Ref;
409 }
Craig Topper25542942014-05-20 04:30:07 +0000410 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000411 }
412
413 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
414
415 /// Return the next context after processing S. This function is used by
416 /// clients of the class to get the appropriate context when traversing the
417 /// CFG. It must be called for every assignment or DeclStmt.
418 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
419 if (SavedContexts[CtxIndex+1].first == S) {
420 CtxIndex++;
421 Context Result = SavedContexts[CtxIndex].second;
422 return Result;
423 }
424 return C;
425 }
426
427 void dumpVarDefinitionName(unsigned i) {
428 if (i == 0) {
429 llvm::errs() << "Undefined";
430 return;
431 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000432 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000433 if (!Dec) {
434 llvm::errs() << "<<NULL>>";
435 return;
436 }
437 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000438 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000439 }
440
441 /// Dumps an ASCII representation of the variable map to llvm::errs()
442 void dump() {
443 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000444 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000445 unsigned Ref = VarDefinitions[i].Ref;
446
447 dumpVarDefinitionName(i);
448 llvm::errs() << " = ";
449 if (Exp) Exp->dump();
450 else {
451 dumpVarDefinitionName(Ref);
452 llvm::errs() << "\n";
453 }
454 }
455 }
456
457 /// Dumps an ASCII representation of a Context to llvm::errs()
458 void dumpContext(Context C) {
459 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000460 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000461 D->printName(llvm::errs());
462 const unsigned *i = C.lookup(D);
463 llvm::errs() << " -> ";
464 dumpVarDefinitionName(*i);
465 llvm::errs() << "\n";
466 }
467 }
468
469 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000470 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
471 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000472
473protected:
474 // Get the current context index
475 unsigned getContextIndex() { return SavedContexts.size()-1; }
476
477 // Save the current context for later replay
478 void saveContext(Stmt *S, Context C) {
479 SavedContexts.push_back(std::make_pair(S,C));
480 }
481
482 // Adds a new definition to the given context, and returns a new context.
483 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000484 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000485 assert(!Ctx.contains(D));
486 unsigned newID = VarDefinitions.size();
487 Context NewCtx = ContextFactory.add(Ctx, D, newID);
488 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
489 return NewCtx;
490 }
491
492 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000493 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000494 unsigned newID = VarDefinitions.size();
495 Context NewCtx = ContextFactory.add(Ctx, D, newID);
496 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
497 return NewCtx;
498 }
499
500 // Updates a definition only if that definition is already in the map.
501 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000502 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000503 if (Ctx.contains(D)) {
504 unsigned newID = VarDefinitions.size();
505 Context NewCtx = ContextFactory.remove(Ctx, D);
506 NewCtx = ContextFactory.add(NewCtx, D, newID);
507 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
508 return NewCtx;
509 }
510 return Ctx;
511 }
512
513 // Removes a definition from the context, but keeps the variable name
514 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000515 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000516 Context NewCtx = Ctx;
517 if (NewCtx.contains(D)) {
518 NewCtx = ContextFactory.remove(NewCtx, D);
519 NewCtx = ContextFactory.add(NewCtx, D, 0);
520 }
521 return NewCtx;
522 }
523
524 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000525 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000526 Context NewCtx = Ctx;
527 if (NewCtx.contains(D)) {
528 NewCtx = ContextFactory.remove(NewCtx, D);
529 }
530 return NewCtx;
531 }
532
533 Context intersectContexts(Context C1, Context C2);
534 Context createReferenceContext(Context C);
535 void intersectBackEdge(Context C1, Context C2);
536
537 friend class VarMapBuilder;
538};
539
540
541// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000542CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
543 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000544}
545
546
547/// Visitor which builds a LocalVariableMap
548class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
549public:
550 LocalVariableMap* VMap;
551 LocalVariableMap::Context Ctx;
552
553 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
554 : VMap(VM), Ctx(C) {}
555
556 void VisitDeclStmt(DeclStmt *S);
557 void VisitBinaryOperator(BinaryOperator *BO);
558};
559
560
561// Add new local variables to the variable map
562void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
563 bool modifiedCtx = false;
564 DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000565 for (const auto *D : DGrp) {
566 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
567 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000568
569 // Add local variables with trivial type to the variable map
570 QualType T = VD->getType();
571 if (T.isTrivialType(VD->getASTContext())) {
572 Ctx = VMap->addDefinition(VD, E, Ctx);
573 modifiedCtx = true;
574 }
575 }
576 }
577 if (modifiedCtx)
578 VMap->saveContext(S, Ctx);
579}
580
581// Update local variable definitions in variable map
582void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
583 if (!BO->isAssignmentOp())
584 return;
585
586 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
587
588 // Update the variable map and current context.
589 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
590 ValueDecl *VDec = DRE->getDecl();
591 if (Ctx.lookup(VDec)) {
592 if (BO->getOpcode() == BO_Assign)
593 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
594 else
595 // FIXME -- handle compound assignment operators
596 Ctx = VMap->clearDefinition(VDec, Ctx);
597 VMap->saveContext(BO, Ctx);
598 }
599 }
600}
601
602
603// Computes the intersection of two contexts. The intersection is the
604// set of variables which have the same definition in both contexts;
605// variables with different definitions are discarded.
606LocalVariableMap::Context
607LocalVariableMap::intersectContexts(Context C1, Context C2) {
608 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000609 for (const auto &P : C1) {
610 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000611 const unsigned *i2 = C2.lookup(Dec);
612 if (!i2) // variable doesn't exist on second path
613 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000614 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000615 Result = clearDefinition(Dec, Result);
616 }
617 return Result;
618}
619
620// For every variable in C, create a new variable that refers to the
621// definition in C. Return a new context that contains these new variables.
622// (We use this for a naive implementation of SSA on loop back-edges.)
623LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
624 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000625 for (const auto &P : C)
626 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000627 return Result;
628}
629
630// This routine also takes the intersection of C1 and C2, but it does so by
631// altering the VarDefinitions. C1 must be the result of an earlier call to
632// createReferenceContext.
633void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000634 for (const auto &P : C1) {
635 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000636 VarDefinition *VDef = &VarDefinitions[i1];
637 assert(VDef->isReference());
638
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000639 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000640 if (!i2 || (*i2 != i1))
641 VDef->Ref = 0; // Mark this variable as undefined
642 }
643}
644
645
646// Traverse the CFG in topological order, so all predecessors of a block
647// (excluding back-edges) are visited before the block itself. At
648// each point in the code, we calculate a Context, which holds the set of
649// variable definitions which are visible at that point in execution.
650// Visible variables are mapped to their definitions using an array that
651// contains all definitions.
652//
653// At join points in the CFG, the set is computed as the intersection of
654// the incoming sets along each edge, E.g.
655//
656// { Context | VarDefinitions }
657// int x = 0; { x -> x1 | x1 = 0 }
658// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
659// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
660// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
661// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
662//
663// This is essentially a simpler and more naive version of the standard SSA
664// algorithm. Those definitions that remain in the intersection are from blocks
665// that strictly dominate the current block. We do not bother to insert proper
666// phi nodes, because they are not used in our analysis; instead, wherever
667// a phi node would be required, we simply remove that definition from the
668// context (E.g. x above).
669//
670// The initial traversal does not capture back-edges, so those need to be
671// handled on a separate pass. Whenever the first pass encounters an
672// incoming back edge, it duplicates the context, creating new definitions
673// that refer back to the originals. (These correspond to places where SSA
674// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000675// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000676// node was actually required.) E.g.
677//
678// { Context | VarDefinitions }
679// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
680// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
681// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
682// ... { y -> y1 | x3 = 2, x2 = 1, ... }
683//
684void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000685 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000686 std::vector<CFGBlockInfo> &BlockInfo) {
687 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
688
689 CtxIndices.resize(CFGraph->getNumBlockIDs());
690
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000691 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000692 int CurrBlockID = CurrBlock->getBlockID();
693 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
694
695 VisitedBlocks.insert(CurrBlock);
696
697 // Calculate the entry context for the current block
698 bool HasBackEdges = false;
699 bool CtxInit = true;
700 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
701 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
702 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000703 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000704 HasBackEdges = true;
705 continue;
706 }
707
708 int PrevBlockID = (*PI)->getBlockID();
709 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
710
711 if (CtxInit) {
712 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
713 CtxInit = false;
714 }
715 else {
716 CurrBlockInfo->EntryContext =
717 intersectContexts(CurrBlockInfo->EntryContext,
718 PrevBlockInfo->ExitContext);
719 }
720 }
721
722 // Duplicate the context if we have back-edges, so we can call
723 // intersectBackEdges later.
724 if (HasBackEdges)
725 CurrBlockInfo->EntryContext =
726 createReferenceContext(CurrBlockInfo->EntryContext);
727
728 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000729 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000730 CurrBlockInfo->EntryIndex = getContextIndex();
731
732 // Visit all the statements in the basic block.
733 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
734 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
735 BE = CurrBlock->end(); BI != BE; ++BI) {
736 switch (BI->getKind()) {
737 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +0000738 CFGStmt CS = BI->castAs<CFGStmt>();
739 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000740 break;
741 }
742 default:
743 break;
744 }
745 }
746 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
747
748 // Mark variables on back edges as "unknown" if they've been changed.
749 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
750 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
751 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000752 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000753 continue;
754
755 CFGBlock *FirstLoopBlock = *SI;
756 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
757 Context LoopEnd = CurrBlockInfo->ExitContext;
758 intersectBackEdge(LoopBegin, LoopEnd);
759 }
760 }
761
762 // Put an extra entry at the end of the indexed context array
763 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000764 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000765}
766
Richard Smith92286672012-02-03 04:45:26 +0000767/// Find the appropriate source locations to use when producing diagnostics for
768/// each block in the CFG.
769static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000770 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000771 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000772 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000773 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
774
775 // Find the source location of the last statement in the block, if the
776 // block is not empty.
777 if (const Stmt *S = CurrBlock->getTerminator()) {
778 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
779 } else {
780 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
781 BE = CurrBlock->rend(); BI != BE; ++BI) {
782 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000783 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
784 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000785 break;
786 }
787 }
788 }
789
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000790 if (CurrBlockInfo->ExitLoc.isValid()) {
Richard Smith92286672012-02-03 04:45:26 +0000791 // This block contains at least one statement. Find the source location
792 // of the first statement in the block.
793 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
794 BE = CurrBlock->end(); BI != BE; ++BI) {
795 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000796 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
797 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000798 break;
799 }
800 }
801 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
802 CurrBlock != &CFGraph->getExit()) {
803 // The block is empty, and has a single predecessor. Use its exit
804 // location.
805 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
806 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
807 }
808 }
809}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000810
Ed Schoutenca988742014-09-03 06:00:11 +0000811class LockableFactEntry : public FactEntry {
812private:
813 bool Managed; ///< managed by ScopedLockable object
814
815public:
816 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
817 bool Mng = false, bool Asrt = false)
818 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
819
820 void
821 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
822 SourceLocation JoinLoc, LockErrorKind LEK,
823 ThreadSafetyHandler &Handler) const override {
824 if (!Managed && !asserted() && !negative() && !isUniversal()) {
825 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
826 LEK);
827 }
828 }
829
830 void handleUnlock(FactSet &FSet, FactManager &FactMan,
831 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
832 bool FullyRemove, ThreadSafetyHandler &Handler,
833 StringRef DiagKind) const override {
834 FSet.removeLock(FactMan, Cp);
835 if (!Cp.negative()) {
836 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
837 !Cp, LK_Exclusive, UnlockLoc));
838 }
839 }
840};
841
842class ScopedLockableFactEntry : public FactEntry {
843private:
844 SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
845
846public:
847 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
848 const CapExprSet &Excl, const CapExprSet &Shrd)
849 : FactEntry(CE, LK_Exclusive, Loc, false) {
850 for (const auto &M : Excl)
851 UnderlyingMutexes.push_back(M.sexpr());
852 for (const auto &M : Shrd)
853 UnderlyingMutexes.push_back(M.sexpr());
854 }
855
856 void
857 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
858 SourceLocation JoinLoc, LockErrorKind LEK,
859 ThreadSafetyHandler &Handler) const override {
860 for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
861 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
862 // If this scoped lock manages another mutex, and if the underlying
863 // mutex is still held, then warn about the underlying mutex.
864 Handler.handleMutexHeldEndOfScope(
865 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
866 }
867 }
868 }
869
870 void handleUnlock(FactSet &FSet, FactManager &FactMan,
871 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
872 bool FullyRemove, ThreadSafetyHandler &Handler,
873 StringRef DiagKind) const override {
874 assert(!Cp.negative() && "Managing object cannot be negative.");
875 for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
876 CapabilityExpr UnderCp(UnderlyingMutex, false);
877 auto UnderEntry = llvm::make_unique<LockableFactEntry>(
878 !UnderCp, LK_Exclusive, UnlockLoc);
879
880 if (FullyRemove) {
881 // We're destroying the managing object.
882 // Remove the underlying mutex if it exists; but don't warn.
883 if (FSet.findLock(FactMan, UnderCp)) {
884 FSet.removeLock(FactMan, UnderCp);
885 FSet.addLock(FactMan, std::move(UnderEntry));
886 }
887 } else {
888 // We're releasing the underlying mutex, but not destroying the
889 // managing object. Warn on dual release.
890 if (!FSet.findLock(FactMan, UnderCp)) {
891 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
892 UnlockLoc);
893 }
894 FSet.removeLock(FactMan, UnderCp);
895 FSet.addLock(FactMan, std::move(UnderEntry));
896 }
897 }
898 if (FullyRemove)
899 FSet.removeLock(FactMan, Cp);
900 }
901};
902
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000903/// \brief Class which implements the core thread safety analysis routines.
904class ThreadSafetyAnalyzer {
905 friend class BuildLockset;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000906 friend class threadSafety::BeforeSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000907
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000908 llvm::BumpPtrAllocator Bpa;
909 threadSafety::til::MemRegionRef Arena;
910 threadSafety::SExprBuilder SxBuilder;
911
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000912 ThreadSafetyHandler &Handler;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000913 const CXXMethodDecl *CurrentMethod;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000914 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000915 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000916 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000917
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000918 BeforeSet* GlobalBeforeSet;
919
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000920public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000921 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
922 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000923
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000924 bool inCurrentScope(const CapabilityExpr &CapE);
925
Ed Schoutenca988742014-09-03 06:00:11 +0000926 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
927 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +0000928 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000929 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
930 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000931
932 template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000933 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +0000934 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000935
936 template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000937 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000938 const NamedDecl *D,
939 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
940 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000941
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000942 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
943 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000944
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000945 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
946 const CFGBlock* PredBlock,
947 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +0000948
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000949 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
950 SourceLocation JoinLoc,
951 LockErrorKind LEK1, LockErrorKind LEK2,
952 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000953
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000954 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
955 SourceLocation JoinLoc, LockErrorKind LEK1,
956 bool Modify=true) {
957 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000958 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000959
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000960 void runAnalysis(AnalysisDeclContext &AC);
961};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000962} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000963
964/// Process acquired_before and acquired_after attributes on Vd.
965BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
966 ThreadSafetyAnalyzer& Analyzer) {
967 // Create a new entry for Vd.
Reid Kleckner19ff5602015-11-20 19:08:30 +0000968 BeforeInfo *Info = nullptr;
969 {
970 // Keep InfoPtr in its own scope in case BMap is modified later and the
971 // reference becomes invalid.
972 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
973 if (!InfoPtr)
974 InfoPtr.reset(new BeforeInfo());
975 Info = InfoPtr.get();
976 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000977
978 for (Attr* At : Vd->attrs()) {
979 switch (At->getKind()) {
980 case attr::AcquiredBefore: {
981 auto *A = cast<AcquiredBeforeAttr>(At);
982
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000983 // Read exprs from the attribute, and add them to BeforeVect.
984 for (const auto *Arg : A->args()) {
985 CapabilityExpr Cp =
986 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
987 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000988 Info->Vect.push_back(Cpvd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000989 auto It = BMap.find(Cpvd);
990 if (It == BMap.end())
991 insertAttrExprs(Cpvd, Analyzer);
992 }
993 }
994 break;
995 }
996 case attr::AcquiredAfter: {
997 auto *A = cast<AcquiredAfterAttr>(At);
998
999 // Read exprs from the attribute, and add them to BeforeVect.
1000 for (const auto *Arg : A->args()) {
1001 CapabilityExpr Cp =
1002 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1003 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1004 // Get entry for mutex listed in attribute
Reid Kleckner19ff5602015-11-20 19:08:30 +00001005 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1006 ArgInfo->Vect.push_back(Vd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001007 }
1008 }
1009 break;
1010 }
1011 default:
1012 break;
1013 }
1014 }
1015
1016 return Info;
1017}
1018
Reid Kleckner19ff5602015-11-20 19:08:30 +00001019BeforeSet::BeforeInfo *
1020BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1021 ThreadSafetyAnalyzer &Analyzer) {
1022 auto It = BMap.find(Vd);
1023 BeforeInfo *Info = nullptr;
1024 if (It == BMap.end())
1025 Info = insertAttrExprs(Vd, Analyzer);
1026 else
1027 Info = It->second.get();
1028 assert(Info && "BMap contained nullptr?");
1029 return Info;
1030}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001031
1032/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1033void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1034 const FactSet& FSet,
1035 ThreadSafetyAnalyzer& Analyzer,
1036 SourceLocation Loc, StringRef CapKind) {
1037 SmallVector<BeforeInfo*, 8> InfoVect;
1038
1039 // Do a depth-first traversal of Vd.
1040 // Return true if there are cycles.
1041 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1042 if (!Vd)
1043 return false;
1044
Reid Kleckner19ff5602015-11-20 19:08:30 +00001045 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001046
1047 if (Info->Visited == 1)
1048 return true;
1049
1050 if (Info->Visited == 2)
1051 return false;
1052
Reid Kleckner19ff5602015-11-20 19:08:30 +00001053 if (Info->Vect.empty())
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001054 return false;
1055
1056 InfoVect.push_back(Info);
1057 Info->Visited = 1;
Reid Kleckner19ff5602015-11-20 19:08:30 +00001058 for (auto *Vdb : Info->Vect) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001059 // Exclude mutexes in our immediate before set.
1060 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1061 StringRef L1 = StartVd->getName();
1062 StringRef L2 = Vdb->getName();
1063 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1064 }
1065 // Transitively search other before sets, and warn on cycles.
1066 if (traverse(Vdb)) {
1067 if (CycMap.find(Vd) == CycMap.end()) {
1068 CycMap.insert(std::make_pair(Vd, true));
1069 StringRef L1 = Vd->getName();
1070 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1071 }
1072 }
1073 }
1074 Info->Visited = 2;
1075 return false;
1076 };
1077
1078 traverse(StartVd);
1079
1080 for (auto* Info : InfoVect)
1081 Info->Visited = 0;
1082}
1083
1084
1085
Aaron Ballmane0449042014-04-01 21:43:23 +00001086/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1087static const ValueDecl *getValueDecl(const Expr *Exp) {
1088 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1089 return getValueDecl(CE->getSubExpr());
1090
1091 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1092 return DR->getDecl();
1093
1094 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1095 return ME->getMemberDecl();
1096
1097 return nullptr;
1098}
1099
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001100namespace {
Aaron Ballmane0449042014-04-01 21:43:23 +00001101template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001102class has_arg_iterator_range {
Aaron Ballmane0449042014-04-01 21:43:23 +00001103 typedef char yes[1];
1104 typedef char no[2];
1105
1106 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001107 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001108
1109 template <typename>
1110 static no& test(...);
1111
1112public:
1113 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1114};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001115} // namespace
Aaron Ballmane0449042014-04-01 21:43:23 +00001116
1117static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1118 return A->getName();
1119}
1120
1121static StringRef ClassifyDiagnostic(QualType VDT) {
1122 // We need to look at the declaration of the type of the value to determine
1123 // which it is. The type should either be a record or a typedef, or a pointer
1124 // or reference thereof.
1125 if (const auto *RT = VDT->getAs<RecordType>()) {
1126 if (const auto *RD = RT->getDecl())
1127 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1128 return ClassifyDiagnostic(CA);
1129 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1130 if (const auto *TD = TT->getDecl())
1131 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1132 return ClassifyDiagnostic(CA);
1133 } else if (VDT->isPointerType() || VDT->isReferenceType())
1134 return ClassifyDiagnostic(VDT->getPointeeType());
1135
1136 return "mutex";
1137}
1138
1139static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1140 assert(VD && "No ValueDecl passed");
1141
1142 // The ValueDecl is the declaration of a mutex or role (hopefully).
1143 return ClassifyDiagnostic(VD->getType());
1144}
1145
1146template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001147static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001148 StringRef>::type
1149ClassifyDiagnostic(const AttrTy *A) {
1150 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1151 return ClassifyDiagnostic(VD);
1152 return "mutex";
1153}
1154
1155template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001156static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001157 StringRef>::type
1158ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001159 for (const auto *Arg : A->args()) {
1160 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001161 return ClassifyDiagnostic(VD);
1162 }
1163 return "mutex";
1164}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001165
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001166
1167inline bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1168 if (!CurrentMethod)
1169 return false;
1170 if (auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1171 auto *VD = P->clangDecl();
1172 if (VD)
1173 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1174 }
1175 return false;
1176}
1177
1178
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001179/// \brief Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001180/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001181void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1182 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001183 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001184 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001185 return;
1186
Ed Schoutenca988742014-09-03 06:00:11 +00001187 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001188 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001189 CapabilityExpr NegC = !*Entry;
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001190 FactEntry *Nen = FSet.findLock(FactMan, NegC);
1191 if (Nen) {
1192 FSet.removeLock(FactMan, NegC);
1193 }
1194 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001195 if (inCurrentScope(*Entry) && !Entry->asserted())
1196 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1197 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001198 }
1199 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001200
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001201 // Check before/after constraints
1202 if (Handler.issueBetaWarnings() &&
1203 !Entry->asserted() && !Entry->declared()) {
1204 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1205 Entry->loc(), DiagKind);
1206 }
1207
DeLesley Hutchins42665222014-08-04 16:10:59 +00001208 // FIXME: Don't always warn when we have support for reentrant locks.
Ed Schoutenca988742014-09-03 06:00:11 +00001209 if (FSet.findLock(FactMan, *Entry)) {
1210 if (!Entry->asserted())
1211 Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001212 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001213 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001214 }
1215}
1216
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001217
1218/// \brief Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001219/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001220void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001221 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001222 bool FullyRemove, LockKind ReceivedKind,
1223 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001224 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001225 return;
1226
DeLesley Hutchins42665222014-08-04 16:10:59 +00001227 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001228 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001229 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001230 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001231 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001232
Aaron Ballmandf115d92014-03-21 14:48:48 +00001233 // Generic lock removal doesn't care about lock kind mismatches, but
1234 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001235 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1236 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1237 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001238 }
1239
Ed Schoutenca988742014-09-03 06:00:11 +00001240 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1241 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001242}
1243
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001244
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001245/// \brief Extract the list of mutexIDs from the attribute on an expression,
1246/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001247template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001248void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001249 Expr *Exp, const NamedDecl *D,
1250 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001251 if (Attr->args_size() == 0) {
1252 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001253 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1254 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001255 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1256 return;
1257 }
1258 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001259 if (!Cp.shouldIgnore())
1260 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001261 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001262 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001263
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001264 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001265 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1266 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001267 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001268 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001269 }
1270 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001271 if (!Cp.shouldIgnore())
1272 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001273 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001274}
1275
1276
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001277/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1278/// trylock applies to the given edge, then push them onto Mtxs, discarding
1279/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001280template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001281void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001282 Expr *Exp, const NamedDecl *D,
1283 const CFGBlock *PredBlock,
1284 const CFGBlock *CurrBlock,
1285 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001286 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001287 bool branch = false;
1288 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001289 branch = BLE->getValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001290 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001291 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001292
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001293 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001294 if (Neg)
1295 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001296
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001297 // If we've taken the trylock branch, then add the lock
1298 int i = 0;
1299 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1300 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001301 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001302 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001303 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001304}
1305
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001306static bool getStaticBooleanValue(Expr *E, bool &TCond) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001307 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1308 TCond = false;
1309 return true;
1310 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1311 TCond = BLE->getValue();
1312 return true;
1313 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1314 TCond = ILE->getValue().getBoolValue();
1315 return true;
1316 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1317 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1318 }
1319 return false;
1320}
1321
1322
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001323// If Cond can be traced back to a function call, return the call expression.
1324// The negate variable should be called with false, and will be set to true
1325// if the function call is negated, e.g. if (!mu.tryLock(...))
1326const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1327 LocalVarContext C,
1328 bool &Negate) {
1329 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001330 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001331
1332 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1333 return CallExp;
1334 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001335 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1336 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1337 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001338 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1339 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1340 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001341 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1342 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1343 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001344 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1345 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1346 return getTrylockCallExpr(E, C, Negate);
1347 }
1348 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1349 if (UOP->getOpcode() == UO_LNot) {
1350 Negate = !Negate;
1351 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1352 }
Craig Topper25542942014-05-20 04:30:07 +00001353 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001354 }
1355 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1356 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1357 if (BOP->getOpcode() == BO_NE)
1358 Negate = !Negate;
1359
1360 bool TCond = false;
1361 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1362 if (!TCond) Negate = !Negate;
1363 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1364 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001365 TCond = false;
1366 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001367 if (!TCond) Negate = !Negate;
1368 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1369 }
Craig Topper25542942014-05-20 04:30:07 +00001370 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001371 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001372 if (BOP->getOpcode() == BO_LAnd) {
1373 // LHS must have been evaluated in a different block.
1374 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1375 }
1376 if (BOP->getOpcode() == BO_LOr) {
1377 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1378 }
Craig Topper25542942014-05-20 04:30:07 +00001379 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001380 }
Craig Topper25542942014-05-20 04:30:07 +00001381 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001382}
1383
1384
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001385/// \brief Find the lockset that holds on the edge between PredBlock
1386/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1387/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001388void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1389 const FactSet &ExitSet,
1390 const CFGBlock *PredBlock,
1391 const CFGBlock *CurrBlock) {
1392 Result = ExitSet;
1393
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001394 const Stmt *Cond = PredBlock->getTerminatorCondition();
1395 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001396 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001397
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001398 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001399 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1400 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001401 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001402
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001403 CallExpr *Exp =
1404 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001405 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001406 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001407
1408 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1409 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001410 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001411
DeLesley Hutchins42665222014-08-04 16:10:59 +00001412 CapExprSet ExclusiveLocksToAdd;
1413 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001414
1415 // If the condition is a call to a Trylock function, then grab the attributes
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001416 for (auto *Attr : FunDecl->attrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001417 switch (Attr->getKind()) {
1418 case attr::ExclusiveTrylockFunction: {
1419 ExclusiveTrylockFunctionAttr *A =
1420 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001421 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1422 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001423 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001424 break;
1425 }
1426 case attr::SharedTrylockFunction: {
1427 SharedTrylockFunctionAttr *A =
1428 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001429 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001430 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001431 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001432 break;
1433 }
1434 default:
1435 break;
1436 }
1437 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001438
1439 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001440 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001441 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001442 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1443 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001444 CapDiagKind);
1445 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001446 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1447 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001448 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001449}
1450
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001451namespace {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001452/// \brief We use this class to visit different types of expressions in
1453/// CFGBlocks, and build up the lockset.
1454/// An expression may cause us to add or remove locks from the lockset, or else
1455/// output error messages related to missing locks.
1456/// FIXME: In future, we may be able to not inherit from a visitor.
1457class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001458 friend class ThreadSafetyAnalyzer;
1459
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001460 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001461 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001462 LocalVariableMap::Context LVarCtx;
1463 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001464
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001465 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001466 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001467 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001468 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001469 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1470 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001471
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001472 void checkAccess(const Expr *Exp, AccessKind AK,
1473 ProtectedOperationKind POK = POK_VarAccess);
1474 void checkPtAccess(const Expr *Exp, AccessKind AK,
1475 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001476
Craig Topper25542942014-05-20 04:30:07 +00001477 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001478
Caitlin Sadowski33208342011-09-09 16:11:56 +00001479public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001480 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001481 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001482 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001483 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001484 LVarCtx(Info.EntryContext),
1485 CtxIndex(Info.EntryIndex)
1486 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001487
1488 void VisitUnaryOperator(UnaryOperator *UO);
1489 void VisitBinaryOperator(BinaryOperator *BO);
1490 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001491 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001492 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001493 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001494};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001495} // namespace
DeLesley Hutchins42665222014-08-04 16:10:59 +00001496
Caitlin Sadowski33208342011-09-09 16:11:56 +00001497/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001498/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001499void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001500 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001501 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001502 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001503 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001504
DeLesley Hutchins42665222014-08-04 16:10:59 +00001505 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1506 if (Cp.isInvalid()) {
1507 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001508 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001509 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001510 return;
1511 }
1512
DeLesley Hutchins42665222014-08-04 16:10:59 +00001513 if (Cp.negative()) {
1514 // Negative capabilities act like locks excluded
1515 FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1516 if (LDat) {
1517 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001518 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001519 return;
1520 }
1521
1522 // If this does not refer to a negative capability in the same class,
1523 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001524 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001525 return;
1526
1527 // Otherwise the negative requirement must be propagated to the caller.
1528 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1529 if (!LDat) {
1530 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001531 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001532 }
1533 return;
1534 }
1535
1536 FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001537 bool NoError = true;
1538 if (!LDat) {
1539 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001540 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1541 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001542 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001543 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001544 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001545 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1546 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001547 } else {
1548 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001549 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1550 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001551 }
1552 NoError = false;
1553 }
1554 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001555 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001556 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1557 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001558 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001559}
1560
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001561/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001562void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001563 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001564 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1565 if (Cp.isInvalid()) {
1566 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1567 return;
1568 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001569 return;
1570 }
1571
DeLesley Hutchins42665222014-08-04 16:10:59 +00001572 FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
1573 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001574 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001575 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1576 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001577}
1578
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001579/// \brief Checks guarded_by and pt_guarded_by attributes.
1580/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1581/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1582/// Similarly, we check if the access is to an expression that dereferences
1583/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001584void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1585 ProtectedOperationKind POK) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001586 Exp = Exp->IgnoreParenCasts();
1587
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001588 SourceLocation Loc = Exp->getExprLoc();
1589
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001590 // Local variables of reference type cannot be re-assigned;
1591 // map them to their initializer.
1592 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1593 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1594 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1595 if (const auto *E = VD->getInit()) {
1596 Exp = E;
1597 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001598 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001599 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001600 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001601 }
1602
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001603 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1604 // For dereferences
1605 if (UO->getOpcode() == clang::UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001606 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001607 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001608 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001609
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001610 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001611 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001612 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001613 }
1614
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001615 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1616 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001617 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001618 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001619 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001620 }
1621
Caitlin Sadowski33208342011-09-09 16:11:56 +00001622 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001623 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001624 return;
1625
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001626 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001627 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001628 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001629
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001630 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001631 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001632 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001633}
1634
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001635
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001636/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001637/// POK is the same operationKind that was passed to checkAccess.
1638void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1639 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001640 while (true) {
1641 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1642 Exp = PE->getSubExpr();
1643 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001644 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001645 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1646 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1647 // If it's an actual array, and not a pointer, then it's elements
1648 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001649 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001650 return;
1651 }
1652 Exp = CE->getSubExpr();
1653 continue;
1654 }
1655 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001656 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001657
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001658 // Pass by reference warnings are under a different flag.
1659 ProtectedOperationKind PtPOK = POK_VarDereference;
1660 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1661
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001662 const ValueDecl *D = getValueDecl(Exp);
1663 if (!D || !D->hasAttrs())
1664 return;
1665
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001666 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001667 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001668 Exp->getExprLoc());
1669
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001670 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001671 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001672 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001673}
1674
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001675/// \brief Process a function call, method call, constructor call,
1676/// or destructor call. This involves looking at the attributes on the
1677/// corresponding function/method/constructor/destructor, issuing warnings,
1678/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001679///
1680/// FIXME: For classes annotated with one of the guarded annotations, we need
1681/// to treat const method calls as reads and non-const method calls as writes,
1682/// and check that the appropriate locks are held. Non-const method calls with
1683/// the same signature as const method calls can be also treated as reads.
1684///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001685void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001686 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001687 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1688 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001689 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
Aaron Ballmane0449042014-04-01 21:43:23 +00001690 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001691
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001692 // Figure out if we're calling the constructor of scoped lockable class
1693 bool isScopedVar = false;
1694 if (VD) {
1695 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1696 const CXXRecordDecl* PD = CD->getParent();
1697 if (PD && PD->hasAttr<ScopedLockableAttr>())
1698 isScopedVar = true;
1699 }
1700 }
1701
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001702 for(Attr *Atconst : D->attrs()) {
1703 Attr* At = const_cast<Attr*>(Atconst);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001704 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001705 // When we encounter a lock function, we need to add the lock to our
1706 // lockset.
1707 case attr::AcquireCapability: {
1708 auto *A = cast<AcquireCapabilityAttr>(At);
1709 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1710 : ExclusiveLocksToAdd,
1711 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001712
1713 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001714 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001715 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001716
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001717 // An assert will add a lock to the lockset, but will not generate
1718 // a warning if it is already there, and will not generate a warning
1719 // if it is not removed.
1720 case attr::AssertExclusiveLock: {
1721 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1722
DeLesley Hutchins42665222014-08-04 16:10:59 +00001723 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001724 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001725 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001726 Analyzer->addLock(FSet,
1727 llvm::make_unique<LockableFactEntry>(
1728 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001729 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001730 break;
1731 }
1732 case attr::AssertSharedLock: {
1733 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1734
DeLesley Hutchins42665222014-08-04 16:10:59 +00001735 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001736 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001737 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001738 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1739 AssertLock, LK_Shared, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001740 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001741 break;
1742 }
1743
Caitlin Sadowski33208342011-09-09 16:11:56 +00001744 // When we encounter an unlock function, we need to remove unlocked
1745 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001746 case attr::ReleaseCapability: {
1747 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001748 if (A->isGeneric())
1749 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1750 else if (A->isShared())
1751 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1752 else
1753 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001754
1755 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001756 break;
1757 }
1758
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001759 case attr::RequiresCapability: {
1760 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001761 for (auto *Arg : A->args()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001762 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001763 POK_FunctionCall, ClassifyDiagnostic(A),
1764 Exp->getExprLoc());
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001765 // use for adopting a lock
1766 if (isScopedVar) {
1767 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1768 : ScopedExclusiveReqs,
1769 A, Exp, D, VD);
1770 }
1771 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001772 break;
1773 }
1774
1775 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001776 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001777 for (auto *Arg : A->args())
1778 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001779 break;
1780 }
1781
Alp Tokerd4733632013-12-05 04:47:09 +00001782 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001783 default:
1784 break;
1785 }
1786 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001787
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001788 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00001789 for (const auto &M : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001790 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1791 M, LK_Exclusive, Loc, isScopedVar),
Aaron Ballmane0449042014-04-01 21:43:23 +00001792 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001793 for (const auto &M : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001794 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1795 M, LK_Shared, Loc, isScopedVar),
Aaron Ballmane0449042014-04-01 21:43:23 +00001796 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001797
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001798 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001799 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001800 SourceLocation MLoc = VD->getLocation();
1801 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001802 // FIXME: does this store a pointer to DRE?
1803 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001804
1805 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1806 std::back_inserter(ExclusiveLocksToAdd));
1807 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1808 std::back_inserter(SharedLocksToAdd));
Ed Schoutenca988742014-09-03 06:00:11 +00001809 Analyzer->addLock(FSet,
1810 llvm::make_unique<ScopedLockableFactEntry>(
1811 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1812 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001813 }
1814
1815 // Remove locks.
1816 // FIXME -- should only fully remove if the attribute refers to 'this'.
1817 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001818 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001819 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001820 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001821 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001822 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001823 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001824}
1825
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001826
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001827/// \brief For unary operations which read and write a variable, we need to
1828/// check whether we hold any required mutexes. Reads are checked in
1829/// VisitCastExpr.
1830void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1831 switch (UO->getOpcode()) {
1832 case clang::UO_PostDec:
1833 case clang::UO_PostInc:
1834 case clang::UO_PreDec:
1835 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001836 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001837 break;
1838 }
1839 default:
1840 break;
1841 }
1842}
1843
1844/// For binary operations which assign to a variable (writes), we need to check
1845/// whether we hold any required mutexes.
1846/// FIXME: Deal with non-primitive types.
1847void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1848 if (!BO->isAssignmentOp())
1849 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001850
1851 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001852 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001853
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001854 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001855}
1856
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001857
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001858/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1859/// need to ensure we hold any required mutexes.
1860/// FIXME: Deal with non-primitive types.
1861void BuildLockset::VisitCastExpr(CastExpr *CE) {
1862 if (CE->getCastKind() != CK_LValueToRValue)
1863 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001864 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001865}
1866
1867
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001868void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001869 bool ExamineArgs = true;
1870 bool OperatorFun = false;
1871
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001872 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1873 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
1874 // ME can be null when calling a method pointer
1875 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001876
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001877 if (ME && MD) {
1878 if (ME->isArrow()) {
1879 if (MD->isConst()) {
1880 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1881 } else { // FIXME -- should be AK_Written
1882 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001883 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001884 } else {
1885 if (MD->isConst())
1886 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1887 else // FIXME -- should be AK_Written
1888 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001889 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001890 }
1891 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001892 OperatorFun = true;
1893
1894 auto OEop = OE->getOperator();
1895 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001896 case OO_Equal: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001897 ExamineArgs = false;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001898 const Expr *Target = OE->getArg(0);
1899 const Expr *Source = OE->getArg(1);
1900 checkAccess(Target, AK_Written);
1901 checkAccess(Source, AK_Read);
1902 break;
1903 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001904 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001905 case OO_Arrow:
1906 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001907 const Expr *Obj = OE->getArg(0);
1908 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001909 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1910 // Grrr. operator* can be multiplication...
1911 checkPtAccess(Obj, AK_Read);
1912 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001913 break;
1914 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001915 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001916 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001917 const Expr *Obj = OE->getArg(0);
1918 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001919 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001920 }
1921 }
1922 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001923
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001924 if (ExamineArgs) {
1925 if (FunctionDecl *FD = Exp->getDirectCallee()) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001926
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001927 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
1928 // only turns off checking within the body of a function, but we also
1929 // use it to turn off checking in arguments to the function. This
1930 // could result in some false negatives, but the alternative is to
1931 // create yet another attribute.
1932 //
1933 if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
1934 unsigned Fn = FD->getNumParams();
1935 unsigned Cn = Exp->getNumArgs();
1936 unsigned Skip = 0;
1937
1938 unsigned i = 0;
1939 if (OperatorFun) {
1940 if (isa<CXXMethodDecl>(FD)) {
1941 // First arg in operator call is implicit self argument,
1942 // and doesn't appear in the FunctionDecl.
1943 Skip = 1;
1944 Cn--;
1945 } else {
1946 // Ignore the first argument of operators; it's been checked above.
1947 i = 1;
1948 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001949 }
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001950 // Ignore default arguments
1951 unsigned n = (Fn < Cn) ? Fn : Cn;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001952
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001953 for (; i < n; ++i) {
1954 ParmVarDecl* Pvd = FD->getParamDecl(i);
1955 Expr* Arg = Exp->getArg(i+Skip);
1956 QualType Qt = Pvd->getType();
1957 if (Qt->isReferenceType())
1958 checkAccess(Arg, AK_Read, POK_PassByRef);
1959 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001960 }
1961 }
1962 }
1963
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001964 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1965 if(!D || !D->hasAttrs())
1966 return;
1967 handleCall(Exp, D);
1968}
1969
1970void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001971 const CXXConstructorDecl *D = Exp->getConstructor();
1972 if (D && D->isCopyConstructor()) {
1973 const Expr* Source = Exp->getArg(0);
1974 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001975 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001976 // FIXME -- only handles constructors in DeclStmt below.
1977}
1978
1979void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001980 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001981 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001982
Aaron Ballman9ee54d12014-05-14 20:42:13 +00001983 for (auto *D : S->getDeclGroup()) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001984 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1985 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00001986 // handle constructors that involve temporaries
1987 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1988 E = EWC->getSubExpr();
1989
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001990 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1991 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1992 if (!CtorD || !CtorD->hasAttrs())
1993 return;
1994 handleCall(CE, CtorD, VD);
1995 }
1996 }
1997 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001998}
1999
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002000
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002001
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002002/// \brief Compute the intersection of two locksets and issue warnings for any
2003/// locks in the symmetric difference.
2004///
2005/// This function is used at a merge point in the CFG when comparing the lockset
2006/// of each branch being merged. For example, given the following sequence:
2007/// A; if () then B; else C; D; we need to check that the lockset after B and C
2008/// are the same. In the event of a difference, we use the intersection of these
2009/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002010///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002011/// \param FSet1 The first lockset.
2012/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002013/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002014/// \param LEK1 The error message to report if a mutex is missing from LSet1
2015/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002016void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2017 const FactSet &FSet2,
2018 SourceLocation JoinLoc,
2019 LockErrorKind LEK1,
2020 LockErrorKind LEK2,
2021 bool Modify) {
2022 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002023
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002024 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002025 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002026 const FactEntry *LDat1 = nullptr;
2027 const FactEntry *LDat2 = &FactMan[Fact];
2028 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2029 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002030
DeLesley Hutchins42665222014-08-04 16:10:59 +00002031 if (LDat1) {
2032 if (LDat1->kind() != LDat2->kind()) {
2033 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2034 LDat2->loc(), LDat1->loc());
2035 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002036 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002037 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002038 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002039 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00002040 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002041 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002042 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002043 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002044 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00002045 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2046 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002047 }
2048 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002049
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002050 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002051 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002052 const FactEntry *LDat1 = &FactMan[Fact];
2053 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002054
DeLesley Hutchins42665222014-08-04 16:10:59 +00002055 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00002056 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2057 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002058 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00002059 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002060 }
2061 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002062}
2063
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002064
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002065// Return true if block B never continues to its successors.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002066static bool neverReturns(const CFGBlock *B) {
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002067 if (B->hasNoReturnElement())
2068 return true;
2069 if (B->empty())
2070 return false;
2071
2072 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002073 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2074 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002075 return true;
2076 }
2077 return false;
2078}
2079
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002080
Caitlin Sadowski33208342011-09-09 16:11:56 +00002081/// \brief Check a function's CFG for thread-safety violations.
2082///
2083/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2084/// at the end of each block, and issue warnings for thread safety violations.
2085/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002086void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002087 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2088 // For now, we just use the walker to set things up.
2089 threadSafety::CFGWalker walker;
2090 if (!walker.init(AC))
2091 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002092
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002093 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002094 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002095
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002096 CFG *CFGraph = walker.getGraph();
2097 const NamedDecl *D = walker.getDecl();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002098 const FunctionDecl *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00002099 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002100
Aaron Ballman9ead1242013-12-19 02:39:40 +00002101 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002102 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002103
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002104 // FIXME: Do something a bit more intelligent inside constructor and
2105 // destructor code. Constructors and destructors must assume unique access
2106 // to 'this', so checks on member variable access is disabled, but we should
2107 // still enable checks on other objects.
2108 if (isa<CXXConstructorDecl>(D))
2109 return; // Don't check inside constructors.
2110 if (isa<CXXDestructorDecl>(D))
2111 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002112
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002113 Handler.enterFunction(CurrentFunction);
2114
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002115 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002116 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002117
2118 // We need to explore the CFG via a "topological" ordering.
2119 // That way, we will be guaranteed to have information about required
2120 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002121 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002122 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002123
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002124 // Mark entry block as reachable
2125 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2126
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002127 // Compute SSA names for local variables
2128 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2129
Richard Smith92286672012-02-03 04:45:26 +00002130 // Fill in source locations for all CFGBlocks.
2131 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2132
DeLesley Hutchins42665222014-08-04 16:10:59 +00002133 CapExprSet ExclusiveLocksAcquired;
2134 CapExprSet SharedLocksAcquired;
2135 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002136
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002137 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002138 // to initial lockset. Also turn off checking for lock and unlock functions.
2139 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002140 if (!SortedGraph->empty() && D->hasAttrs()) {
2141 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002142 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002143
DeLesley Hutchins42665222014-08-04 16:10:59 +00002144 CapExprSet ExclusiveLocksToAdd;
2145 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002146 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002147
2148 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002149 for (const auto *Attr : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002150 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002151 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002152 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00002153 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002154 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002155 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002156 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2157 // We must ignore such methods.
2158 if (A->args_size() == 0)
2159 return;
2160 // FIXME -- deal with exclusive vs. shared unlock functions?
Aaron Ballman0491afa2014-04-18 13:13:15 +00002161 getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
2162 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002163 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002164 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002165 if (A->args_size() == 0)
2166 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002167 getMutexIDs(A->isShared() ? SharedLocksAcquired
2168 : ExclusiveLocksAcquired,
2169 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002170 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002171 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2172 // Don't try to check trylock functions for now
2173 return;
2174 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2175 // Don't try to check trylock functions for now
2176 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002177 }
2178 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002179
2180 // FIXME -- Loc can be wrong here.
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002181 for (const auto &Mu : ExclusiveLocksToAdd) {
2182 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2183 Entry->setDeclared(true);
2184 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2185 }
2186 for (const auto &Mu : SharedLocksToAdd) {
2187 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2188 Entry->setDeclared(true);
2189 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2190 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002191 }
2192
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002193 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002194 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002195 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002196
2197 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002198 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002199
2200 // Iterate through the predecessor blocks and warn if the lockset for all
2201 // predecessors is not the same. We take the entry lockset of the current
2202 // block to be the intersection of all previous locksets.
2203 // FIXME: By keeping the intersection, we may output more errors in future
2204 // for a lock which is not in the intersection, but was in the union. We
2205 // may want to also keep the union in future. As an example, let's say
2206 // the intersection contains Mutex L, and the union contains L and M.
2207 // Later we unlock M. At this point, we would output an error because we
2208 // never locked M; although the real error is probably that we forgot to
2209 // lock M on all code paths. Conversely, let's say that later we lock M.
2210 // In this case, we should compare against the intersection instead of the
2211 // union because the real error is probably that we forgot to unlock M on
2212 // all code paths.
2213 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002214 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002215 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2216 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2217
2218 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002219 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002220 continue;
2221
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002222 int PrevBlockID = (*PI)->getBlockID();
2223 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2224
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002225 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002226 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002227 continue;
2228
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002229 // Okay, we can reach this block from the entry.
2230 CurrBlockInfo->Reachable = true;
2231
Richard Smith815b29d2012-02-03 03:30:07 +00002232 // If the previous block ended in a 'continue' or 'break' statement, then
2233 // a difference in locksets is probably due to a bug in that block, rather
2234 // than in some other predecessor. In that case, keep the other
2235 // predecessor's lockset.
2236 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2237 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2238 SpecialBlocks.push_back(*PI);
2239 continue;
2240 }
2241 }
2242
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002243 FactSet PrevLockset;
2244 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002245
Caitlin Sadowski33208342011-09-09 16:11:56 +00002246 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002247 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002248 LocksetInitialized = true;
2249 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002250 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2251 CurrBlockInfo->EntryLoc,
2252 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002253 }
2254 }
2255
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002256 // Skip rest of block if it's not reachable.
2257 if (!CurrBlockInfo->Reachable)
2258 continue;
2259
Richard Smith815b29d2012-02-03 03:30:07 +00002260 // Process continue and break blocks. Assume that the lockset for the
2261 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002262 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00002263 int PrevBlockID = PrevBlock->getBlockID();
2264 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2265
2266 if (!LocksetInitialized) {
2267 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2268 LocksetInitialized = true;
2269 } else {
2270 // Determine whether this edge is a loop terminator for diagnostic
2271 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2272 // it might also be part of a switch. Also, a subsequent destructor
2273 // might add to the lockset, in which case the real issue might be a
2274 // double lock on the other path.
2275 const Stmt *Terminator = PrevBlock->getTerminator();
2276 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2277
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002278 FactSet PrevLockset;
2279 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2280 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002281
Richard Smith815b29d2012-02-03 03:30:07 +00002282 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002283 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2284 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002285 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002286 : LEK_LockedSomePredecessors,
2287 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002288 }
2289 }
2290
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002291 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2292
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002293 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002294 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2295 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002296 switch (BI->getKind()) {
2297 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002298 CFGStmt CS = BI->castAs<CFGStmt>();
2299 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002300 break;
2301 }
2302 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2303 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002304 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2305 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2306 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002307 if (!DD->hasAttrs())
2308 break;
2309
2310 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002311 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
Richard Trieua1877592015-03-16 21:49:43 +00002312 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
2313 VK_LValue, AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002314 LocksetBuilder.handleCall(&DRE, DD);
2315 break;
2316 }
2317 default:
2318 break;
2319 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002320 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002321 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002322
2323 // For every back edge from CurrBlock (the end of the loop) to another block
2324 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2325 // the one held at the beginning of FirstLoopBlock. We can look up the
2326 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2327 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2328 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2329
2330 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002331 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002332 continue;
2333
2334 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002335 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2336 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2337 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2338 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002339 LEK_LockedSomeLoopIterations,
2340 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002341 }
2342 }
2343
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002344 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2345 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002346
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002347 // Skip the final check if the exit block is unreachable.
2348 if (!Final->Reachable)
2349 return;
2350
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002351 // By default, we expect all locks held on entry to be held on exit.
2352 FactSet ExpectedExitSet = Initial->EntrySet;
2353
2354 // Adjust the expected exit set by adding or removing locks, as declared
2355 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2356 // issue the appropriate warning.
2357 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002358 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002359 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2360 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002361 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002362 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2363 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002364 for (const auto &Lock : LocksReleased)
2365 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002366
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002367 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002368 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002369 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002370 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002371 LEK_NotLockedAtEndOfFunction,
2372 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002373
2374 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002375}
2376
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002377
2378/// \brief Check a function's CFG for thread-safety violations.
2379///
2380/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2381/// at the end of each block, and issue warnings for thread safety violations.
2382/// Each block in the CFG is traversed exactly once.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002383void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2384 ThreadSafetyHandler &Handler,
2385 BeforeSet **BSet) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002386 if (!*BSet)
2387 *BSet = new BeforeSet;
2388 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002389 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002390}
2391
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002392void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002393
Caitlin Sadowski33208342011-09-09 16:11:56 +00002394/// \brief Helper function that returns a LockKind required for the given level
2395/// of access.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002396LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002397 switch (AK) {
2398 case AK_Read :
2399 return LK_Shared;
2400 case AK_Written :
2401 return LK_Exclusive;
2402 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002403 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002404}