blob: b282a5bbd8d8ccf57b6f3c083180eba76892f6f5 [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
Benjamin Kramerea70eb32012-12-01 15:09:41 +000018#include "clang/AST/Attr.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000019#include "clang/AST/DeclCXX.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Analysis/Analyses/PostOrderCFGView.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000024#include "clang/Analysis/Analyses/ThreadSafety.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/BitVector.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/ImmutableMap.h"
38#include "llvm/ADT/PostOrderIterator.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringRef.h"
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000041#include "llvm/Support/raw_ostream.h"
Caitlin Sadowski33208342011-09-09 16:11:56 +000042#include <algorithm>
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000043#include <ostream>
44#include <sstream>
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +000045#include <utility>
Caitlin Sadowski33208342011-09-09 16:11:56 +000046#include <vector>
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000047using namespace clang;
48using namespace threadSafety;
Caitlin Sadowski33208342011-09-09 16:11:56 +000049
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000050// Key method definition
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000051ThreadSafetyHandler::~ThreadSafetyHandler() {}
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000052
Benjamin Kramer66a97ee2015-03-09 14:19:54 +000053namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000054class TILPrinter :
55 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000056
57
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000058/// Issue a warning about an invalid lock expression
59static void warnInvalidLock(ThreadSafetyHandler &Handler,
60 const Expr *MutexExp, const NamedDecl *D,
61 const Expr *DeclExp, StringRef Kind) {
62 SourceLocation Loc;
63 if (DeclExp)
64 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000065
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000066 // FIXME: add a note about the attribute location in MutexExp or D
67 if (Loc.isValid())
68 Handler.handleInvalidLockExp(Kind, Loc);
69}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000070
DeLesley Hutchins42665222014-08-04 16:10:59 +000071/// \brief A set of CapabilityInfo objects, which are compiled from the
72/// requires attributes on a function.
73class CapExprSet : public SmallVector<CapabilityExpr, 4> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000074public:
Aaron Ballmancea26092014-03-06 19:10:16 +000075 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchins42665222014-08-04 16:10:59 +000076 void push_back_nodup(const CapabilityExpr &CapE) {
77 iterator It = std::find_if(begin(), end(),
78 [=](const CapabilityExpr &CapE2) {
79 return CapE.equals(CapE2);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000080 });
81 if (It == end())
DeLesley Hutchins42665222014-08-04 16:10:59 +000082 push_back(CapE);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +000083 }
84};
85
Ed Schoutenca988742014-09-03 06:00:11 +000086class FactManager;
87class FactSet;
DeLesley Hutchins42665222014-08-04 16:10:59 +000088
89/// \brief This is a helper class that stores a fact that is known at a
90/// particular point in program execution. Currently, a fact is a capability,
91/// along with additional information, such as where it was acquired, whether
92/// it is exclusive or shared, etc.
Caitlin Sadowski33208342011-09-09 16:11:56 +000093///
DeLesley Hutchins42665222014-08-04 16:10:59 +000094/// FIXME: this analysis does not currently support either re-entrant
95/// locking or lock "upgrading" and "downgrading" between exclusive and
96/// shared.
97class FactEntry : public CapabilityExpr {
98private:
NAKAMURA Takumie9882cf2014-08-04 22:48:36 +000099 LockKind LKind; ///< exclusive or shared
100 SourceLocation AcquireLoc; ///< where it was acquired.
NAKAMURA Takumie9882cf2014-08-04 22:48:36 +0000101 bool Asserted; ///< true if the lock was asserted
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000102 bool Declared; ///< true if the lock was declared
Caitlin Sadowski33208342011-09-09 16:11:56 +0000103
DeLesley Hutchins42665222014-08-04 16:10:59 +0000104public:
105 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000106 bool Asrt, bool Declrd = false)
107 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
108 Declared(Declrd) {}
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000109
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000110 virtual ~FactEntry() {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000111
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000112 LockKind kind() const { return LKind; }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000113 SourceLocation loc() const { return AcquireLoc; }
114 bool asserted() const { return Asserted; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000115 bool declared() const { return Declared; }
116
117 void setDeclared(bool D) { Declared = D; }
Ed Schoutenca988742014-09-03 06:00:11 +0000118
119 virtual void
120 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
121 SourceLocation JoinLoc, LockErrorKind LEK,
122 ThreadSafetyHandler &Handler) const = 0;
123 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
124 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
125 bool FullyRemove, ThreadSafetyHandler &Handler,
126 StringRef DiagKind) const = 0;
Caitlin Sadowski33208342011-09-09 16:11:56 +0000127
DeLesley Hutchins42665222014-08-04 16:10:59 +0000128 // Return true if LKind >= LK, where exclusive > shared
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000129 bool isAtLeast(LockKind LK) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000130 return (LKind == LK_Exclusive) || (LK == LK_Shared);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000131 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000132};
133
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000134
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000135typedef unsigned short FactID;
136
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000137/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000138/// the analysis of a single routine.
139class FactManager {
140private:
Ed Schoutenca988742014-09-03 06:00:11 +0000141 std::vector<std::unique_ptr<FactEntry>> Facts;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000142
143public:
Ed Schoutenca988742014-09-03 06:00:11 +0000144 FactID newFact(std::unique_ptr<FactEntry> Entry) {
145 Facts.push_back(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000146 return static_cast<unsigned short>(Facts.size() - 1);
147 }
148
Ed Schoutenca988742014-09-03 06:00:11 +0000149 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
150 FactEntry &operator[](FactID F) { return *Facts[F]; }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000151};
152
153
154/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000155/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000156/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000157/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000158/// locks, so we can get away with doing a linear search for lookup. Note
159/// that a hashtable or map is inappropriate in this case, because lookups
160/// may involve partial pattern matches, rather than exact matches.
161class FactSet {
162private:
163 typedef SmallVector<FactID, 4> FactVec;
164
165 FactVec FactIDs;
166
167public:
168 typedef FactVec::iterator iterator;
169 typedef FactVec::const_iterator const_iterator;
170
171 iterator begin() { return FactIDs.begin(); }
172 const_iterator begin() const { return FactIDs.begin(); }
173
174 iterator end() { return FactIDs.end(); }
175 const_iterator end() const { return FactIDs.end(); }
176
177 bool isEmpty() const { return FactIDs.size() == 0; }
178
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000179 // Return true if the set contains only negative facts
180 bool isEmpty(FactManager &FactMan) const {
181 for (FactID FID : *this) {
182 if (!FactMan[FID].negative())
183 return false;
184 }
185 return true;
186 }
187
188 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
189
Ed Schoutenca988742014-09-03 06:00:11 +0000190 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
191 FactID F = FM.newFact(std::move(Entry));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000192 FactIDs.push_back(F);
193 return F;
194 }
195
DeLesley Hutchins42665222014-08-04 16:10:59 +0000196 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000197 unsigned n = FactIDs.size();
198 if (n == 0)
199 return false;
200
201 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000202 if (FM[FactIDs[i]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000203 FactIDs[i] = FactIDs[n-1];
204 FactIDs.pop_back();
205 return true;
206 }
207 }
DeLesley Hutchins42665222014-08-04 16:10:59 +0000208 if (FM[FactIDs[n-1]].matches(CapE)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000209 FactIDs.pop_back();
210 return true;
211 }
212 return false;
213 }
214
DeLesley Hutchins42665222014-08-04 16:10:59 +0000215 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000216 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000217 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000218 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000219 }
220
DeLesley Hutchins42665222014-08-04 16:10:59 +0000221 FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000222 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000223 return FM[ID].matches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000224 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000225 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000226 }
227
DeLesley Hutchins42665222014-08-04 16:10:59 +0000228 FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000229 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000230 return FM[ID].matchesUniv(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000231 });
DeLesley Hutchins42665222014-08-04 16:10:59 +0000232 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000233 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000234
DeLesley Hutchins42665222014-08-04 16:10:59 +0000235 FactEntry *findPartialMatch(FactManager &FM,
236 const CapabilityExpr &CapE) const {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000237 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchins42665222014-08-04 16:10:59 +0000238 return FM[ID].partiallyMatches(CapE);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000239 });
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000240 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000241 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000242
243 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
244 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
245 return FM[ID].valueDecl() == Vd;
246 });
247 return I != end();
248 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000249};
250
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000251class ThreadSafetyAnalyzer;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000252} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000253
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000254namespace clang {
255namespace threadSafety {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000256class BeforeSet {
257private:
258 typedef SmallVector<const ValueDecl*, 4> BeforeVect;
259
260 struct BeforeInfo {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000261 BeforeInfo() : Visited(0) {}
262 BeforeInfo(BeforeInfo &&O) : Vect(std::move(O.Vect)), Visited(O.Visited) {}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000263
Reid Kleckner19ff5602015-11-20 19:08:30 +0000264 BeforeVect Vect;
265 int Visited;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000266 };
267
Reid Kleckner19ff5602015-11-20 19:08:30 +0000268 typedef llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>
269 BeforeMap;
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000270 typedef llvm::DenseMap<const ValueDecl*, bool> CycleMap;
271
272public:
273 BeforeSet() { }
274
275 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
276 ThreadSafetyAnalyzer& Analyzer);
277
Reid Kleckner19ff5602015-11-20 19:08:30 +0000278 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
279 ThreadSafetyAnalyzer &Analyzer);
280
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000281 void checkBeforeAfter(const ValueDecl* Vd,
282 const FactSet& FSet,
283 ThreadSafetyAnalyzer& Analyzer,
284 SourceLocation Loc, StringRef CapKind);
285
286private:
287 BeforeMap BMap;
288 CycleMap CycMap;
289};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000290} // end namespace threadSafety
291} // end namespace clang
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000292
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000293namespace {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000294typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000295class LocalVariableMap;
296
Richard Smith92286672012-02-03 04:45:26 +0000297/// A side (entry or exit) of a CFG node.
298enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000299
300/// CFGBlockInfo is a struct which contains all the information that is
301/// maintained for each block in the CFG. See LocalVariableMap for more
302/// information about the contexts.
303struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000304 FactSet EntrySet; // Lockset held at entry to block
305 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000306 LocalVarContext EntryContext; // Context held at entry to block
307 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000308 SourceLocation EntryLoc; // Location of first statement in block
309 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000310 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000311 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000312
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000313 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000314 return Side == CBS_Entry ? EntrySet : ExitSet;
315 }
316 SourceLocation getLocation(CFGBlockSide Side) const {
317 return Side == CBS_Entry ? EntryLoc : ExitLoc;
318 }
319
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000320private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000321 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000322 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000323 { }
324
325public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000326 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000327};
328
329
330
331// A LocalVariableMap maintains a map from local variables to their currently
332// valid definitions. It provides SSA-like functionality when traversing the
333// CFG. Like SSA, each definition or assignment to a variable is assigned a
334// unique name (an integer), which acts as the SSA name for that definition.
335// The total set of names is shared among all CFG basic blocks.
336// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
337// with their SSA-names. Instead, we compute a Context for each point in the
338// code, which maps local variables to the appropriate SSA-name. This map
339// changes with each assignment.
340//
341// The map is computed in a single pass over the CFG. Subsequent analyses can
342// then query the map to find the appropriate Context for a statement, and use
343// that Context to look up the definitions of variables.
344class LocalVariableMap {
345public:
346 typedef LocalVarContext Context;
347
348 /// A VarDefinition consists of an expression, representing the value of the
349 /// variable, along with the context in which that expression should be
350 /// interpreted. A reference VarDefinition does not itself contain this
351 /// information, but instead contains a pointer to a previous VarDefinition.
352 struct VarDefinition {
353 public:
354 friend class LocalVariableMap;
355
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000356 const NamedDecl *Dec; // The original declaration for this variable.
357 const Expr *Exp; // The expression for this variable, OR
358 unsigned Ref; // Reference to another VarDefinition
359 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000360
361 bool isReference() { return !Exp; }
362
363 private:
364 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000365 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000366 : Dec(D), Exp(E), Ref(0), Ctx(C)
367 { }
368
369 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000370 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Craig Topper25542942014-05-20 04:30:07 +0000371 : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000372 { }
373 };
374
375private:
376 Context::Factory ContextFactory;
377 std::vector<VarDefinition> VarDefinitions;
378 std::vector<unsigned> CtxIndices;
379 std::vector<std::pair<Stmt*, Context> > SavedContexts;
380
381public:
382 LocalVariableMap() {
383 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000384 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000385 }
386
387 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000388 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000389 const unsigned *i = Ctx.lookup(D);
390 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000391 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000392 assert(*i < VarDefinitions.size());
393 return &VarDefinitions[*i];
394 }
395
396 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000397 /// NULL if the expression is not statically known. If successful, also
398 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000399 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000400 const unsigned *P = Ctx.lookup(D);
401 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000402 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000403
404 unsigned i = *P;
405 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000406 if (VarDefinitions[i].Exp) {
407 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000408 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000409 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000410 i = VarDefinitions[i].Ref;
411 }
Craig Topper25542942014-05-20 04:30:07 +0000412 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000413 }
414
415 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
416
417 /// Return the next context after processing S. This function is used by
418 /// clients of the class to get the appropriate context when traversing the
419 /// CFG. It must be called for every assignment or DeclStmt.
420 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
421 if (SavedContexts[CtxIndex+1].first == S) {
422 CtxIndex++;
423 Context Result = SavedContexts[CtxIndex].second;
424 return Result;
425 }
426 return C;
427 }
428
429 void dumpVarDefinitionName(unsigned i) {
430 if (i == 0) {
431 llvm::errs() << "Undefined";
432 return;
433 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000434 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000435 if (!Dec) {
436 llvm::errs() << "<<NULL>>";
437 return;
438 }
439 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000440 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000441 }
442
443 /// Dumps an ASCII representation of the variable map to llvm::errs()
444 void dump() {
445 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000446 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000447 unsigned Ref = VarDefinitions[i].Ref;
448
449 dumpVarDefinitionName(i);
450 llvm::errs() << " = ";
451 if (Exp) Exp->dump();
452 else {
453 dumpVarDefinitionName(Ref);
454 llvm::errs() << "\n";
455 }
456 }
457 }
458
459 /// Dumps an ASCII representation of a Context to llvm::errs()
460 void dumpContext(Context C) {
461 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000462 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000463 D->printName(llvm::errs());
464 const unsigned *i = C.lookup(D);
465 llvm::errs() << " -> ";
466 dumpVarDefinitionName(*i);
467 llvm::errs() << "\n";
468 }
469 }
470
471 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000472 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
473 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000474
475protected:
476 // Get the current context index
477 unsigned getContextIndex() { return SavedContexts.size()-1; }
478
479 // Save the current context for later replay
480 void saveContext(Stmt *S, Context C) {
481 SavedContexts.push_back(std::make_pair(S,C));
482 }
483
484 // Adds a new definition to the given context, and returns a new context.
485 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000486 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000487 assert(!Ctx.contains(D));
488 unsigned newID = VarDefinitions.size();
489 Context NewCtx = ContextFactory.add(Ctx, D, newID);
490 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
491 return NewCtx;
492 }
493
494 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000495 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000496 unsigned newID = VarDefinitions.size();
497 Context NewCtx = ContextFactory.add(Ctx, D, newID);
498 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
499 return NewCtx;
500 }
501
502 // Updates a definition only if that definition is already in the map.
503 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000504 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000505 if (Ctx.contains(D)) {
506 unsigned newID = VarDefinitions.size();
507 Context NewCtx = ContextFactory.remove(Ctx, D);
508 NewCtx = ContextFactory.add(NewCtx, D, newID);
509 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
510 return NewCtx;
511 }
512 return Ctx;
513 }
514
515 // Removes a definition from the context, but keeps the variable name
516 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000517 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000518 Context NewCtx = Ctx;
519 if (NewCtx.contains(D)) {
520 NewCtx = ContextFactory.remove(NewCtx, D);
521 NewCtx = ContextFactory.add(NewCtx, D, 0);
522 }
523 return NewCtx;
524 }
525
526 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000527 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000528 Context NewCtx = Ctx;
529 if (NewCtx.contains(D)) {
530 NewCtx = ContextFactory.remove(NewCtx, D);
531 }
532 return NewCtx;
533 }
534
535 Context intersectContexts(Context C1, Context C2);
536 Context createReferenceContext(Context C);
537 void intersectBackEdge(Context C1, Context C2);
538
539 friend class VarMapBuilder;
540};
541
542
543// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000544CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
545 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000546}
547
548
549/// Visitor which builds a LocalVariableMap
550class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
551public:
552 LocalVariableMap* VMap;
553 LocalVariableMap::Context Ctx;
554
555 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
556 : VMap(VM), Ctx(C) {}
557
558 void VisitDeclStmt(DeclStmt *S);
559 void VisitBinaryOperator(BinaryOperator *BO);
560};
561
562
563// Add new local variables to the variable map
564void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
565 bool modifiedCtx = false;
566 DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000567 for (const auto *D : DGrp) {
568 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
569 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000570
571 // Add local variables with trivial type to the variable map
572 QualType T = VD->getType();
573 if (T.isTrivialType(VD->getASTContext())) {
574 Ctx = VMap->addDefinition(VD, E, Ctx);
575 modifiedCtx = true;
576 }
577 }
578 }
579 if (modifiedCtx)
580 VMap->saveContext(S, Ctx);
581}
582
583// Update local variable definitions in variable map
584void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
585 if (!BO->isAssignmentOp())
586 return;
587
588 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
589
590 // Update the variable map and current context.
591 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
592 ValueDecl *VDec = DRE->getDecl();
593 if (Ctx.lookup(VDec)) {
594 if (BO->getOpcode() == BO_Assign)
595 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
596 else
597 // FIXME -- handle compound assignment operators
598 Ctx = VMap->clearDefinition(VDec, Ctx);
599 VMap->saveContext(BO, Ctx);
600 }
601 }
602}
603
604
605// Computes the intersection of two contexts. The intersection is the
606// set of variables which have the same definition in both contexts;
607// variables with different definitions are discarded.
608LocalVariableMap::Context
609LocalVariableMap::intersectContexts(Context C1, Context C2) {
610 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000611 for (const auto &P : C1) {
612 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000613 const unsigned *i2 = C2.lookup(Dec);
614 if (!i2) // variable doesn't exist on second path
615 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000616 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000617 Result = clearDefinition(Dec, Result);
618 }
619 return Result;
620}
621
622// For every variable in C, create a new variable that refers to the
623// definition in C. Return a new context that contains these new variables.
624// (We use this for a naive implementation of SSA on loop back-edges.)
625LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
626 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000627 for (const auto &P : C)
628 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000629 return Result;
630}
631
632// This routine also takes the intersection of C1 and C2, but it does so by
633// altering the VarDefinitions. C1 must be the result of an earlier call to
634// createReferenceContext.
635void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000636 for (const auto &P : C1) {
637 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000638 VarDefinition *VDef = &VarDefinitions[i1];
639 assert(VDef->isReference());
640
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000641 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000642 if (!i2 || (*i2 != i1))
643 VDef->Ref = 0; // Mark this variable as undefined
644 }
645}
646
647
648// Traverse the CFG in topological order, so all predecessors of a block
649// (excluding back-edges) are visited before the block itself. At
650// each point in the code, we calculate a Context, which holds the set of
651// variable definitions which are visible at that point in execution.
652// Visible variables are mapped to their definitions using an array that
653// contains all definitions.
654//
655// At join points in the CFG, the set is computed as the intersection of
656// the incoming sets along each edge, E.g.
657//
658// { Context | VarDefinitions }
659// int x = 0; { x -> x1 | x1 = 0 }
660// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
661// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
662// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
663// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
664//
665// This is essentially a simpler and more naive version of the standard SSA
666// algorithm. Those definitions that remain in the intersection are from blocks
667// that strictly dominate the current block. We do not bother to insert proper
668// phi nodes, because they are not used in our analysis; instead, wherever
669// a phi node would be required, we simply remove that definition from the
670// context (E.g. x above).
671//
672// The initial traversal does not capture back-edges, so those need to be
673// handled on a separate pass. Whenever the first pass encounters an
674// incoming back edge, it duplicates the context, creating new definitions
675// that refer back to the originals. (These correspond to places where SSA
676// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000677// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000678// node was actually required.) E.g.
679//
680// { Context | VarDefinitions }
681// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
682// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
683// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
684// ... { y -> y1 | x3 = 2, x2 = 1, ... }
685//
686void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000687 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000688 std::vector<CFGBlockInfo> &BlockInfo) {
689 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
690
691 CtxIndices.resize(CFGraph->getNumBlockIDs());
692
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000693 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000694 int CurrBlockID = CurrBlock->getBlockID();
695 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
696
697 VisitedBlocks.insert(CurrBlock);
698
699 // Calculate the entry context for the current block
700 bool HasBackEdges = false;
701 bool CtxInit = true;
702 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
703 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
704 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000705 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000706 HasBackEdges = true;
707 continue;
708 }
709
710 int PrevBlockID = (*PI)->getBlockID();
711 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
712
713 if (CtxInit) {
714 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
715 CtxInit = false;
716 }
717 else {
718 CurrBlockInfo->EntryContext =
719 intersectContexts(CurrBlockInfo->EntryContext,
720 PrevBlockInfo->ExitContext);
721 }
722 }
723
724 // Duplicate the context if we have back-edges, so we can call
725 // intersectBackEdges later.
726 if (HasBackEdges)
727 CurrBlockInfo->EntryContext =
728 createReferenceContext(CurrBlockInfo->EntryContext);
729
730 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000731 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000732 CurrBlockInfo->EntryIndex = getContextIndex();
733
734 // Visit all the statements in the basic block.
735 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
736 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
737 BE = CurrBlock->end(); BI != BE; ++BI) {
738 switch (BI->getKind()) {
739 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +0000740 CFGStmt CS = BI->castAs<CFGStmt>();
741 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000742 break;
743 }
744 default:
745 break;
746 }
747 }
748 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
749
750 // Mark variables on back edges as "unknown" if they've been changed.
751 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
752 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
753 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000754 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000755 continue;
756
757 CFGBlock *FirstLoopBlock = *SI;
758 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
759 Context LoopEnd = CurrBlockInfo->ExitContext;
760 intersectBackEdge(LoopBegin, LoopEnd);
761 }
762 }
763
764 // Put an extra entry at the end of the indexed context array
765 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000766 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000767}
768
Richard Smith92286672012-02-03 04:45:26 +0000769/// Find the appropriate source locations to use when producing diagnostics for
770/// each block in the CFG.
771static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000772 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000773 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000774 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000775 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
776
777 // Find the source location of the last statement in the block, if the
778 // block is not empty.
779 if (const Stmt *S = CurrBlock->getTerminator()) {
780 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
781 } else {
782 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
783 BE = CurrBlock->rend(); BI != BE; ++BI) {
784 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000785 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
786 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000787 break;
788 }
789 }
790 }
791
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000792 if (CurrBlockInfo->ExitLoc.isValid()) {
Richard Smith92286672012-02-03 04:45:26 +0000793 // This block contains at least one statement. Find the source location
794 // of the first statement in the block.
795 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
796 BE = CurrBlock->end(); BI != BE; ++BI) {
797 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000798 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
799 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000800 break;
801 }
802 }
803 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
804 CurrBlock != &CFGraph->getExit()) {
805 // The block is empty, and has a single predecessor. Use its exit
806 // location.
807 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
808 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
809 }
810 }
811}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000812
Ed Schoutenca988742014-09-03 06:00:11 +0000813class LockableFactEntry : public FactEntry {
814private:
815 bool Managed; ///< managed by ScopedLockable object
816
817public:
818 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
819 bool Mng = false, bool Asrt = false)
820 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
821
822 void
823 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
824 SourceLocation JoinLoc, LockErrorKind LEK,
825 ThreadSafetyHandler &Handler) const override {
826 if (!Managed && !asserted() && !negative() && !isUniversal()) {
827 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
828 LEK);
829 }
830 }
831
832 void handleUnlock(FactSet &FSet, FactManager &FactMan,
833 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
834 bool FullyRemove, ThreadSafetyHandler &Handler,
835 StringRef DiagKind) const override {
836 FSet.removeLock(FactMan, Cp);
837 if (!Cp.negative()) {
838 FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
839 !Cp, LK_Exclusive, UnlockLoc));
840 }
841 }
842};
843
844class ScopedLockableFactEntry : public FactEntry {
845private:
846 SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
847
848public:
849 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
850 const CapExprSet &Excl, const CapExprSet &Shrd)
851 : FactEntry(CE, LK_Exclusive, Loc, false) {
852 for (const auto &M : Excl)
853 UnderlyingMutexes.push_back(M.sexpr());
854 for (const auto &M : Shrd)
855 UnderlyingMutexes.push_back(M.sexpr());
856 }
857
858 void
859 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
860 SourceLocation JoinLoc, LockErrorKind LEK,
861 ThreadSafetyHandler &Handler) const override {
862 for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
863 if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
864 // If this scoped lock manages another mutex, and if the underlying
865 // mutex is still held, then warn about the underlying mutex.
866 Handler.handleMutexHeldEndOfScope(
867 "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
868 }
869 }
870 }
871
872 void handleUnlock(FactSet &FSet, FactManager &FactMan,
873 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
874 bool FullyRemove, ThreadSafetyHandler &Handler,
875 StringRef DiagKind) const override {
876 assert(!Cp.negative() && "Managing object cannot be negative.");
877 for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
878 CapabilityExpr UnderCp(UnderlyingMutex, false);
879 auto UnderEntry = llvm::make_unique<LockableFactEntry>(
880 !UnderCp, LK_Exclusive, UnlockLoc);
881
882 if (FullyRemove) {
883 // We're destroying the managing object.
884 // Remove the underlying mutex if it exists; but don't warn.
885 if (FSet.findLock(FactMan, UnderCp)) {
886 FSet.removeLock(FactMan, UnderCp);
887 FSet.addLock(FactMan, std::move(UnderEntry));
888 }
889 } else {
890 // We're releasing the underlying mutex, but not destroying the
891 // managing object. Warn on dual release.
892 if (!FSet.findLock(FactMan, UnderCp)) {
893 Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
894 UnlockLoc);
895 }
896 FSet.removeLock(FactMan, UnderCp);
897 FSet.addLock(FactMan, std::move(UnderEntry));
898 }
899 }
900 if (FullyRemove)
901 FSet.removeLock(FactMan, Cp);
902 }
903};
904
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000905/// \brief Class which implements the core thread safety analysis routines.
906class ThreadSafetyAnalyzer {
907 friend class BuildLockset;
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000908 friend class threadSafety::BeforeSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000909
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000910 llvm::BumpPtrAllocator Bpa;
911 threadSafety::til::MemRegionRef Arena;
912 threadSafety::SExprBuilder SxBuilder;
913
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000914 ThreadSafetyHandler &Handler;
DeLesley Hutchins42665222014-08-04 16:10:59 +0000915 const CXXMethodDecl *CurrentMethod;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000916 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000917 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000918 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000919
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000920 BeforeSet* GlobalBeforeSet;
921
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000922public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000923 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
924 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000925
DeLesley Hutchins3efd0492014-08-04 22:13:06 +0000926 bool inCurrentScope(const CapabilityExpr &CapE);
927
Ed Schoutenca988742014-09-03 06:00:11 +0000928 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
929 StringRef DiagKind, bool ReqAttr = false);
DeLesley Hutchins42665222014-08-04 16:10:59 +0000930 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000931 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
932 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000933
934 template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000935 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +0000936 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000937
938 template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +0000939 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000940 const NamedDecl *D,
941 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
942 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000943
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000944 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
945 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000946
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000947 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
948 const CFGBlock* PredBlock,
949 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +0000950
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000951 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
952 SourceLocation JoinLoc,
953 LockErrorKind LEK1, LockErrorKind LEK2,
954 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000955
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000956 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
957 SourceLocation JoinLoc, LockErrorKind LEK1,
958 bool Modify=true) {
959 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000960 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000961
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000962 void runAnalysis(AnalysisDeclContext &AC);
963};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +0000964} // namespace
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000965
966/// Process acquired_before and acquired_after attributes on Vd.
967BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
968 ThreadSafetyAnalyzer& Analyzer) {
969 // Create a new entry for Vd.
Reid Kleckner19ff5602015-11-20 19:08:30 +0000970 BeforeInfo *Info = nullptr;
971 {
972 // Keep InfoPtr in its own scope in case BMap is modified later and the
973 // reference becomes invalid.
974 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
975 if (!InfoPtr)
976 InfoPtr.reset(new BeforeInfo());
977 Info = InfoPtr.get();
978 }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000979
980 for (Attr* At : Vd->attrs()) {
981 switch (At->getKind()) {
982 case attr::AcquiredBefore: {
983 auto *A = cast<AcquiredBeforeAttr>(At);
984
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000985 // Read exprs from the attribute, and add them to BeforeVect.
986 for (const auto *Arg : A->args()) {
987 CapabilityExpr Cp =
988 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
989 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
Reid Kleckner19ff5602015-11-20 19:08:30 +0000990 Info->Vect.push_back(Cpvd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +0000991 auto It = BMap.find(Cpvd);
992 if (It == BMap.end())
993 insertAttrExprs(Cpvd, Analyzer);
994 }
995 }
996 break;
997 }
998 case attr::AcquiredAfter: {
999 auto *A = cast<AcquiredAfterAttr>(At);
1000
1001 // Read exprs from the attribute, and add them to BeforeVect.
1002 for (const auto *Arg : A->args()) {
1003 CapabilityExpr Cp =
1004 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1005 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1006 // Get entry for mutex listed in attribute
Reid Kleckner19ff5602015-11-20 19:08:30 +00001007 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1008 ArgInfo->Vect.push_back(Vd);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001009 }
1010 }
1011 break;
1012 }
1013 default:
1014 break;
1015 }
1016 }
1017
1018 return Info;
1019}
1020
Reid Kleckner19ff5602015-11-20 19:08:30 +00001021BeforeSet::BeforeInfo *
1022BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1023 ThreadSafetyAnalyzer &Analyzer) {
1024 auto It = BMap.find(Vd);
1025 BeforeInfo *Info = nullptr;
1026 if (It == BMap.end())
1027 Info = insertAttrExprs(Vd, Analyzer);
1028 else
1029 Info = It->second.get();
1030 assert(Info && "BMap contained nullptr?");
1031 return Info;
1032}
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001033
1034/// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1035void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1036 const FactSet& FSet,
1037 ThreadSafetyAnalyzer& Analyzer,
1038 SourceLocation Loc, StringRef CapKind) {
1039 SmallVector<BeforeInfo*, 8> InfoVect;
1040
1041 // Do a depth-first traversal of Vd.
1042 // Return true if there are cycles.
1043 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1044 if (!Vd)
1045 return false;
1046
Reid Kleckner19ff5602015-11-20 19:08:30 +00001047 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001048
1049 if (Info->Visited == 1)
1050 return true;
1051
1052 if (Info->Visited == 2)
1053 return false;
1054
Reid Kleckner19ff5602015-11-20 19:08:30 +00001055 if (Info->Vect.empty())
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001056 return false;
1057
1058 InfoVect.push_back(Info);
1059 Info->Visited = 1;
Reid Kleckner19ff5602015-11-20 19:08:30 +00001060 for (auto *Vdb : Info->Vect) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001061 // Exclude mutexes in our immediate before set.
1062 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1063 StringRef L1 = StartVd->getName();
1064 StringRef L2 = Vdb->getName();
1065 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1066 }
1067 // Transitively search other before sets, and warn on cycles.
1068 if (traverse(Vdb)) {
1069 if (CycMap.find(Vd) == CycMap.end()) {
1070 CycMap.insert(std::make_pair(Vd, true));
1071 StringRef L1 = Vd->getName();
1072 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1073 }
1074 }
1075 }
1076 Info->Visited = 2;
1077 return false;
1078 };
1079
1080 traverse(StartVd);
1081
1082 for (auto* Info : InfoVect)
1083 Info->Visited = 0;
1084}
1085
1086
1087
Aaron Ballmane0449042014-04-01 21:43:23 +00001088/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
1089static const ValueDecl *getValueDecl(const Expr *Exp) {
1090 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1091 return getValueDecl(CE->getSubExpr());
1092
1093 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1094 return DR->getDecl();
1095
1096 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1097 return ME->getMemberDecl();
1098
1099 return nullptr;
1100}
1101
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001102namespace {
Aaron Ballmane0449042014-04-01 21:43:23 +00001103template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001104class has_arg_iterator_range {
Aaron Ballmane0449042014-04-01 21:43:23 +00001105 typedef char yes[1];
1106 typedef char no[2];
1107
1108 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001109 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +00001110
1111 template <typename>
1112 static no& test(...);
1113
1114public:
1115 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1116};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001117} // namespace
Aaron Ballmane0449042014-04-01 21:43:23 +00001118
1119static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1120 return A->getName();
1121}
1122
1123static StringRef ClassifyDiagnostic(QualType VDT) {
1124 // We need to look at the declaration of the type of the value to determine
1125 // which it is. The type should either be a record or a typedef, or a pointer
1126 // or reference thereof.
1127 if (const auto *RT = VDT->getAs<RecordType>()) {
1128 if (const auto *RD = RT->getDecl())
1129 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1130 return ClassifyDiagnostic(CA);
1131 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1132 if (const auto *TD = TT->getDecl())
1133 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1134 return ClassifyDiagnostic(CA);
1135 } else if (VDT->isPointerType() || VDT->isReferenceType())
1136 return ClassifyDiagnostic(VDT->getPointeeType());
1137
1138 return "mutex";
1139}
1140
1141static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1142 assert(VD && "No ValueDecl passed");
1143
1144 // The ValueDecl is the declaration of a mutex or role (hopefully).
1145 return ClassifyDiagnostic(VD->getType());
1146}
1147
1148template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001149static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001150 StringRef>::type
1151ClassifyDiagnostic(const AttrTy *A) {
1152 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1153 return ClassifyDiagnostic(VD);
1154 return "mutex";
1155}
1156
1157template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001158static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +00001159 StringRef>::type
1160ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001161 for (const auto *Arg : A->args()) {
1162 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +00001163 return ClassifyDiagnostic(VD);
1164 }
1165 return "mutex";
1166}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001167
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001168
1169inline bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1170 if (!CurrentMethod)
1171 return false;
1172 if (auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1173 auto *VD = P->clangDecl();
1174 if (VD)
1175 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1176 }
1177 return false;
1178}
1179
1180
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001181/// \brief Add a new lock to the lockset, warning if the lock is already there.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001182/// \param ReqAttr -- true if this is part of an initial Requires attribute.
Ed Schoutenca988742014-09-03 06:00:11 +00001183void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1184 std::unique_ptr<FactEntry> Entry,
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001185 StringRef DiagKind, bool ReqAttr) {
Ed Schoutenca988742014-09-03 06:00:11 +00001186 if (Entry->shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001187 return;
1188
Ed Schoutenca988742014-09-03 06:00:11 +00001189 if (!ReqAttr && !Entry->negative()) {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001190 // look for the negative capability, and remove it from the fact set.
Ed Schoutenca988742014-09-03 06:00:11 +00001191 CapabilityExpr NegC = !*Entry;
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001192 FactEntry *Nen = FSet.findLock(FactMan, NegC);
1193 if (Nen) {
1194 FSet.removeLock(FactMan, NegC);
1195 }
1196 else {
Ed Schoutenca988742014-09-03 06:00:11 +00001197 if (inCurrentScope(*Entry) && !Entry->asserted())
1198 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1199 NegC.toString(), Entry->loc());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001200 }
1201 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00001202
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001203 // Check before/after constraints
1204 if (Handler.issueBetaWarnings() &&
1205 !Entry->asserted() && !Entry->declared()) {
1206 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1207 Entry->loc(), DiagKind);
1208 }
1209
DeLesley Hutchins42665222014-08-04 16:10:59 +00001210 // FIXME: Don't always warn when we have support for reentrant locks.
Ed Schoutenca988742014-09-03 06:00:11 +00001211 if (FSet.findLock(FactMan, *Entry)) {
1212 if (!Entry->asserted())
1213 Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001214 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00001215 FSet.addLock(FactMan, std::move(Entry));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001216 }
1217}
1218
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001219
1220/// \brief Remove a lock from the lockset, warning if the lock is not there.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001221/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins42665222014-08-04 16:10:59 +00001222void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001223 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +00001224 bool FullyRemove, LockKind ReceivedKind,
1225 StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001226 if (Cp.shouldIgnore())
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +00001227 return;
1228
DeLesley Hutchins42665222014-08-04 16:10:59 +00001229 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001230 if (!LDat) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001231 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001232 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001233 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001234
Aaron Ballmandf115d92014-03-21 14:48:48 +00001235 // Generic lock removal doesn't care about lock kind mismatches, but
1236 // otherwise diagnose when the lock kinds are mismatched.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001237 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1238 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
1239 LDat->kind(), ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001240 }
1241
Ed Schoutenca988742014-09-03 06:00:11 +00001242 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1243 DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001244}
1245
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001246
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001247/// \brief Extract the list of mutexIDs from the attribute on an expression,
1248/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001249template <typename AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001250void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001251 Expr *Exp, const NamedDecl *D,
1252 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001253 if (Attr->args_size() == 0) {
1254 // The mutex held is the "this" object.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001255 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1256 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001257 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1258 return;
1259 }
1260 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001261 if (!Cp.shouldIgnore())
1262 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001263 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001264 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001265
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001266 for (const auto *Arg : Attr->args()) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001267 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1268 if (Cp.isInvalid()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001269 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
DeLesley Hutchins42665222014-08-04 16:10:59 +00001270 continue;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001271 }
1272 //else
DeLesley Hutchins42665222014-08-04 16:10:59 +00001273 if (!Cp.shouldIgnore())
1274 Mtxs.push_back_nodup(Cp);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001275 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001276}
1277
1278
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001279/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1280/// trylock applies to the given edge, then push them onto Mtxs, discarding
1281/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001282template <class AttrType>
DeLesley Hutchins42665222014-08-04 16:10:59 +00001283void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001284 Expr *Exp, const NamedDecl *D,
1285 const CFGBlock *PredBlock,
1286 const CFGBlock *CurrBlock,
1287 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001288 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001289 bool branch = false;
1290 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001291 branch = BLE->getValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001292 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001293 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001294
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001295 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001296 if (Neg)
1297 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001298
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001299 // If we've taken the trylock branch, then add the lock
1300 int i = 0;
1301 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1302 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001303 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001304 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001305 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001306}
1307
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001308static bool getStaticBooleanValue(Expr *E, bool &TCond) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001309 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1310 TCond = false;
1311 return true;
1312 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1313 TCond = BLE->getValue();
1314 return true;
1315 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1316 TCond = ILE->getValue().getBoolValue();
1317 return true;
1318 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1319 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1320 }
1321 return false;
1322}
1323
1324
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001325// If Cond can be traced back to a function call, return the call expression.
1326// The negate variable should be called with false, and will be set to true
1327// if the function call is negated, e.g. if (!mu.tryLock(...))
1328const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1329 LocalVarContext C,
1330 bool &Negate) {
1331 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001332 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001333
1334 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1335 return CallExp;
1336 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001337 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1338 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1339 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001340 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1341 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1342 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001343 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1344 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1345 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001346 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1347 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1348 return getTrylockCallExpr(E, C, Negate);
1349 }
1350 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1351 if (UOP->getOpcode() == UO_LNot) {
1352 Negate = !Negate;
1353 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1354 }
Craig Topper25542942014-05-20 04:30:07 +00001355 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001356 }
1357 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1358 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1359 if (BOP->getOpcode() == BO_NE)
1360 Negate = !Negate;
1361
1362 bool TCond = false;
1363 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1364 if (!TCond) Negate = !Negate;
1365 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1366 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001367 TCond = false;
1368 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001369 if (!TCond) Negate = !Negate;
1370 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1371 }
Craig Topper25542942014-05-20 04:30:07 +00001372 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001373 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001374 if (BOP->getOpcode() == BO_LAnd) {
1375 // LHS must have been evaluated in a different block.
1376 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1377 }
1378 if (BOP->getOpcode() == BO_LOr) {
1379 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1380 }
Craig Topper25542942014-05-20 04:30:07 +00001381 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001382 }
Craig Topper25542942014-05-20 04:30:07 +00001383 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001384}
1385
1386
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001387/// \brief Find the lockset that holds on the edge between PredBlock
1388/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1389/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001390void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1391 const FactSet &ExitSet,
1392 const CFGBlock *PredBlock,
1393 const CFGBlock *CurrBlock) {
1394 Result = ExitSet;
1395
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001396 const Stmt *Cond = PredBlock->getTerminatorCondition();
1397 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001398 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001399
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001400 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001401 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1402 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001403 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001404
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001405 CallExpr *Exp =
1406 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001407 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001408 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001409
1410 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1411 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001412 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001413
DeLesley Hutchins42665222014-08-04 16:10:59 +00001414 CapExprSet ExclusiveLocksToAdd;
1415 CapExprSet SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001416
1417 // If the condition is a call to a Trylock function, then grab the attributes
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001418 for (auto *Attr : FunDecl->attrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001419 switch (Attr->getKind()) {
1420 case attr::ExclusiveTrylockFunction: {
1421 ExclusiveTrylockFunctionAttr *A =
1422 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001423 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1424 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001425 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001426 break;
1427 }
1428 case attr::SharedTrylockFunction: {
1429 SharedTrylockFunctionAttr *A =
1430 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001431 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001432 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001433 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001434 break;
1435 }
1436 default:
1437 break;
1438 }
1439 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001440
1441 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001442 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001443 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001444 addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1445 LK_Exclusive, Loc),
Aaron Ballmane0449042014-04-01 21:43:23 +00001446 CapDiagKind);
1447 for (const auto &SharedLockToAdd : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001448 addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
1449 LK_Shared, Loc),
DeLesley Hutchins42665222014-08-04 16:10:59 +00001450 CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001451}
1452
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001453namespace {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001454/// \brief We use this class to visit different types of expressions in
1455/// CFGBlocks, and build up the lockset.
1456/// An expression may cause us to add or remove locks from the lockset, or else
1457/// output error messages related to missing locks.
1458/// FIXME: In future, we may be able to not inherit from a visitor.
1459class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001460 friend class ThreadSafetyAnalyzer;
1461
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001462 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001463 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001464 LocalVariableMap::Context LVarCtx;
1465 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001466
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001467 // helper functions
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001468 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001469 Expr *MutexExp, ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001470 StringRef DiagKind, SourceLocation Loc);
Aaron Ballmane0449042014-04-01 21:43:23 +00001471 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1472 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001473
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001474 void checkAccess(const Expr *Exp, AccessKind AK,
1475 ProtectedOperationKind POK = POK_VarAccess);
1476 void checkPtAccess(const Expr *Exp, AccessKind AK,
1477 ProtectedOperationKind POK = POK_VarAccess);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001478
Craig Topper25542942014-05-20 04:30:07 +00001479 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001480
Caitlin Sadowski33208342011-09-09 16:11:56 +00001481public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001482 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001483 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001484 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001485 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001486 LVarCtx(Info.EntryContext),
1487 CtxIndex(Info.EntryIndex)
1488 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001489
1490 void VisitUnaryOperator(UnaryOperator *UO);
1491 void VisitBinaryOperator(BinaryOperator *BO);
1492 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001493 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001494 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001495 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001496};
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00001497} // namespace
DeLesley Hutchins42665222014-08-04 16:10:59 +00001498
Caitlin Sadowski33208342011-09-09 16:11:56 +00001499/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001500/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001501void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001502 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001503 ProtectedOperationKind POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001504 StringRef DiagKind, SourceLocation Loc) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001505 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001506
DeLesley Hutchins42665222014-08-04 16:10:59 +00001507 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1508 if (Cp.isInvalid()) {
1509 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001510 return;
DeLesley Hutchins42665222014-08-04 16:10:59 +00001511 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001512 return;
1513 }
1514
DeLesley Hutchins42665222014-08-04 16:10:59 +00001515 if (Cp.negative()) {
1516 // Negative capabilities act like locks excluded
1517 FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1518 if (LDat) {
1519 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001520 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001521 return;
1522 }
1523
1524 // If this does not refer to a negative capability in the same class,
1525 // then stop here.
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001526 if (!Analyzer->inCurrentScope(Cp))
DeLesley Hutchins42665222014-08-04 16:10:59 +00001527 return;
1528
1529 // Otherwise the negative requirement must be propagated to the caller.
1530 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1531 if (!LDat) {
1532 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001533 LK_Shared, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001534 }
1535 return;
1536 }
1537
1538 FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001539 bool NoError = true;
1540 if (!LDat) {
1541 // No exact match found. Look for a partial match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001542 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1543 if (LDat) {
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001544 // Warn that there's no precise match.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001545 std::string PartMatchStr = LDat->toString();
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001546 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001547 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1548 LK, Loc, &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001549 } else {
1550 // Warn that there's no match at all.
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001551 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1552 LK, Loc);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001553 }
1554 NoError = false;
1555 }
1556 // Make sure the mutex we found is the right kind.
DeLesley Hutchins42665222014-08-04 16:10:59 +00001557 if (NoError && LDat && !LDat->isAtLeast(LK)) {
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001558 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1559 LK, Loc);
DeLesley Hutchins42665222014-08-04 16:10:59 +00001560 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001561}
1562
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001563/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001564void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001565 Expr *MutexExp, StringRef DiagKind) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00001566 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1567 if (Cp.isInvalid()) {
1568 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1569 return;
1570 } else if (Cp.shouldIgnore()) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001571 return;
1572 }
1573
DeLesley Hutchins42665222014-08-04 16:10:59 +00001574 FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
1575 if (LDat) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001576 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchins42665222014-08-04 16:10:59 +00001577 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1578 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001579}
1580
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001581/// \brief Checks guarded_by and pt_guarded_by attributes.
1582/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1583/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1584/// Similarly, we check if the access is to an expression that dereferences
1585/// a pointer marked with pt_guarded_by.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001586void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1587 ProtectedOperationKind POK) {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001588 Exp = Exp->IgnoreParenCasts();
1589
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001590 SourceLocation Loc = Exp->getExprLoc();
1591
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001592 // Local variables of reference type cannot be re-assigned;
1593 // map them to their initializer.
1594 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1595 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1596 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1597 if (const auto *E = VD->getInit()) {
1598 Exp = E;
1599 continue;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001600 }
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001601 }
DeLesley Hutchins6d41f382014-11-05 23:09:28 +00001602 break;
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001603 }
1604
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001605 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1606 // For dereferences
1607 if (UO->getOpcode() == clang::UO_Deref)
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001608 checkPtAccess(UO->getSubExpr(), AK, POK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001609 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001610 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001611
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001612 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001613 checkPtAccess(AE->getLHS(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001614 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001615 }
1616
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001617 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1618 if (ME->isArrow())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001619 checkPtAccess(ME->getBase(), AK, POK);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001620 else
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001621 checkAccess(ME->getBase(), AK, POK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001622 }
1623
Caitlin Sadowski33208342011-09-09 16:11:56 +00001624 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001625 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001626 return;
1627
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001628 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001629 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001630 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001631
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001632 for (const auto *I : D->specific_attrs<GuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001633 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001634 ClassifyDiagnostic(I), Loc);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001635}
1636
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001637
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001638/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001639/// POK is the same operationKind that was passed to checkAccess.
1640void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1641 ProtectedOperationKind POK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001642 while (true) {
1643 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1644 Exp = PE->getSubExpr();
1645 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001646 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001647 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1648 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1649 // If it's an actual array, and not a pointer, then it's elements
1650 // are protected by GUARDED_BY, not PT_GUARDED_BY;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001651 checkAccess(CE->getSubExpr(), AK, POK);
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001652 return;
1653 }
1654 Exp = CE->getSubExpr();
1655 continue;
1656 }
1657 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001658 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001659
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001660 // Pass by reference warnings are under a different flag.
1661 ProtectedOperationKind PtPOK = POK_VarDereference;
1662 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1663
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001664 const ValueDecl *D = getValueDecl(Exp);
1665 if (!D || !D->hasAttrs())
1666 return;
1667
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001668 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001669 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001670 Exp->getExprLoc());
1671
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001672 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001673 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001674 ClassifyDiagnostic(I), Exp->getExprLoc());
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001675}
1676
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001677/// \brief Process a function call, method call, constructor call,
1678/// or destructor call. This involves looking at the attributes on the
1679/// corresponding function/method/constructor/destructor, issuing warnings,
1680/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001681///
1682/// FIXME: For classes annotated with one of the guarded annotations, we need
1683/// to treat const method calls as reads and non-const method calls as writes,
1684/// and check that the appropriate locks are held. Non-const method calls with
1685/// the same signature as const method calls can be also treated as reads.
1686///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001687void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001688 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins42665222014-08-04 16:10:59 +00001689 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1690 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001691 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
Aaron Ballmane0449042014-04-01 21:43:23 +00001692 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001693
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001694 // Figure out if we're calling the constructor of scoped lockable class
1695 bool isScopedVar = false;
1696 if (VD) {
1697 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1698 const CXXRecordDecl* PD = CD->getParent();
1699 if (PD && PD->hasAttr<ScopedLockableAttr>())
1700 isScopedVar = true;
1701 }
1702 }
1703
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001704 for(Attr *Atconst : D->attrs()) {
1705 Attr* At = const_cast<Attr*>(Atconst);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001706 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001707 // When we encounter a lock function, we need to add the lock to our
1708 // lockset.
1709 case attr::AcquireCapability: {
1710 auto *A = cast<AcquireCapabilityAttr>(At);
1711 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1712 : ExclusiveLocksToAdd,
1713 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001714
1715 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001716 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001717 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001718
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001719 // An assert will add a lock to the lockset, but will not generate
1720 // a warning if it is already there, and will not generate a warning
1721 // if it is not removed.
1722 case attr::AssertExclusiveLock: {
1723 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1724
DeLesley Hutchins42665222014-08-04 16:10:59 +00001725 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001726 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001727 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001728 Analyzer->addLock(FSet,
1729 llvm::make_unique<LockableFactEntry>(
1730 AssertLock, LK_Exclusive, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001731 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001732 break;
1733 }
1734 case attr::AssertSharedLock: {
1735 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1736
DeLesley Hutchins42665222014-08-04 16:10:59 +00001737 CapExprSet AssertLocks;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001738 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001739 for (const auto &AssertLock : AssertLocks)
Ed Schoutenca988742014-09-03 06:00:11 +00001740 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1741 AssertLock, LK_Shared, Loc, false, true),
Aaron Ballmane0449042014-04-01 21:43:23 +00001742 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001743 break;
1744 }
1745
Caitlin Sadowski33208342011-09-09 16:11:56 +00001746 // When we encounter an unlock function, we need to remove unlocked
1747 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001748 case attr::ReleaseCapability: {
1749 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001750 if (A->isGeneric())
1751 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1752 else if (A->isShared())
1753 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1754 else
1755 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001756
1757 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001758 break;
1759 }
1760
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001761 case attr::RequiresCapability: {
1762 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001763 for (auto *Arg : A->args()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001764 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
DeLesley Hutchins4133b132014-08-14 19:17:06 +00001765 POK_FunctionCall, ClassifyDiagnostic(A),
1766 Exp->getExprLoc());
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001767 // use for adopting a lock
1768 if (isScopedVar) {
1769 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1770 : ScopedExclusiveReqs,
1771 A, Exp, D, VD);
1772 }
1773 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001774 break;
1775 }
1776
1777 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001778 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001779 for (auto *Arg : A->args())
1780 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001781 break;
1782 }
1783
Alp Tokerd4733632013-12-05 04:47:09 +00001784 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001785 default:
1786 break;
1787 }
1788 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001789
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001790 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00001791 for (const auto &M : ExclusiveLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001792 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1793 M, LK_Exclusive, Loc, isScopedVar),
Aaron Ballmane0449042014-04-01 21:43:23 +00001794 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001795 for (const auto &M : SharedLocksToAdd)
Ed Schoutenca988742014-09-03 06:00:11 +00001796 Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
1797 M, LK_Shared, Loc, isScopedVar),
Aaron Ballmane0449042014-04-01 21:43:23 +00001798 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001799
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001800 if (isScopedVar) {
Ed Schoutenca988742014-09-03 06:00:11 +00001801 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001802 SourceLocation MLoc = VD->getLocation();
1803 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchins42665222014-08-04 16:10:59 +00001804 // FIXME: does this store a pointer to DRE?
1805 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins3c355aa2015-02-04 21:16:17 +00001806
1807 std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
1808 std::back_inserter(ExclusiveLocksToAdd));
1809 std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
1810 std::back_inserter(SharedLocksToAdd));
Ed Schoutenca988742014-09-03 06:00:11 +00001811 Analyzer->addLock(FSet,
1812 llvm::make_unique<ScopedLockableFactEntry>(
1813 Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
1814 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001815 }
1816
1817 // Remove locks.
1818 // FIXME -- should only fully remove if the attribute refers to 'this'.
1819 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001820 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001821 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001822 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001823 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001824 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001825 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001826}
1827
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001828
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001829/// \brief For unary operations which read and write a variable, we need to
1830/// check whether we hold any required mutexes. Reads are checked in
1831/// VisitCastExpr.
1832void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1833 switch (UO->getOpcode()) {
1834 case clang::UO_PostDec:
1835 case clang::UO_PostInc:
1836 case clang::UO_PreDec:
1837 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001838 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001839 break;
1840 }
1841 default:
1842 break;
1843 }
1844}
1845
1846/// For binary operations which assign to a variable (writes), we need to check
1847/// whether we hold any required mutexes.
1848/// FIXME: Deal with non-primitive types.
1849void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1850 if (!BO->isAssignmentOp())
1851 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001852
1853 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001854 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001855
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001856 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001857}
1858
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001859
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001860/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1861/// need to ensure we hold any required mutexes.
1862/// FIXME: Deal with non-primitive types.
1863void BuildLockset::VisitCastExpr(CastExpr *CE) {
1864 if (CE->getCastKind() != CK_LValueToRValue)
1865 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001866 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001867}
1868
1869
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001870void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001871 bool ExamineArgs = true;
1872 bool OperatorFun = false;
1873
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001874 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1875 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
1876 // ME can be null when calling a method pointer
1877 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001878
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001879 if (ME && MD) {
1880 if (ME->isArrow()) {
1881 if (MD->isConst()) {
1882 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1883 } else { // FIXME -- should be AK_Written
1884 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001885 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001886 } else {
1887 if (MD->isConst())
1888 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1889 else // FIXME -- should be AK_Written
1890 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001891 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001892 }
1893 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001894 OperatorFun = true;
1895
1896 auto OEop = OE->getOperator();
1897 switch (OEop) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001898 case OO_Equal: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001899 ExamineArgs = false;
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001900 const Expr *Target = OE->getArg(0);
1901 const Expr *Source = OE->getArg(1);
1902 checkAccess(Target, AK_Written);
1903 checkAccess(Source, AK_Read);
1904 break;
1905 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001906 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001907 case OO_Arrow:
1908 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001909 const Expr *Obj = OE->getArg(0);
1910 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001911 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
1912 // Grrr. operator* can be multiplication...
1913 checkPtAccess(Obj, AK_Read);
1914 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001915 break;
1916 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001917 default: {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001918 // TODO: get rid of this, and rely on pass-by-ref instead.
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001919 const Expr *Obj = OE->getArg(0);
1920 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001921 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001922 }
1923 }
1924 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001925
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001926 if (ExamineArgs) {
1927 if (FunctionDecl *FD = Exp->getDirectCallee()) {
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001928
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001929 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
1930 // only turns off checking within the body of a function, but we also
1931 // use it to turn off checking in arguments to the function. This
1932 // could result in some false negatives, but the alternative is to
1933 // create yet another attribute.
1934 //
1935 if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
1936 unsigned Fn = FD->getNumParams();
1937 unsigned Cn = Exp->getNumArgs();
1938 unsigned Skip = 0;
1939
1940 unsigned i = 0;
1941 if (OperatorFun) {
1942 if (isa<CXXMethodDecl>(FD)) {
1943 // First arg in operator call is implicit self argument,
1944 // and doesn't appear in the FunctionDecl.
1945 Skip = 1;
1946 Cn--;
1947 } else {
1948 // Ignore the first argument of operators; it's been checked above.
1949 i = 1;
1950 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001951 }
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001952 // Ignore default arguments
1953 unsigned n = (Fn < Cn) ? Fn : Cn;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001954
DeLesley Hutchins445a31c2015-09-03 21:14:22 +00001955 for (; i < n; ++i) {
1956 ParmVarDecl* Pvd = FD->getParamDecl(i);
1957 Expr* Arg = Exp->getArg(i+Skip);
1958 QualType Qt = Pvd->getType();
1959 if (Qt->isReferenceType())
1960 checkAccess(Arg, AK_Read, POK_PassByRef);
1961 }
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001962 }
1963 }
1964 }
1965
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001966 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1967 if(!D || !D->hasAttrs())
1968 return;
1969 handleCall(Exp, D);
1970}
1971
1972void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001973 const CXXConstructorDecl *D = Exp->getConstructor();
1974 if (D && D->isCopyConstructor()) {
1975 const Expr* Source = Exp->getArg(0);
1976 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001977 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001978 // FIXME -- only handles constructors in DeclStmt below.
1979}
1980
1981void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001982 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001983 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001984
Aaron Ballman9ee54d12014-05-14 20:42:13 +00001985 for (auto *D : S->getDeclGroup()) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001986 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1987 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00001988 // handle constructors that involve temporaries
1989 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1990 E = EWC->getSubExpr();
1991
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001992 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1993 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1994 if (!CtorD || !CtorD->hasAttrs())
1995 return;
1996 handleCall(CE, CtorD, VD);
1997 }
1998 }
1999 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00002000}
2001
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002002
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002003
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00002004/// \brief Compute the intersection of two locksets and issue warnings for any
2005/// locks in the symmetric difference.
2006///
2007/// This function is used at a merge point in the CFG when comparing the lockset
2008/// of each branch being merged. For example, given the following sequence:
2009/// A; if () then B; else C; D; we need to check that the lockset after B and C
2010/// are the same. In the event of a difference, we use the intersection of these
2011/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002012///
Ted Kremenek78094ca2012-08-22 23:50:41 +00002013/// \param FSet1 The first lockset.
2014/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002015/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002016/// \param LEK1 The error message to report if a mutex is missing from LSet1
2017/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002018void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2019 const FactSet &FSet2,
2020 SourceLocation JoinLoc,
2021 LockErrorKind LEK1,
2022 LockErrorKind LEK2,
2023 bool Modify) {
2024 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002025
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002026 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002027 for (const auto &Fact : FSet2) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002028 const FactEntry *LDat1 = nullptr;
2029 const FactEntry *LDat2 = &FactMan[Fact];
2030 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2031 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002032
DeLesley Hutchins42665222014-08-04 16:10:59 +00002033 if (LDat1) {
2034 if (LDat1->kind() != LDat2->kind()) {
2035 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2036 LDat2->loc(), LDat1->loc());
2037 if (Modify && LDat1->kind() != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002038 // Take the exclusive lock, which is the one in FSet2.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002039 *Iter1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002040 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002041 }
DeLesley Hutchins42665222014-08-04 16:10:59 +00002042 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002043 // The non-asserted lock in FSet2 is the one we want to track.
DeLesley Hutchins42665222014-08-04 16:10:59 +00002044 *Iter1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00002045 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002046 } else {
Ed Schoutenca988742014-09-03 06:00:11 +00002047 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2048 Handler);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002049 }
2050 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002051
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00002052 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00002053 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchins42665222014-08-04 16:10:59 +00002054 const FactEntry *LDat1 = &FactMan[Fact];
2055 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00002056
DeLesley Hutchins42665222014-08-04 16:10:59 +00002057 if (!LDat2) {
Ed Schoutenca988742014-09-03 06:00:11 +00002058 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2059 Handler);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002060 if (Modify)
DeLesley Hutchins42665222014-08-04 16:10:59 +00002061 FSet1.removeLock(FactMan, *LDat1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002062 }
2063 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002064}
2065
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002066
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002067// Return true if block B never continues to its successors.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002068static bool neverReturns(const CFGBlock *B) {
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002069 if (B->hasNoReturnElement())
2070 return true;
2071 if (B->empty())
2072 return false;
2073
2074 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00002075 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2076 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002077 return true;
2078 }
2079 return false;
2080}
2081
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002082
Caitlin Sadowski33208342011-09-09 16:11:56 +00002083/// \brief Check a function's CFG for thread-safety violations.
2084///
2085/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2086/// at the end of each block, and issue warnings for thread safety violations.
2087/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002088void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002089 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2090 // For now, we just use the walker to set things up.
2091 threadSafety::CFGWalker walker;
2092 if (!walker.init(AC))
2093 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002094
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002095 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002096 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002097
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002098 CFG *CFGraph = walker.getGraph();
2099 const NamedDecl *D = walker.getDecl();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002100 const FunctionDecl *CurrentFunction = dyn_cast<FunctionDecl>(D);
DeLesley Hutchins42665222014-08-04 16:10:59 +00002101 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002102
Aaron Ballman9ead1242013-12-19 02:39:40 +00002103 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00002104 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00002105
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002106 // FIXME: Do something a bit more intelligent inside constructor and
2107 // destructor code. Constructors and destructors must assume unique access
2108 // to 'this', so checks on member variable access is disabled, but we should
2109 // still enable checks on other objects.
2110 if (isa<CXXConstructorDecl>(D))
2111 return; // Don't check inside constructors.
2112 if (isa<CXXDestructorDecl>(D))
2113 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002114
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002115 Handler.enterFunction(CurrentFunction);
2116
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002117 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002118 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00002119
2120 // We need to explore the CFG via a "topological" ordering.
2121 // That way, we will be guaranteed to have information about required
2122 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002123 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002124 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002125
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002126 // Mark entry block as reachable
2127 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2128
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002129 // Compute SSA names for local variables
2130 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2131
Richard Smith92286672012-02-03 04:45:26 +00002132 // Fill in source locations for all CFGBlocks.
2133 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2134
DeLesley Hutchins42665222014-08-04 16:10:59 +00002135 CapExprSet ExclusiveLocksAcquired;
2136 CapExprSet SharedLocksAcquired;
2137 CapExprSet LocksReleased;
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002138
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002139 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00002140 // to initial lockset. Also turn off checking for lock and unlock functions.
2141 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00002142 if (!SortedGraph->empty() && D->hasAttrs()) {
2143 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002144 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002145
DeLesley Hutchins42665222014-08-04 16:10:59 +00002146 CapExprSet ExclusiveLocksToAdd;
2147 CapExprSet SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00002148 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002149
2150 SourceLocation Loc = D->getLocation();
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002151 for (const auto *Attr : D->attrs()) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002152 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00002153 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00002154 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00002155 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002156 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002157 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002158 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2159 // We must ignore such methods.
2160 if (A->args_size() == 0)
2161 return;
2162 // FIXME -- deal with exclusive vs. shared unlock functions?
Aaron Ballman0491afa2014-04-18 13:13:15 +00002163 getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
2164 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002165 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00002166 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002167 if (A->args_size() == 0)
2168 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00002169 getMutexIDs(A->isShared() ? SharedLocksAcquired
2170 : ExclusiveLocksAcquired,
2171 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00002172 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00002173 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2174 // Don't try to check trylock functions for now
2175 return;
2176 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2177 // Don't try to check trylock functions for now
2178 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002179 }
2180 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00002181
2182 // FIXME -- Loc can be wrong here.
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002183 for (const auto &Mu : ExclusiveLocksToAdd) {
2184 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2185 Entry->setDeclared(true);
2186 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2187 }
2188 for (const auto &Mu : SharedLocksToAdd) {
2189 auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2190 Entry->setDeclared(true);
2191 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2192 }
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00002193 }
2194
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00002195 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002196 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002197 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00002198
2199 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002200 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002201
2202 // Iterate through the predecessor blocks and warn if the lockset for all
2203 // predecessors is not the same. We take the entry lockset of the current
2204 // block to be the intersection of all previous locksets.
2205 // FIXME: By keeping the intersection, we may output more errors in future
2206 // for a lock which is not in the intersection, but was in the union. We
2207 // may want to also keep the union in future. As an example, let's say
2208 // the intersection contains Mutex L, and the union contains L and M.
2209 // Later we unlock M. At this point, we would output an error because we
2210 // never locked M; although the real error is probably that we forgot to
2211 // lock M on all code paths. Conversely, let's say that later we lock M.
2212 // In this case, we should compare against the intersection instead of the
2213 // union because the real error is probably that we forgot to unlock M on
2214 // all code paths.
2215 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002216 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002217 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2218 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2219
2220 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00002221 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002222 continue;
2223
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002224 int PrevBlockID = (*PI)->getBlockID();
2225 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2226
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002227 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00002228 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00002229 continue;
2230
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002231 // Okay, we can reach this block from the entry.
2232 CurrBlockInfo->Reachable = true;
2233
Richard Smith815b29d2012-02-03 03:30:07 +00002234 // If the previous block ended in a 'continue' or 'break' statement, then
2235 // a difference in locksets is probably due to a bug in that block, rather
2236 // than in some other predecessor. In that case, keep the other
2237 // predecessor's lockset.
2238 if (const Stmt *Terminator = (*PI)->getTerminator()) {
2239 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2240 SpecialBlocks.push_back(*PI);
2241 continue;
2242 }
2243 }
2244
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002245 FactSet PrevLockset;
2246 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002247
Caitlin Sadowski33208342011-09-09 16:11:56 +00002248 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002249 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002250 LocksetInitialized = true;
2251 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002252 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2253 CurrBlockInfo->EntryLoc,
2254 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002255 }
2256 }
2257
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002258 // Skip rest of block if it's not reachable.
2259 if (!CurrBlockInfo->Reachable)
2260 continue;
2261
Richard Smith815b29d2012-02-03 03:30:07 +00002262 // Process continue and break blocks. Assume that the lockset for the
2263 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002264 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00002265 int PrevBlockID = PrevBlock->getBlockID();
2266 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2267
2268 if (!LocksetInitialized) {
2269 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2270 LocksetInitialized = true;
2271 } else {
2272 // Determine whether this edge is a loop terminator for diagnostic
2273 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2274 // it might also be part of a switch. Also, a subsequent destructor
2275 // might add to the lockset, in which case the real issue might be a
2276 // double lock on the other path.
2277 const Stmt *Terminator = PrevBlock->getTerminator();
2278 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2279
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002280 FactSet PrevLockset;
2281 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2282 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002283
Richard Smith815b29d2012-02-03 03:30:07 +00002284 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002285 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2286 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00002287 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002288 : LEK_LockedSomePredecessors,
2289 false);
Richard Smith815b29d2012-02-03 03:30:07 +00002290 }
2291 }
2292
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00002293 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2294
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00002295 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00002296 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
2297 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002298 switch (BI->getKind()) {
2299 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002300 CFGStmt CS = BI->castAs<CFGStmt>();
2301 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002302 break;
2303 }
2304 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2305 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002306 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2307 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2308 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002309 if (!DD->hasAttrs())
2310 break;
2311
2312 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002313 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
Richard Trieua1877592015-03-16 21:49:43 +00002314 DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
2315 VK_LValue, AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002316 LocksetBuilder.handleCall(&DRE, DD);
2317 break;
2318 }
2319 default:
2320 break;
2321 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002322 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002323 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002324
2325 // For every back edge from CurrBlock (the end of the loop) to another block
2326 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2327 // the one held at the beginning of FirstLoopBlock. We can look up the
2328 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2329 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2330 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2331
2332 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002333 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002334 continue;
2335
2336 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002337 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2338 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2339 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2340 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002341 LEK_LockedSomeLoopIterations,
2342 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002343 }
2344 }
2345
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002346 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2347 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002348
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002349 // Skip the final check if the exit block is unreachable.
2350 if (!Final->Reachable)
2351 return;
2352
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002353 // By default, we expect all locks held on entry to be held on exit.
2354 FactSet ExpectedExitSet = Initial->EntrySet;
2355
2356 // Adjust the expected exit set by adding or removing locks, as declared
2357 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2358 // issue the appropriate warning.
2359 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002360 for (const auto &Lock : ExclusiveLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002361 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2362 Lock, LK_Exclusive, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002363 for (const auto &Lock : SharedLocksAcquired)
Ed Schoutenca988742014-09-03 06:00:11 +00002364 ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
2365 Lock, LK_Shared, D->getLocation()));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002366 for (const auto &Lock : LocksReleased)
2367 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002368
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002369 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002370 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002371 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002372 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002373 LEK_NotLockedAtEndOfFunction,
2374 false);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002375
2376 Handler.leaveFunction(CurrentFunction);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002377}
2378
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002379
2380/// \brief Check a function's CFG for thread-safety violations.
2381///
2382/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2383/// at the end of each block, and issue warnings for thread safety violations.
2384/// Each block in the CFG is traversed exactly once.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002385void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2386 ThreadSafetyHandler &Handler,
2387 BeforeSet **BSet) {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002388 if (!*BSet)
2389 *BSet = new BeforeSet;
2390 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002391 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002392}
2393
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002394void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002395
Caitlin Sadowski33208342011-09-09 16:11:56 +00002396/// \brief Helper function that returns a LockKind required for the given level
2397/// of access.
Benjamin Kramer66a97ee2015-03-09 14:19:54 +00002398LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00002399 switch (AK) {
2400 case AK_Read :
2401 return LK_Shared;
2402 case AK_Written :
2403 return LK_Exclusive;
2404 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002405 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002406}