blob: f4f174d59bc71942bad9f22f9375e5202ac65ef4 [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"
Aaron Ballman7c192b42014-05-09 18:26:23 +000025#include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000026#include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
DeLesley Hutchins7e615c22014-04-09 22:39:43 +000027#include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
DeLesley Hutchinsb2213912014-04-07 18:09:54 +000028#include "clang/Analysis/Analyses/ThreadSafetyCommon.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>
47
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000048
49namespace clang {
50namespace threadSafety {
Caitlin Sadowski33208342011-09-09 16:11:56 +000051
Caitlin Sadowski5b34a2f2011-09-14 20:05:09 +000052// Key method definition
53ThreadSafetyHandler::~ThreadSafetyHandler() {}
54
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000055class TILPrinter :
56 public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000057
58
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000059/// Issue a warning about an invalid lock expression
60static void warnInvalidLock(ThreadSafetyHandler &Handler,
61 const Expr *MutexExp, const NamedDecl *D,
62 const Expr *DeclExp, StringRef Kind) {
63 SourceLocation Loc;
64 if (DeclExp)
65 Loc = DeclExp->getExprLoc();
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000066
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000067 // FIXME: add a note about the attribute location in MutexExp or D
68 if (Loc.isValid())
69 Handler.handleInvalidLockExp(Kind, Loc);
70}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000071
Caitlin Sadowski33208342011-09-09 16:11:56 +000072
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000073// Various helper functions on til::SExpr
74namespace sx {
DeLesley Hutchins49979f22012-06-25 18:33:18 +000075
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000076bool isUniversal(const til::SExpr *E) {
77 return isa<til::Wildcard>(E);
78}
DeLesley Hutchins49979f22012-06-25 18:33:18 +000079
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000080bool equals(const til::SExpr *E1, const til::SExpr *E2) {
81 return til::EqualsComparator::compareExprs(E1, E2);
82}
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +000083
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000084const til::SExpr* ignorePtrCasts(const til::SExpr *E) {
85 if (auto *CE = dyn_cast<til::Cast>(E)) {
86 if (CE->castOpcode() == til::CAST_objToPtr)
87 return CE->expr();
Aaron Ballman19842c42014-03-06 19:25:11 +000088 }
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000089 return E;
90}
Aaron Ballman19842c42014-03-06 19:25:11 +000091
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +000092bool matches(const til::SExpr *E1, const til::SExpr *E2) {
93 // We treat a top-level wildcard as the "univsersal" lock.
94 // It matches everything for the purpose of checking locks, but not
95 // for unlocking them.
96 if (isa<til::Wildcard>(E1))
97 return isa<til::Wildcard>(E2);
98 if (isa<til::Wildcard>(E2))
99 return isa<til::Wildcard>(E1);
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000100
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000101 return til::MatchComparator::compareExprs(E1, E2);
102}
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000103
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000104bool partiallyMatches(const til::SExpr *E1, const til::SExpr *E2) {
105 auto *PE1 = dyn_cast_or_null<til::Project>(E1);
106 if (!PE1)
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000107 return false;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000108 auto *PE2 = dyn_cast_or_null<til::Project>(E2);
109 if (!PE2)
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000110 return false;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000111 return PE1->clangDecl() == PE2->clangDecl();
112}
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000113
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000114std::string toString(const til::SExpr *E) {
115 std::stringstream ss;
116 til::StdPrinter::print(E, ss);
117 return ss.str();
118}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000119
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000120bool shouldIgnore(const til::SExpr *E) {
121 if (!E)
122 return true;
123 // Trap mutex expressions like nullptr, or 0.
124 // Any literal value is nonsense.
125 if (isa<til::Literal>(E))
126 return true;
127 return false;
128}
DeLesley Hutchins0c90c2b2012-08-10 20:29:46 +0000129
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000130} // end namespace sx
131
132
Caitlin Sadowski33208342011-09-09 16:11:56 +0000133
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000134/// \brief A short list of SExprs
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000135class MutexIDList : public SmallVector<const til::SExpr*, 3> {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000136public:
Aaron Ballmancea26092014-03-06 19:10:16 +0000137 /// \brief Push M onto list, but discard duplicates.
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000138 void push_back_nodup(const til::SExpr *E) {
139 iterator It = std::find_if(begin(), end(), [=](const til::SExpr *E2) {
140 return sx::equals(E, E2);
141 });
142 if (It == end())
143 push_back(E);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000144 }
145};
146
Caitlin Sadowski33208342011-09-09 16:11:56 +0000147/// \brief This is a helper class that stores info about the most recent
148/// accquire of a Lock.
149///
150/// The main body of the analysis maps MutexIDs to LockDatas.
151struct LockData {
152 SourceLocation AcquireLoc;
153
154 /// \brief LKind stores whether a lock is held shared or exclusively.
155 /// Note that this analysis does not currently support either re-entrant
156 /// locking or lock "upgrading" and "downgrading" between exclusive and
157 /// shared.
158 ///
159 /// FIXME: add support for re-entrant locking and lock up/downgrading
160 LockKind LKind;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000161 bool Asserted; // for asserted locks
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000162 bool Managed; // for ScopedLockable objects
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000163 const til::SExpr* UnderlyingMutex; // for ScopedLockable objects
Caitlin Sadowski33208342011-09-09 16:11:56 +0000164
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000165 LockData(SourceLocation AcquireLoc, LockKind LKind, bool M=false,
166 bool Asrt=false)
167 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(Asrt), Managed(M),
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000168 UnderlyingMutex(nullptr)
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +0000169 {}
170
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000171 LockData(SourceLocation AcquireLoc, LockKind LKind, const til::SExpr *Mu)
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000172 : AcquireLoc(AcquireLoc), LKind(LKind), Asserted(false), Managed(false),
DeLesley Hutchinsd162c912012-06-28 22:42:48 +0000173 UnderlyingMutex(Mu)
174 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000175
176 bool operator==(const LockData &other) const {
177 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
178 }
179
180 bool operator!=(const LockData &other) const {
181 return !(*this == other);
182 }
183
184 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000185 ID.AddInteger(AcquireLoc.getRawEncoding());
186 ID.AddInteger(LKind);
187 }
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000188
189 bool isAtLeast(LockKind LK) {
190 return (LK == LK_Shared) || (LKind == LK_Exclusive);
191 }
Caitlin Sadowski33208342011-09-09 16:11:56 +0000192};
193
DeLesley Hutchins3d312b12011-10-21 16:14:33 +0000194
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000195/// \brief A FactEntry stores a single fact that is known at a particular point
196/// in the program execution. Currently, this is information regarding a lock
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000197/// that is held at that point.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000198struct FactEntry {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000199 const til::SExpr *MutID;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000200 LockData LDat;
201
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000202 FactEntry(const til::SExpr* M, const LockData& L)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000203 : MutID(M), LDat(L)
204 { }
205};
206
207
208typedef unsigned short FactID;
209
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000210/// \brief FactManager manages the memory for all facts that are created during
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000211/// the analysis of a single routine.
212class FactManager {
213private:
214 std::vector<FactEntry> Facts;
215
216public:
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000217 FactID newLock(const til::SExpr *M, const LockData& L) {
218 Facts.push_back(FactEntry(M, L));
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000219 return static_cast<unsigned short>(Facts.size() - 1);
220 }
221
222 const FactEntry& operator[](FactID F) const { return Facts[F]; }
223 FactEntry& operator[](FactID F) { return Facts[F]; }
224};
225
226
227/// \brief A FactSet is the set of facts that are known to be true at a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000228/// particular program point. FactSets must be small, because they are
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000229/// frequently copied, and are thus implemented as a set of indices into a
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +0000230/// table maintained by a FactManager. A typical FactSet only holds 1 or 2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000231/// locks, so we can get away with doing a linear search for lookup. Note
232/// that a hashtable or map is inappropriate in this case, because lookups
233/// may involve partial pattern matches, rather than exact matches.
234class FactSet {
235private:
236 typedef SmallVector<FactID, 4> FactVec;
237
238 FactVec FactIDs;
239
240public:
241 typedef FactVec::iterator iterator;
242 typedef FactVec::const_iterator const_iterator;
243
244 iterator begin() { return FactIDs.begin(); }
245 const_iterator begin() const { return FactIDs.begin(); }
246
247 iterator end() { return FactIDs.end(); }
248 const_iterator end() const { return FactIDs.end(); }
249
250 bool isEmpty() const { return FactIDs.size() == 0; }
251
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000252 FactID addLock(FactManager& FM, const til::SExpr *M, const LockData& L) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000253 FactID F = FM.newLock(M, L);
254 FactIDs.push_back(F);
255 return F;
256 }
257
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000258 bool removeLock(FactManager& FM, const til::SExpr *M) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000259 unsigned n = FactIDs.size();
260 if (n == 0)
261 return false;
262
263 for (unsigned i = 0; i < n-1; ++i) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000264 if (sx::matches(FM[FactIDs[i]].MutID, M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000265 FactIDs[i] = FactIDs[n-1];
266 FactIDs.pop_back();
267 return true;
268 }
269 }
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000270 if (sx::matches(FM[FactIDs[n-1]].MutID, M)) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000271 FactIDs.pop_back();
272 return true;
273 }
274 return false;
275 }
276
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000277 iterator findLockIter(FactManager &FM, const til::SExpr *M) {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000278 return std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000279 return sx::matches(FM[ID].MutID, M);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000280 });
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +0000281 }
282
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000283 LockData *findLock(FactManager &FM, const til::SExpr *M) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000284 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000285 return sx::matches(FM[ID].MutID, M);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000286 });
287
288 return I != end() ? &FM[*I].LDat : nullptr;
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +0000289 }
290
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000291 LockData *findLockUniv(FactManager &FM, const til::SExpr *M) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000292 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000293 const til::SExpr *E = FM[ID].MutID;
294 return sx::isUniversal(E) || sx::matches(E, M);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000295 });
296
297 return I != end() ? &FM[*I].LDat : nullptr;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000298 }
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000299
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000300 FactEntry *findPartialMatch(FactManager &FM, const til::SExpr *M) const {
Aaron Ballman59a72b92014-05-14 18:32:59 +0000301 auto I = std::find_if(begin(), end(), [&](FactID ID) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000302 return sx::partiallyMatches(FM[ID].MutID, M);
Aaron Ballman42f9a8a2014-05-14 15:01:43 +0000303 });
304
305 return I != end() ? &FM[*I] : nullptr;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +0000306 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000307};
308
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000309
DeLesley Hutchins9b1d72f2012-08-10 20:19:55 +0000310/// A Lockset maps each SExpr (defined above) to information about how it has
Caitlin Sadowski33208342011-09-09 16:11:56 +0000311/// been locked.
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000312typedef llvm::ImmutableMap<til::SExpr*, LockData> Lockset;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000313typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000314
315class LocalVariableMap;
316
Richard Smith92286672012-02-03 04:45:26 +0000317/// A side (entry or exit) of a CFG node.
318enum CFGBlockSide { CBS_Entry, CBS_Exit };
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000319
320/// CFGBlockInfo is a struct which contains all the information that is
321/// maintained for each block in the CFG. See LocalVariableMap for more
322/// information about the contexts.
323struct CFGBlockInfo {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000324 FactSet EntrySet; // Lockset held at entry to block
325 FactSet ExitSet; // Lockset held at exit from block
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000326 LocalVarContext EntryContext; // Context held at entry to block
327 LocalVarContext ExitContext; // Context held at exit from block
Richard Smith92286672012-02-03 04:45:26 +0000328 SourceLocation EntryLoc; // Location of first statement in block
329 SourceLocation ExitLoc; // Location of last statement in block.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000330 unsigned EntryIndex; // Used to replay contexts later
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000331 bool Reachable; // Is this block reachable?
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000332
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000333 const FactSet &getSet(CFGBlockSide Side) const {
Richard Smith92286672012-02-03 04:45:26 +0000334 return Side == CBS_Entry ? EntrySet : ExitSet;
335 }
336 SourceLocation getLocation(CFGBlockSide Side) const {
337 return Side == CBS_Entry ? EntryLoc : ExitLoc;
338 }
339
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000340private:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000341 CFGBlockInfo(LocalVarContext EmptyCtx)
DeLesley Hutchins10958ca2012-09-21 17:57:00 +0000342 : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000343 { }
344
345public:
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000346 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000347};
348
349
350
351// A LocalVariableMap maintains a map from local variables to their currently
352// valid definitions. It provides SSA-like functionality when traversing the
353// CFG. Like SSA, each definition or assignment to a variable is assigned a
354// unique name (an integer), which acts as the SSA name for that definition.
355// The total set of names is shared among all CFG basic blocks.
356// Unlike SSA, we do not rewrite expressions to replace local variables declrefs
357// with their SSA-names. Instead, we compute a Context for each point in the
358// code, which maps local variables to the appropriate SSA-name. This map
359// changes with each assignment.
360//
361// The map is computed in a single pass over the CFG. Subsequent analyses can
362// then query the map to find the appropriate Context for a statement, and use
363// that Context to look up the definitions of variables.
364class LocalVariableMap {
365public:
366 typedef LocalVarContext Context;
367
368 /// A VarDefinition consists of an expression, representing the value of the
369 /// variable, along with the context in which that expression should be
370 /// interpreted. A reference VarDefinition does not itself contain this
371 /// information, but instead contains a pointer to a previous VarDefinition.
372 struct VarDefinition {
373 public:
374 friend class LocalVariableMap;
375
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000376 const NamedDecl *Dec; // The original declaration for this variable.
377 const Expr *Exp; // The expression for this variable, OR
378 unsigned Ref; // Reference to another VarDefinition
379 Context Ctx; // The map with which Exp should be interpreted.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000380
381 bool isReference() { return !Exp; }
382
383 private:
384 // Create ordinary variable definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000385 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000386 : Dec(D), Exp(E), Ref(0), Ctx(C)
387 { }
388
389 // Create reference to previous definition
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000390 VarDefinition(const NamedDecl *D, unsigned R, Context C)
Craig Topper25542942014-05-20 04:30:07 +0000391 : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000392 { }
393 };
394
395private:
396 Context::Factory ContextFactory;
397 std::vector<VarDefinition> VarDefinitions;
398 std::vector<unsigned> CtxIndices;
399 std::vector<std::pair<Stmt*, Context> > SavedContexts;
400
401public:
402 LocalVariableMap() {
403 // index 0 is a placeholder for undefined variables (aka phi-nodes).
Craig Topper25542942014-05-20 04:30:07 +0000404 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000405 }
406
407 /// Look up a definition, within the given context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000408 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000409 const unsigned *i = Ctx.lookup(D);
410 if (!i)
Craig Topper25542942014-05-20 04:30:07 +0000411 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000412 assert(*i < VarDefinitions.size());
413 return &VarDefinitions[*i];
414 }
415
416 /// Look up the definition for D within the given context. Returns
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000417 /// NULL if the expression is not statically known. If successful, also
418 /// modifies Ctx to hold the context of the return Expr.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000419 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000420 const unsigned *P = Ctx.lookup(D);
421 if (!P)
Craig Topper25542942014-05-20 04:30:07 +0000422 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000423
424 unsigned i = *P;
425 while (i > 0) {
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000426 if (VarDefinitions[i].Exp) {
427 Ctx = VarDefinitions[i].Ctx;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000428 return VarDefinitions[i].Exp;
DeLesley Hutchins9d530332012-01-06 19:16:50 +0000429 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000430 i = VarDefinitions[i].Ref;
431 }
Craig Topper25542942014-05-20 04:30:07 +0000432 return nullptr;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000433 }
434
435 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
436
437 /// Return the next context after processing S. This function is used by
438 /// clients of the class to get the appropriate context when traversing the
439 /// CFG. It must be called for every assignment or DeclStmt.
440 Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
441 if (SavedContexts[CtxIndex+1].first == S) {
442 CtxIndex++;
443 Context Result = SavedContexts[CtxIndex].second;
444 return Result;
445 }
446 return C;
447 }
448
449 void dumpVarDefinitionName(unsigned i) {
450 if (i == 0) {
451 llvm::errs() << "Undefined";
452 return;
453 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000454 const NamedDecl *Dec = VarDefinitions[i].Dec;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000455 if (!Dec) {
456 llvm::errs() << "<<NULL>>";
457 return;
458 }
459 Dec->printName(llvm::errs());
Roman Divackye6377112012-09-06 15:59:27 +0000460 llvm::errs() << "." << i << " " << ((const void*) Dec);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000461 }
462
463 /// Dumps an ASCII representation of the variable map to llvm::errs()
464 void dump() {
465 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000466 const Expr *Exp = VarDefinitions[i].Exp;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000467 unsigned Ref = VarDefinitions[i].Ref;
468
469 dumpVarDefinitionName(i);
470 llvm::errs() << " = ";
471 if (Exp) Exp->dump();
472 else {
473 dumpVarDefinitionName(Ref);
474 llvm::errs() << "\n";
475 }
476 }
477 }
478
479 /// Dumps an ASCII representation of a Context to llvm::errs()
480 void dumpContext(Context C) {
481 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000482 const NamedDecl *D = I.getKey();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000483 D->printName(llvm::errs());
484 const unsigned *i = C.lookup(D);
485 llvm::errs() << " -> ";
486 dumpVarDefinitionName(*i);
487 llvm::errs() << "\n";
488 }
489 }
490
491 /// Builds the variable map.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000492 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
493 std::vector<CFGBlockInfo> &BlockInfo);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000494
495protected:
496 // Get the current context index
497 unsigned getContextIndex() { return SavedContexts.size()-1; }
498
499 // Save the current context for later replay
500 void saveContext(Stmt *S, Context C) {
501 SavedContexts.push_back(std::make_pair(S,C));
502 }
503
504 // Adds a new definition to the given context, and returns a new context.
505 // This method should be called when declaring a new variable.
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000506 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000507 assert(!Ctx.contains(D));
508 unsigned newID = VarDefinitions.size();
509 Context NewCtx = ContextFactory.add(Ctx, D, newID);
510 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
511 return NewCtx;
512 }
513
514 // Add a new reference to an existing definition.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000515 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000516 unsigned newID = VarDefinitions.size();
517 Context NewCtx = ContextFactory.add(Ctx, D, newID);
518 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
519 return NewCtx;
520 }
521
522 // Updates a definition only if that definition is already in the map.
523 // This method should be called when assigning to an existing variable.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000524 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000525 if (Ctx.contains(D)) {
526 unsigned newID = VarDefinitions.size();
527 Context NewCtx = ContextFactory.remove(Ctx, D);
528 NewCtx = ContextFactory.add(NewCtx, D, newID);
529 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
530 return NewCtx;
531 }
532 return Ctx;
533 }
534
535 // Removes a definition from the context, but keeps the variable name
536 // as a valid variable. The index 0 is a placeholder for cleared definitions.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000537 Context clearDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000538 Context NewCtx = Ctx;
539 if (NewCtx.contains(D)) {
540 NewCtx = ContextFactory.remove(NewCtx, D);
541 NewCtx = ContextFactory.add(NewCtx, D, 0);
542 }
543 return NewCtx;
544 }
545
546 // Remove a definition entirely frmo the context.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000547 Context removeDefinition(const NamedDecl *D, Context Ctx) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000548 Context NewCtx = Ctx;
549 if (NewCtx.contains(D)) {
550 NewCtx = ContextFactory.remove(NewCtx, D);
551 }
552 return NewCtx;
553 }
554
555 Context intersectContexts(Context C1, Context C2);
556 Context createReferenceContext(Context C);
557 void intersectBackEdge(Context C1, Context C2);
558
559 friend class VarMapBuilder;
560};
561
562
563// This has to be defined after LocalVariableMap.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000564CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
565 return CFGBlockInfo(M.getEmptyContext());
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000566}
567
568
569/// Visitor which builds a LocalVariableMap
570class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
571public:
572 LocalVariableMap* VMap;
573 LocalVariableMap::Context Ctx;
574
575 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
576 : VMap(VM), Ctx(C) {}
577
578 void VisitDeclStmt(DeclStmt *S);
579 void VisitBinaryOperator(BinaryOperator *BO);
580};
581
582
583// Add new local variables to the variable map
584void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
585 bool modifiedCtx = false;
586 DeclGroupRef DGrp = S->getDeclGroup();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000587 for (const auto *D : DGrp) {
588 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
589 const Expr *E = VD->getInit();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000590
591 // Add local variables with trivial type to the variable map
592 QualType T = VD->getType();
593 if (T.isTrivialType(VD->getASTContext())) {
594 Ctx = VMap->addDefinition(VD, E, Ctx);
595 modifiedCtx = true;
596 }
597 }
598 }
599 if (modifiedCtx)
600 VMap->saveContext(S, Ctx);
601}
602
603// Update local variable definitions in variable map
604void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
605 if (!BO->isAssignmentOp())
606 return;
607
608 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
609
610 // Update the variable map and current context.
611 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
612 ValueDecl *VDec = DRE->getDecl();
613 if (Ctx.lookup(VDec)) {
614 if (BO->getOpcode() == BO_Assign)
615 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
616 else
617 // FIXME -- handle compound assignment operators
618 Ctx = VMap->clearDefinition(VDec, Ctx);
619 VMap->saveContext(BO, Ctx);
620 }
621 }
622}
623
624
625// Computes the intersection of two contexts. The intersection is the
626// set of variables which have the same definition in both contexts;
627// variables with different definitions are discarded.
628LocalVariableMap::Context
629LocalVariableMap::intersectContexts(Context C1, Context C2) {
630 Context Result = C1;
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000631 for (const auto &P : C1) {
632 const NamedDecl *Dec = P.first;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000633 const unsigned *i2 = C2.lookup(Dec);
634 if (!i2) // variable doesn't exist on second path
635 Result = removeDefinition(Dec, Result);
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000636 else if (*i2 != P.second) // variable exists, but has different definition
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000637 Result = clearDefinition(Dec, Result);
638 }
639 return Result;
640}
641
642// For every variable in C, create a new variable that refers to the
643// definition in C. Return a new context that contains these new variables.
644// (We use this for a naive implementation of SSA on loop back-edges.)
645LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
646 Context Result = getEmptyContext();
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000647 for (const auto &P : C)
648 Result = addReference(P.first, P.second, Result);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000649 return Result;
650}
651
652// This routine also takes the intersection of C1 and C2, but it does so by
653// altering the VarDefinitions. C1 must be the result of an earlier call to
654// createReferenceContext.
655void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000656 for (const auto &P : C1) {
657 unsigned i1 = P.second;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000658 VarDefinition *VDef = &VarDefinitions[i1];
659 assert(VDef->isReference());
660
Aaron Ballman9ee54d12014-05-14 20:42:13 +0000661 const unsigned *i2 = C2.lookup(P.first);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000662 if (!i2 || (*i2 != i1))
663 VDef->Ref = 0; // Mark this variable as undefined
664 }
665}
666
667
668// Traverse the CFG in topological order, so all predecessors of a block
669// (excluding back-edges) are visited before the block itself. At
670// each point in the code, we calculate a Context, which holds the set of
671// variable definitions which are visible at that point in execution.
672// Visible variables are mapped to their definitions using an array that
673// contains all definitions.
674//
675// At join points in the CFG, the set is computed as the intersection of
676// the incoming sets along each edge, E.g.
677//
678// { Context | VarDefinitions }
679// int x = 0; { x -> x1 | x1 = 0 }
680// int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
681// if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
682// else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
683// ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
684//
685// This is essentially a simpler and more naive version of the standard SSA
686// algorithm. Those definitions that remain in the intersection are from blocks
687// that strictly dominate the current block. We do not bother to insert proper
688// phi nodes, because they are not used in our analysis; instead, wherever
689// a phi node would be required, we simply remove that definition from the
690// context (E.g. x above).
691//
692// The initial traversal does not capture back-edges, so those need to be
693// handled on a separate pass. Whenever the first pass encounters an
694// incoming back edge, it duplicates the context, creating new definitions
695// that refer back to the originals. (These correspond to places where SSA
696// might have to insert a phi node.) On the second pass, these definitions are
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000697// set to NULL if the variable has changed on the back-edge (i.e. a phi
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000698// node was actually required.) E.g.
699//
700// { Context | VarDefinitions }
701// int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
702// while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
703// x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
704// ... { y -> y1 | x3 = 2, x2 = 1, ... }
705//
706void LocalVariableMap::traverseCFG(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000707 const PostOrderCFGView *SortedGraph,
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000708 std::vector<CFGBlockInfo> &BlockInfo) {
709 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
710
711 CtxIndices.resize(CFGraph->getNumBlockIDs());
712
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000713 for (const auto *CurrBlock : *SortedGraph) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000714 int CurrBlockID = CurrBlock->getBlockID();
715 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
716
717 VisitedBlocks.insert(CurrBlock);
718
719 // Calculate the entry context for the current block
720 bool HasBackEdges = false;
721 bool CtxInit = true;
722 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
723 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
724 // if *PI -> CurrBlock is a back edge, so skip it
Craig Topper25542942014-05-20 04:30:07 +0000725 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000726 HasBackEdges = true;
727 continue;
728 }
729
730 int PrevBlockID = (*PI)->getBlockID();
731 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
732
733 if (CtxInit) {
734 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
735 CtxInit = false;
736 }
737 else {
738 CurrBlockInfo->EntryContext =
739 intersectContexts(CurrBlockInfo->EntryContext,
740 PrevBlockInfo->ExitContext);
741 }
742 }
743
744 // Duplicate the context if we have back-edges, so we can call
745 // intersectBackEdges later.
746 if (HasBackEdges)
747 CurrBlockInfo->EntryContext =
748 createReferenceContext(CurrBlockInfo->EntryContext);
749
750 // Create a starting context index for the current block
Craig Topper25542942014-05-20 04:30:07 +0000751 saveContext(nullptr, CurrBlockInfo->EntryContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000752 CurrBlockInfo->EntryIndex = getContextIndex();
753
754 // Visit all the statements in the basic block.
755 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
756 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
757 BE = CurrBlock->end(); BI != BE; ++BI) {
758 switch (BI->getKind()) {
759 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +0000760 CFGStmt CS = BI->castAs<CFGStmt>();
761 VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000762 break;
763 }
764 default:
765 break;
766 }
767 }
768 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
769
770 // Mark variables on back edges as "unknown" if they've been changed.
771 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
772 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
773 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +0000774 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000775 continue;
776
777 CFGBlock *FirstLoopBlock = *SI;
778 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
779 Context LoopEnd = CurrBlockInfo->ExitContext;
780 intersectBackEdge(LoopBegin, LoopEnd);
781 }
782 }
783
784 // Put an extra entry at the end of the indexed context array
785 unsigned exitID = CFGraph->getExit().getBlockID();
Craig Topper25542942014-05-20 04:30:07 +0000786 saveContext(nullptr, BlockInfo[exitID].ExitContext);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000787}
788
Richard Smith92286672012-02-03 04:45:26 +0000789/// Find the appropriate source locations to use when producing diagnostics for
790/// each block in the CFG.
791static void findBlockLocations(CFG *CFGraph,
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000792 const PostOrderCFGView *SortedGraph,
Richard Smith92286672012-02-03 04:45:26 +0000793 std::vector<CFGBlockInfo> &BlockInfo) {
Aaron Ballmane80bfcd2014-04-17 21:44:08 +0000794 for (const auto *CurrBlock : *SortedGraph) {
Richard Smith92286672012-02-03 04:45:26 +0000795 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
796
797 // Find the source location of the last statement in the block, if the
798 // block is not empty.
799 if (const Stmt *S = CurrBlock->getTerminator()) {
800 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
801 } else {
802 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
803 BE = CurrBlock->rend(); BI != BE; ++BI) {
804 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000805 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
806 CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000807 break;
808 }
809 }
810 }
811
812 if (!CurrBlockInfo->ExitLoc.isInvalid()) {
813 // This block contains at least one statement. Find the source location
814 // of the first statement in the block.
815 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
816 BE = CurrBlock->end(); BI != BE; ++BI) {
817 // FIXME: Handle other CFGElement kinds.
David Blaikie00be69a2013-02-23 00:29:34 +0000818 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
819 CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
Richard Smith92286672012-02-03 04:45:26 +0000820 break;
821 }
822 }
823 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
824 CurrBlock != &CFGraph->getExit()) {
825 // The block is empty, and has a single predecessor. Use its exit
826 // location.
827 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
828 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
829 }
830 }
831}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000832
833/// \brief Class which implements the core thread safety analysis routines.
834class ThreadSafetyAnalyzer {
835 friend class BuildLockset;
836
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000837 llvm::BumpPtrAllocator Bpa;
838 threadSafety::til::MemRegionRef Arena;
839 threadSafety::SExprBuilder SxBuilder;
840
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000841 ThreadSafetyHandler &Handler;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000842 LocalVariableMap LocalVarMap;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000843 FactManager FactMan;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000844 std::vector<CFGBlockInfo> BlockInfo;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000845
846public:
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000847 ThreadSafetyAnalyzer(ThreadSafetyHandler &H)
848 : Arena(&Bpa), SxBuilder(Arena), Handler(H) {}
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000849
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000850 void addLock(FactSet &FSet, const til::SExpr *Mutex, const LockData &LDat,
Aaron Ballmane0449042014-04-01 21:43:23 +0000851 StringRef DiagKind);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000852 void removeLock(FactSet &FSet, const til::SExpr *Mutex,
853 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
854 StringRef DiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000855
856 template <typename AttrType>
857 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
Craig Topper25542942014-05-20 04:30:07 +0000858 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000859
860 template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +0000861 void getMutexIDs(MutexIDList &Mtxs, AttrType *Attr, Expr *Exp,
862 const NamedDecl *D,
863 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
864 Expr *BrE, bool Neg);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000865
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000866 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
867 bool &Negate);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000868
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000869 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
870 const CFGBlock* PredBlock,
871 const CFGBlock *CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +0000872
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000873 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
874 SourceLocation JoinLoc,
875 LockErrorKind LEK1, LockErrorKind LEK2,
876 bool Modify=true);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000877
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000878 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
879 SourceLocation JoinLoc, LockErrorKind LEK1,
880 bool Modify=true) {
881 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +0000882 }
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000883
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +0000884 void runAnalysis(AnalysisDeclContext &AC);
885};
886
Aaron Ballmane0449042014-04-01 21:43:23 +0000887/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
888static const ValueDecl *getValueDecl(const Expr *Exp) {
889 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
890 return getValueDecl(CE->getSubExpr());
891
892 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
893 return DR->getDecl();
894
895 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
896 return ME->getMemberDecl();
897
898 return nullptr;
899}
900
901template <typename Ty>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000902class has_arg_iterator_range {
Aaron Ballmane0449042014-04-01 21:43:23 +0000903 typedef char yes[1];
904 typedef char no[2];
905
906 template <typename Inner>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000907 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
Aaron Ballmane0449042014-04-01 21:43:23 +0000908
909 template <typename>
910 static no& test(...);
911
912public:
913 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
914};
915
916static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
917 return A->getName();
918}
919
920static StringRef ClassifyDiagnostic(QualType VDT) {
921 // We need to look at the declaration of the type of the value to determine
922 // which it is. The type should either be a record or a typedef, or a pointer
923 // or reference thereof.
924 if (const auto *RT = VDT->getAs<RecordType>()) {
925 if (const auto *RD = RT->getDecl())
926 if (const auto *CA = RD->getAttr<CapabilityAttr>())
927 return ClassifyDiagnostic(CA);
928 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
929 if (const auto *TD = TT->getDecl())
930 if (const auto *CA = TD->getAttr<CapabilityAttr>())
931 return ClassifyDiagnostic(CA);
932 } else if (VDT->isPointerType() || VDT->isReferenceType())
933 return ClassifyDiagnostic(VDT->getPointeeType());
934
935 return "mutex";
936}
937
938static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
939 assert(VD && "No ValueDecl passed");
940
941 // The ValueDecl is the declaration of a mutex or role (hopefully).
942 return ClassifyDiagnostic(VD->getType());
943}
944
945template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000946static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +0000947 StringRef>::type
948ClassifyDiagnostic(const AttrTy *A) {
949 if (const ValueDecl *VD = getValueDecl(A->getArg()))
950 return ClassifyDiagnostic(VD);
951 return "mutex";
952}
953
954template <typename AttrTy>
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000955static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
Aaron Ballmane0449042014-04-01 21:43:23 +0000956 StringRef>::type
957ClassifyDiagnostic(const AttrTy *A) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000958 for (const auto *Arg : A->args()) {
959 if (const ValueDecl *VD = getValueDecl(Arg))
Aaron Ballmane0449042014-04-01 21:43:23 +0000960 return ClassifyDiagnostic(VD);
961 }
962 return "mutex";
963}
Caitlin Sadowski33208342011-09-09 16:11:56 +0000964
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000965/// \brief Add a new lock to the lockset, warning if the lock is already there.
966/// \param Mutex -- the Mutex expression for the lock
967/// \param LDat -- the LockData for the lock
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000968void ThreadSafetyAnalyzer::addLock(FactSet &FSet, const til::SExpr *Mutex,
Aaron Ballmane0449042014-04-01 21:43:23 +0000969 const LockData &LDat, StringRef DiagKind) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000970 // FIXME: deal with acquired before/after annotations.
971 // FIXME: Don't always warn when we have support for reentrant locks.
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000972 if (sx::shouldIgnore(Mutex))
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000973 return;
974
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000975 if (FSet.findLock(FactMan, Mutex)) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +0000976 if (!LDat.Asserted)
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000977 Handler.handleDoubleLock(DiagKind, sx::toString(Mutex), LDat.AcquireLoc);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000978 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000979 FSet.addLock(FactMan, Mutex, LDat);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000980 }
981}
982
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000983
984/// \brief Remove a lock from the lockset, warning if the lock is not there.
Ted Kremenek78094ca2012-08-22 23:50:41 +0000985/// \param Mutex The lock expression corresponding to the lock to be removed
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000986/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000987void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const til::SExpr *Mutex,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000988 SourceLocation UnlockLoc,
Aaron Ballmane0449042014-04-01 21:43:23 +0000989 bool FullyRemove, LockKind ReceivedKind,
990 StringRef DiagKind) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000991 if (sx::shouldIgnore(Mutex))
DeLesley Hutchins3c3d57b2012-08-31 21:57:32 +0000992 return;
993
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000994 const LockData *LDat = FSet.findLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000995 if (!LDat) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +0000996 Handler.handleUnmatchedUnlock(DiagKind, sx::toString(Mutex), UnlockLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000997 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +0000998 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +0000999
Aaron Ballmandf115d92014-03-21 14:48:48 +00001000 // Generic lock removal doesn't care about lock kind mismatches, but
1001 // otherwise diagnose when the lock kinds are mismatched.
1002 if (ReceivedKind != LK_Generic && LDat->LKind != ReceivedKind) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001003 Handler.handleIncorrectUnlockKind(DiagKind, sx::toString(Mutex),
1004 LDat->LKind, ReceivedKind, UnlockLoc);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001005 return;
1006 }
1007
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001008 if (LDat->UnderlyingMutex) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001009 // This is scoped lockable object, which manages the real mutex.
1010 if (FullyRemove) {
1011 // We're destroying the managing object.
1012 // Remove the underlying mutex if it exists; but don't warn.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001013 if (FSet.findLock(FactMan, LDat->UnderlyingMutex))
1014 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001015 } else {
1016 // We're releasing the underlying mutex, but not destroying the
1017 // managing object. Warn on dual release.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001018 if (!FSet.findLock(FactMan, LDat->UnderlyingMutex)) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001019 Handler.handleUnmatchedUnlock(
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001020 DiagKind, sx::toString(LDat->UnderlyingMutex), UnlockLoc);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001021 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001022 FSet.removeLock(FactMan, LDat->UnderlyingMutex);
1023 return;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001024 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001025 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001026 FSet.removeLock(FactMan, Mutex);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001027}
1028
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001029
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001030/// \brief Extract the list of mutexIDs from the attribute on an expression,
1031/// and push them onto Mtxs, discarding any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001032template <typename AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001033void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
DeLesley Hutchins1fe88562012-10-05 22:38:19 +00001034 Expr *Exp, const NamedDecl *D,
1035 VarDecl *SelfDecl) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001036 if (Attr->args_size() == 0) {
1037 // The mutex held is the "this" object.
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001038 til::SExpr *Mu = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1039 if (Mu && isa<til::Undefined>(Mu)) {
1040 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1041 return;
1042 }
1043 //else
1044 if (Mu)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001045 Mtxs.push_back_nodup(Mu);
1046 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001047 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001048
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001049 for (const auto *Arg : Attr->args()) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001050 til::SExpr *Mu = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1051 if (Mu && isa<til::Undefined>(Mu)) {
1052 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1053 return;
1054 }
1055 //else
1056 if (Mu)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001057 Mtxs.push_back_nodup(Mu);
1058 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001059}
1060
1061
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001062/// \brief Extract the list of mutexIDs from a trylock attribute. If the
1063/// trylock applies to the given edge, then push them onto Mtxs, discarding
1064/// any duplicates.
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001065template <class AttrType>
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001066void ThreadSafetyAnalyzer::getMutexIDs(MutexIDList &Mtxs, AttrType *Attr,
1067 Expr *Exp, const NamedDecl *D,
1068 const CFGBlock *PredBlock,
1069 const CFGBlock *CurrBlock,
1070 Expr *BrE, bool Neg) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001071 // Find out which branch has the lock
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001072 bool branch = false;
1073 if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001074 branch = BLE->getValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001075 else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001076 branch = ILE->getValue().getBoolValue();
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001077
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001078 int branchnum = branch ? 0 : 1;
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001079 if (Neg)
1080 branchnum = !branchnum;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001081
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001082 // If we've taken the trylock branch, then add the lock
1083 int i = 0;
1084 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1085 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
Aaron Ballman2f3fc6b2014-05-14 13:03:55 +00001086 if (*SI == CurrBlock && i == branchnum)
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001087 getMutexIDs(Mtxs, Attr, Exp, D);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001088 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001089}
1090
1091
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001092bool getStaticBooleanValue(Expr* E, bool& TCond) {
1093 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1094 TCond = false;
1095 return true;
1096 } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1097 TCond = BLE->getValue();
1098 return true;
1099 } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
1100 TCond = ILE->getValue().getBoolValue();
1101 return true;
1102 } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1103 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1104 }
1105 return false;
1106}
1107
1108
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001109// If Cond can be traced back to a function call, return the call expression.
1110// The negate variable should be called with false, and will be set to true
1111// if the function call is negated, e.g. if (!mu.tryLock(...))
1112const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1113 LocalVarContext C,
1114 bool &Negate) {
1115 if (!Cond)
Craig Topper25542942014-05-20 04:30:07 +00001116 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001117
1118 if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
1119 return CallExp;
1120 }
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001121 else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
1122 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1123 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001124 else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
1125 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1126 }
DeLesley Hutchins93b1b032012-09-05 20:01:16 +00001127 else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
1128 return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
1129 }
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001130 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1131 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1132 return getTrylockCallExpr(E, C, Negate);
1133 }
1134 else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
1135 if (UOP->getOpcode() == UO_LNot) {
1136 Negate = !Negate;
1137 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1138 }
Craig Topper25542942014-05-20 04:30:07 +00001139 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001140 }
1141 else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
1142 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1143 if (BOP->getOpcode() == BO_NE)
1144 Negate = !Negate;
1145
1146 bool TCond = false;
1147 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1148 if (!TCond) Negate = !Negate;
1149 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1150 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001151 TCond = false;
1152 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001153 if (!TCond) Negate = !Negate;
1154 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1155 }
Craig Topper25542942014-05-20 04:30:07 +00001156 return nullptr;
DeLesley Hutchins868830f2012-07-10 21:47:55 +00001157 }
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001158 if (BOP->getOpcode() == BO_LAnd) {
1159 // LHS must have been evaluated in a different block.
1160 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1161 }
1162 if (BOP->getOpcode() == BO_LOr) {
1163 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1164 }
Craig Topper25542942014-05-20 04:30:07 +00001165 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001166 }
Craig Topper25542942014-05-20 04:30:07 +00001167 return nullptr;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001168}
1169
1170
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001171/// \brief Find the lockset that holds on the edge between PredBlock
1172/// and CurrBlock. The edge set is the exit set of PredBlock (passed
1173/// as the ExitSet parameter) plus any trylocks, which are conditionally held.
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001174void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1175 const FactSet &ExitSet,
1176 const CFGBlock *PredBlock,
1177 const CFGBlock *CurrBlock) {
1178 Result = ExitSet;
1179
DeLesley Hutchins9f5193c2013-08-15 23:06:33 +00001180 const Stmt *Cond = PredBlock->getTerminatorCondition();
1181 if (!Cond)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001182 return;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001183
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001184 bool Negate = false;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001185 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1186 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
Aaron Ballmane0449042014-04-01 21:43:23 +00001187 StringRef CapDiagKind = "mutex";
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001188
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001189 CallExpr *Exp =
1190 const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001191 if (!Exp)
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001192 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001193
1194 NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1195 if(!FunDecl || !FunDecl->hasAttrs())
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001196 return;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001197
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001198 MutexIDList ExclusiveLocksToAdd;
1199 MutexIDList SharedLocksToAdd;
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001200
1201 // If the condition is a call to a Trylock function, then grab the attributes
Aaron Ballman9ee54d12014-05-14 20:42:13 +00001202 for (auto *Attr : FunDecl->getAttrs()) {
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001203 switch (Attr->getKind()) {
1204 case attr::ExclusiveTrylockFunction: {
1205 ExclusiveTrylockFunctionAttr *A =
1206 cast<ExclusiveTrylockFunctionAttr>(Attr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001207 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1208 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001209 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001210 break;
1211 }
1212 case attr::SharedTrylockFunction: {
1213 SharedTrylockFunctionAttr *A =
1214 cast<SharedTrylockFunctionAttr>(Attr);
DeLesley Hutchinsfcb0ffa2012-09-20 23:14:43 +00001215 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001216 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
Aaron Ballmane0449042014-04-01 21:43:23 +00001217 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001218 break;
1219 }
1220 default:
1221 break;
1222 }
1223 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001224
1225 // Add and remove locks.
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001226 SourceLocation Loc = Exp->getExprLoc();
Aaron Ballmane0449042014-04-01 21:43:23 +00001227 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1228 addLock(Result, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
1229 CapDiagKind);
1230 for (const auto &SharedLockToAdd : SharedLocksToAdd)
1231 addLock(Result, SharedLockToAdd, LockData(Loc, LK_Shared), CapDiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001232}
1233
Caitlin Sadowski33208342011-09-09 16:11:56 +00001234/// \brief We use this class to visit different types of expressions in
1235/// CFGBlocks, and build up the lockset.
1236/// An expression may cause us to add or remove locks from the lockset, or else
1237/// output error messages related to missing locks.
1238/// FIXME: In future, we may be able to not inherit from a visitor.
1239class BuildLockset : public StmtVisitor<BuildLockset> {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001240 friend class ThreadSafetyAnalyzer;
1241
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001242 ThreadSafetyAnalyzer *Analyzer;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001243 FactSet FSet;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001244 LocalVariableMap::Context LVarCtx;
1245 unsigned CtxIndex;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001246
1247 // Helper functions
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001248
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001249 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
Aaron Ballmane0449042014-04-01 21:43:23 +00001250 Expr *MutexExp, ProtectedOperationKind POK,
1251 StringRef DiagKind);
1252 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1253 StringRef DiagKind);
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001254
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001255 void checkAccess(const Expr *Exp, AccessKind AK);
1256 void checkPtAccess(const Expr *Exp, AccessKind AK);
1257
Craig Topper25542942014-05-20 04:30:07 +00001258 void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001259
Caitlin Sadowski33208342011-09-09 16:11:56 +00001260public:
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001261 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001262 : StmtVisitor<BuildLockset>(),
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001263 Analyzer(Anlzr),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001264 FSet(Info.EntrySet),
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001265 LVarCtx(Info.EntryContext),
1266 CtxIndex(Info.EntryIndex)
1267 {}
Caitlin Sadowski33208342011-09-09 16:11:56 +00001268
1269 void VisitUnaryOperator(UnaryOperator *UO);
1270 void VisitBinaryOperator(BinaryOperator *BO);
1271 void VisitCastExpr(CastExpr *CE);
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001272 void VisitCallExpr(CallExpr *Exp);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001273 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001274 void VisitDeclStmt(DeclStmt *S);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001275};
1276
Caitlin Sadowski33208342011-09-09 16:11:56 +00001277/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001278/// of at least the passed in AccessKind.
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001279void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
Caitlin Sadowski33208342011-09-09 16:11:56 +00001280 AccessKind AK, Expr *MutexExp,
Aaron Ballmane0449042014-04-01 21:43:23 +00001281 ProtectedOperationKind POK,
1282 StringRef DiagKind) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001283 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001284
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001285 til::SExpr *Mutex = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1286 if (!Mutex) {
1287 // TODO: invalid locks?
1288 // warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001289 return;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001290 } else if (sx::shouldIgnore(Mutex)) {
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001291 return;
1292 }
1293
1294 LockData* LDat = FSet.findLockUniv(Analyzer->FactMan, Mutex);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001295 bool NoError = true;
1296 if (!LDat) {
1297 // No exact match found. Look for a partial match.
1298 FactEntry* FEntry = FSet.findPartialMatch(Analyzer->FactMan, Mutex);
1299 if (FEntry) {
1300 // Warn that there's no precise match.
1301 LDat = &FEntry->LDat;
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001302 std::string PartMatchStr = sx::toString(FEntry->MutID);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001303 StringRef PartMatchName(PartMatchStr);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001304 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK,
1305 sx::toString(Mutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001306 LK, Exp->getExprLoc(),
1307 &PartMatchName);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001308 } else {
1309 // Warn that there's no match at all.
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001310 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK,
1311 sx::toString(Mutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001312 LK, Exp->getExprLoc());
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001313 }
1314 NoError = false;
1315 }
1316 // Make sure the mutex we found is the right kind.
1317 if (NoError && LDat && !LDat->isAtLeast(LK))
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001318 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK,
1319 sx::toString(Mutex),
1320 LK, Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001321}
1322
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001323/// \brief Warn if the LSet contains the given lock.
Aaron Ballmane0449042014-04-01 21:43:23 +00001324void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1325 Expr *MutexExp,
1326 StringRef DiagKind) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001327 til::SExpr *Mutex = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1328 if (!Mutex) {
1329 // TODO: invalid locks?
1330 // warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001331 return;
1332 }
1333
1334 LockData* LDat = FSet.findLock(Analyzer->FactMan, Mutex);
Aaron Ballmane0449042014-04-01 21:43:23 +00001335 if (LDat)
1336 Analyzer->Handler.handleFunExcludesLock(
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001337 DiagKind, D->getNameAsString(), sx::toString(Mutex), Exp->getExprLoc());
DeLesley Hutchinsa5a00e82012-09-07 17:34:53 +00001338}
1339
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001340/// \brief Checks guarded_by and pt_guarded_by attributes.
1341/// Whenever we identify an access (read or write) to a DeclRefExpr that is
1342/// marked with guarded_by, we must ensure the appropriate mutexes are held.
1343/// Similarly, we check if the access is to an expression that dereferences
1344/// a pointer marked with pt_guarded_by.
1345void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK) {
1346 Exp = Exp->IgnoreParenCasts();
1347
1348 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
1349 // For dereferences
1350 if (UO->getOpcode() == clang::UO_Deref)
1351 checkPtAccess(UO->getSubExpr(), AK);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001352 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001353 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001354
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001355 if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001356 checkPtAccess(AE->getLHS(), AK);
1357 return;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001358 }
1359
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001360 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
1361 if (ME->isArrow())
1362 checkPtAccess(ME->getBase(), AK);
1363 else
1364 checkAccess(ME->getBase(), AK);
DeLesley Hutchins0cfa1a52012-12-08 03:46:30 +00001365 }
1366
Caitlin Sadowski33208342011-09-09 16:11:56 +00001367 const ValueDecl *D = getValueDecl(Exp);
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001368 if (!D || !D->hasAttrs())
Caitlin Sadowski33208342011-09-09 16:11:56 +00001369 return;
1370
Aaron Ballman9ead1242013-12-19 02:39:40 +00001371 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001372 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarAccess, AK,
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001373 Exp->getExprLoc());
Caitlin Sadowski33208342011-09-09 16:11:56 +00001374
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001375 for (const auto *I : D->specific_attrs<GuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001376 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarAccess,
1377 ClassifyDiagnostic(I));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001378}
1379
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001380/// \brief Checks pt_guarded_by and pt_guarded_var attributes.
1381void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK) {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001382 while (true) {
1383 if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
1384 Exp = PE->getSubExpr();
1385 continue;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001386 }
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001387 if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
1388 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1389 // If it's an actual array, and not a pointer, then it's elements
1390 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1391 checkAccess(CE->getSubExpr(), AK);
1392 return;
1393 }
1394 Exp = CE->getSubExpr();
1395 continue;
1396 }
1397 break;
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001398 }
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001399
1400 const ValueDecl *D = getValueDecl(Exp);
1401 if (!D || !D->hasAttrs())
1402 return;
1403
Aaron Ballman9ead1242013-12-19 02:39:40 +00001404 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty())
Aaron Ballmane0449042014-04-01 21:43:23 +00001405 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK_VarDereference, AK,
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001406 Exp->getExprLoc());
1407
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001408 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
Aaron Ballmane0449042014-04-01 21:43:23 +00001409 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK_VarDereference,
1410 ClassifyDiagnostic(I));
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001411}
1412
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001413/// \brief Process a function call, method call, constructor call,
1414/// or destructor call. This involves looking at the attributes on the
1415/// corresponding function/method/constructor/destructor, issuing warnings,
1416/// and updating the locksets accordingly.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001417///
1418/// FIXME: For classes annotated with one of the guarded annotations, we need
1419/// to treat const method calls as reads and non-const method calls as writes,
1420/// and check that the appropriate locks are held. Non-const method calls with
1421/// the same signature as const method calls can be also treated as reads.
1422///
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001423void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001424 SourceLocation Loc = Exp->getExprLoc();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001425 const AttrVec &ArgAttrs = D->getAttrs();
Aaron Ballmandf115d92014-03-21 14:48:48 +00001426 MutexIDList ExclusiveLocksToAdd, SharedLocksToAdd;
1427 MutexIDList ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
Aaron Ballmane0449042014-04-01 21:43:23 +00001428 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001429
Caitlin Sadowski33208342011-09-09 16:11:56 +00001430 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001431 Attr *At = const_cast<Attr*>(ArgAttrs[i]);
1432 switch (At->getKind()) {
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001433 // When we encounter a lock function, we need to add the lock to our
1434 // lockset.
1435 case attr::AcquireCapability: {
1436 auto *A = cast<AcquireCapabilityAttr>(At);
1437 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1438 : ExclusiveLocksToAdd,
1439 A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001440
1441 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001442 break;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001443 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001444
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001445 // An assert will add a lock to the lockset, but will not generate
1446 // a warning if it is already there, and will not generate a warning
1447 // if it is not removed.
1448 case attr::AssertExclusiveLock: {
1449 AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
1450
1451 MutexIDList AssertLocks;
1452 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001453 for (const auto &AssertLock : AssertLocks)
1454 Analyzer->addLock(FSet, AssertLock,
1455 LockData(Loc, LK_Exclusive, false, true),
1456 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001457 break;
1458 }
1459 case attr::AssertSharedLock: {
1460 AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
1461
1462 MutexIDList AssertLocks;
1463 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001464 for (const auto &AssertLock : AssertLocks)
1465 Analyzer->addLock(FSet, AssertLock,
1466 LockData(Loc, LK_Shared, false, true),
1467 ClassifyDiagnostic(A));
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001468 break;
1469 }
1470
Caitlin Sadowski33208342011-09-09 16:11:56 +00001471 // When we encounter an unlock function, we need to remove unlocked
1472 // mutexes from the lockset, and flag a warning if they are not there.
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001473 case attr::ReleaseCapability: {
1474 auto *A = cast<ReleaseCapabilityAttr>(At);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001475 if (A->isGeneric())
1476 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1477 else if (A->isShared())
1478 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1479 else
1480 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
Aaron Ballmane0449042014-04-01 21:43:23 +00001481
1482 CapDiagKind = ClassifyDiagnostic(A);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001483 break;
1484 }
1485
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001486 case attr::RequiresCapability: {
1487 RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001488 for (auto *Arg : A->args())
1489 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
Aaron Ballmane0449042014-04-01 21:43:23 +00001490 POK_FunctionCall, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001491 break;
1492 }
1493
1494 case attr::LocksExcluded: {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001495 LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
Aaron Ballmana82eaa72014-05-02 13:35:42 +00001496 for (auto *Arg : A->args())
1497 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001498 break;
1499 }
1500
Alp Tokerd4733632013-12-05 04:47:09 +00001501 // Ignore attributes unrelated to thread-safety
Caitlin Sadowski33208342011-09-09 16:11:56 +00001502 default:
1503 break;
1504 }
1505 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001506
1507 // Figure out if we're calling the constructor of scoped lockable class
1508 bool isScopedVar = false;
1509 if (VD) {
1510 if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1511 const CXXRecordDecl* PD = CD->getParent();
Aaron Ballman9ead1242013-12-19 02:39:40 +00001512 if (PD && PD->hasAttr<ScopedLockableAttr>())
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001513 isScopedVar = true;
1514 }
1515 }
1516
1517 // Add locks.
Aaron Ballmandf115d92014-03-21 14:48:48 +00001518 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00001519 Analyzer->addLock(FSet, M, LockData(Loc, LK_Exclusive, isScopedVar),
1520 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001521 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00001522 Analyzer->addLock(FSet, M, LockData(Loc, LK_Shared, isScopedVar),
1523 CapDiagKind);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001524
1525 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1526 // FIXME -- this doesn't work if we acquire multiple locks.
1527 if (isScopedVar) {
1528 SourceLocation MLoc = VD->getLocation();
1529 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001530 til::SExpr *SMutex = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001531
Aaron Ballmandf115d92014-03-21 14:48:48 +00001532 for (const auto &M : ExclusiveLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00001533 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive, M),
1534 CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001535 for (const auto &M : SharedLocksToAdd)
Aaron Ballmane0449042014-04-01 21:43:23 +00001536 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Shared, M),
1537 CapDiagKind);
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001538
1539 // handle corner case where the underlying mutex is invalid
1540 if (ExclusiveLocksToAdd.size() == 0 && SharedLocksToAdd.size() == 0) {
1541 Analyzer->addLock(FSet, SMutex, LockData(MLoc, LK_Exclusive),
1542 CapDiagKind);
1543 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001544 }
1545
1546 // Remove locks.
1547 // FIXME -- should only fully remove if the attribute refers to 'this'.
1548 bool Dtor = isa<CXXDestructorDecl>(D);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001549 for (const auto &M : ExclusiveLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001550 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001551 for (const auto &M : SharedLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001552 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001553 for (const auto &M : GenericLocksToRemove)
Aaron Ballmane0449042014-04-01 21:43:23 +00001554 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001555}
1556
DeLesley Hutchins9d530332012-01-06 19:16:50 +00001557
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001558/// \brief For unary operations which read and write a variable, we need to
1559/// check whether we hold any required mutexes. Reads are checked in
1560/// VisitCastExpr.
1561void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
1562 switch (UO->getOpcode()) {
1563 case clang::UO_PostDec:
1564 case clang::UO_PostInc:
1565 case clang::UO_PreDec:
1566 case clang::UO_PreInc: {
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001567 checkAccess(UO->getSubExpr(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001568 break;
1569 }
1570 default:
1571 break;
1572 }
1573}
1574
1575/// For binary operations which assign to a variable (writes), we need to check
1576/// whether we hold any required mutexes.
1577/// FIXME: Deal with non-primitive types.
1578void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
1579 if (!BO->isAssignmentOp())
1580 return;
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001581
1582 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001583 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001584
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001585 checkAccess(BO->getLHS(), AK_Written);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001586}
1587
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001588
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001589/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1590/// need to ensure we hold any required mutexes.
1591/// FIXME: Deal with non-primitive types.
1592void BuildLockset::VisitCastExpr(CastExpr *CE) {
1593 if (CE->getCastKind() != CK_LValueToRValue)
1594 return;
DeLesley Hutchins5df82f22012-12-05 00:52:33 +00001595 checkAccess(CE->getSubExpr(), AK_Read);
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001596}
1597
1598
DeLesley Hutchins714296c2011-12-29 00:56:48 +00001599void BuildLockset::VisitCallExpr(CallExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001600 if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
1601 MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
1602 // ME can be null when calling a method pointer
1603 CXXMethodDecl *MD = CE->getMethodDecl();
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001604
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001605 if (ME && MD) {
1606 if (ME->isArrow()) {
1607 if (MD->isConst()) {
1608 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
1609 } else { // FIXME -- should be AK_Written
1610 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001611 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001612 } else {
1613 if (MD->isConst())
1614 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
1615 else // FIXME -- should be AK_Written
1616 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001617 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001618 }
1619 } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
1620 switch (OE->getOperator()) {
1621 case OO_Equal: {
1622 const Expr *Target = OE->getArg(0);
1623 const Expr *Source = OE->getArg(1);
1624 checkAccess(Target, AK_Written);
1625 checkAccess(Source, AK_Read);
1626 break;
1627 }
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001628 case OO_Star:
DeLesley Hutchinse73d6b62013-11-08 19:42:01 +00001629 case OO_Arrow:
1630 case OO_Subscript: {
DeLesley Hutchinsd1c9b37d2014-03-10 23:03:49 +00001631 const Expr *Obj = OE->getArg(0);
1632 checkAccess(Obj, AK_Read);
1633 checkPtAccess(Obj, AK_Read);
DeLesley Hutchins5ede5cc2013-11-05 23:09:56 +00001634 break;
1635 }
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001636 default: {
DeLesley Hutchins05b7b372013-11-06 18:40:01 +00001637 const Expr *Obj = OE->getArg(0);
1638 checkAccess(Obj, AK_Read);
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001639 break;
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001640 }
1641 }
1642 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001643 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1644 if(!D || !D->hasAttrs())
1645 return;
1646 handleCall(Exp, D);
1647}
1648
1649void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
DeLesley Hutchinsc105ba12013-04-01 17:47:37 +00001650 const CXXConstructorDecl *D = Exp->getConstructor();
1651 if (D && D->isCopyConstructor()) {
1652 const Expr* Source = Exp->getArg(0);
1653 checkAccess(Source, AK_Read);
DeLesley Hutchinsf489d2b2012-12-05 01:20:45 +00001654 }
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001655 // FIXME -- only handles constructors in DeclStmt below.
1656}
1657
1658void BuildLockset::VisitDeclStmt(DeclStmt *S) {
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001659 // adjust the context
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001660 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001661
Aaron Ballman9ee54d12014-05-14 20:42:13 +00001662 for (auto *D : S->getDeclGroup()) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001663 if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
1664 Expr *E = VD->getInit();
DeLesley Hutchins0c1da202012-07-03 18:25:56 +00001665 // handle constructors that involve temporaries
1666 if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
1667 E = EWC->getSubExpr();
1668
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001669 if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
1670 NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
1671 if (!CtorD || !CtorD->hasAttrs())
1672 return;
1673 handleCall(CE, CtorD, VD);
1674 }
1675 }
1676 }
DeLesley Hutchinsdb917bd2011-10-21 18:06:53 +00001677}
1678
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00001679
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001680
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001681/// \brief Compute the intersection of two locksets and issue warnings for any
1682/// locks in the symmetric difference.
1683///
1684/// This function is used at a merge point in the CFG when comparing the lockset
1685/// of each branch being merged. For example, given the following sequence:
1686/// A; if () then B; else C; D; we need to check that the lockset after B and C
1687/// are the same. In the event of a difference, we use the intersection of these
1688/// two locksets at the start of D.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001689///
Ted Kremenek78094ca2012-08-22 23:50:41 +00001690/// \param FSet1 The first lockset.
1691/// \param FSet2 The second lockset.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001692/// \param JoinLoc The location of the join point for error reporting
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001693/// \param LEK1 The error message to report if a mutex is missing from LSet1
1694/// \param LEK2 The error message to report if a mutex is missing from Lset2
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001695void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
1696 const FactSet &FSet2,
1697 SourceLocation JoinLoc,
1698 LockErrorKind LEK1,
1699 LockErrorKind LEK2,
1700 bool Modify) {
1701 FactSet FSet1Orig = FSet1;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001702
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001703 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
Aaron Ballman59a72b92014-05-14 18:32:59 +00001704 for (const auto &Fact : FSet2) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001705 const til::SExpr *FSet2Mutex = FactMan[Fact].MutID;
Aaron Ballman59a72b92014-05-14 18:32:59 +00001706 const LockData &LDat2 = FactMan[Fact].LDat;
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001707 FactSet::iterator I1 = FSet1.findLockIter(FactMan, FSet2Mutex);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001708
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001709 if (I1 != FSet1.end()) {
1710 const LockData* LDat1 = &FactMan[*I1].LDat;
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00001711 if (LDat1->LKind != LDat2.LKind) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001712 Handler.handleExclusiveAndShared("mutex", sx::toString(FSet2Mutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001713 LDat2.AcquireLoc, LDat1->AcquireLoc);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001714 if (Modify && LDat1->LKind != LK_Exclusive) {
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001715 // Take the exclusive lock, which is the one in FSet2.
Aaron Ballman59a72b92014-05-14 18:32:59 +00001716 *I1 = Fact;
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001717 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001718 }
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001719 else if (LDat1->Asserted && !LDat2.Asserted) {
1720 // The non-asserted lock in FSet2 is the one we want to track.
Aaron Ballman59a72b92014-05-14 18:32:59 +00001721 *I1 = Fact;
DeLesley Hutchinsb6824312013-05-17 23:02:59 +00001722 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001723 } else {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001724 if (LDat2.UnderlyingMutex) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001725 if (FSet2.findLock(FactMan, LDat2.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00001726 // If this is a scoped lock that manages another mutex, and if the
1727 // underlying mutex is still held, then warn about the underlying
1728 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00001729 Handler.handleMutexHeldEndOfScope("mutex",
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001730 sx::toString(LDat2.UnderlyingMutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001731 LDat2.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00001732 }
1733 }
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001734 else if (!LDat2.Managed && !sx::isUniversal(FSet2Mutex) &&
1735 !LDat2.Asserted)
1736 Handler.handleMutexHeldEndOfScope("mutex", sx::toString(FSet2Mutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001737 LDat2.AcquireLoc, JoinLoc, LEK1);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001738 }
1739 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001740
DeLesley Hutchins3b2c66b2013-05-20 17:57:55 +00001741 // Find locks in FSet1 that are not in FSet2, and remove them.
Aaron Ballman59a72b92014-05-14 18:32:59 +00001742 for (const auto &Fact : FSet1Orig) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001743 const til::SExpr *FSet1Mutex = FactMan[Fact].MutID;
Aaron Ballman59a72b92014-05-14 18:32:59 +00001744 const LockData &LDat1 = FactMan[Fact].LDat;
DeLesley Hutchinsd162c912012-06-28 22:42:48 +00001745
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001746 if (!FSet2.findLock(FactMan, FSet1Mutex)) {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001747 if (LDat1.UnderlyingMutex) {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001748 if (FSet1Orig.findLock(FactMan, LDat1.UnderlyingMutex)) {
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00001749 // If this is a scoped lock that manages another mutex, and if the
1750 // underlying mutex is still held, then warn about the underlying
1751 // mutex.
Aaron Ballmane0449042014-04-01 21:43:23 +00001752 Handler.handleMutexHeldEndOfScope("mutex",
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001753 sx::toString(LDat1.UnderlyingMutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001754 LDat1.AcquireLoc, JoinLoc, LEK1);
DeLesley Hutchinsab0d4e62012-07-02 22:26:29 +00001755 }
1756 }
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001757 else if (!LDat1.Managed && !sx::isUniversal(FSet1Mutex) &&
1758 !LDat1.Asserted)
1759 Handler.handleMutexHeldEndOfScope("mutex", sx::toString(FSet1Mutex),
Aaron Ballmane0449042014-04-01 21:43:23 +00001760 LDat1.AcquireLoc, JoinLoc, LEK2);
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001761 if (Modify)
1762 FSet1.removeLock(FactMan, FSet1Mutex);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001763 }
1764 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00001765}
1766
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001767
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00001768// Return true if block B never continues to its successors.
1769inline bool neverReturns(const CFGBlock* B) {
1770 if (B->hasNoReturnElement())
1771 return true;
1772 if (B->empty())
1773 return false;
1774
1775 CFGElement Last = B->back();
David Blaikie00be69a2013-02-23 00:29:34 +00001776 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
1777 if (isa<CXXThrowExpr>(S->getStmt()))
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00001778 return true;
1779 }
1780 return false;
1781}
1782
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001783
Caitlin Sadowski33208342011-09-09 16:11:56 +00001784/// \brief Check a function's CFG for thread-safety violations.
1785///
1786/// We traverse the blocks in the CFG, compute the set of mutexes that are held
1787/// at the end of each block, and issue warnings for thread safety violations.
1788/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00001789void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001790 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
1791 // For now, we just use the walker to set things up.
1792 threadSafety::CFGWalker walker;
1793 if (!walker.init(AC))
1794 return;
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001795
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001796 // AC.dumpCFG(true);
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001797 // threadSafety::printSCFG(walker);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001798
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001799 CFG *CFGraph = walker.getGraph();
1800 const NamedDecl *D = walker.getDecl();
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001801
Aaron Ballman9ead1242013-12-19 02:39:40 +00001802 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
DeLesley Hutchinsa088f672011-10-17 21:33:35 +00001803 return;
DeLesley Hutchinsb2213912014-04-07 18:09:54 +00001804
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00001805 // FIXME: Do something a bit more intelligent inside constructor and
1806 // destructor code. Constructors and destructors must assume unique access
1807 // to 'this', so checks on member variable access is disabled, but we should
1808 // still enable checks on other objects.
1809 if (isa<CXXConstructorDecl>(D))
1810 return; // Don't check inside constructors.
1811 if (isa<CXXDestructorDecl>(D))
1812 return; // Don't check inside destructors.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001813
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001814 BlockInfo.resize(CFGraph->getNumBlockIDs(),
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001815 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
Caitlin Sadowski33208342011-09-09 16:11:56 +00001816
1817 // We need to explore the CFG via a "topological" ordering.
1818 // That way, we will be guaranteed to have information about required
1819 // predecessor locksets when exploring a new block.
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001820 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00001821 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001822
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00001823 // Mark entry block as reachable
1824 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
1825
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001826 // Compute SSA names for local variables
1827 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
1828
Richard Smith92286672012-02-03 04:45:26 +00001829 // Fill in source locations for all CFGBlocks.
1830 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
1831
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001832 MutexIDList ExclusiveLocksAcquired;
1833 MutexIDList SharedLocksAcquired;
1834 MutexIDList LocksReleased;
1835
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00001836 // Add locks from exclusive_locks_required and shared_locks_required
DeLesley Hutchinsc2286f62012-02-16 17:13:43 +00001837 // to initial lockset. Also turn off checking for lock and unlock functions.
1838 // FIXME: is there a more intelligent way to check lock/unlock functions?
Ted Kremenek4b4c51c2011-10-22 02:14:27 +00001839 if (!SortedGraph->empty() && D->hasAttrs()) {
1840 const CFGBlock *FirstBlock = *SortedGraph->begin();
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001841 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001842 const AttrVec &ArgAttrs = D->getAttrs();
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001843
1844 MutexIDList ExclusiveLocksToAdd;
1845 MutexIDList SharedLocksToAdd;
Aaron Ballmane0449042014-04-01 21:43:23 +00001846 StringRef CapDiagKind = "mutex";
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001847
1848 SourceLocation Loc = D->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00001849 for (const auto *Attr : ArgAttrs) {
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001850 Loc = Attr->getLocation();
Aaron Ballman0491afa2014-04-18 13:13:15 +00001851 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
Aaron Ballmanefe348e2014-02-18 17:36:50 +00001852 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
Craig Topper25542942014-05-20 04:30:07 +00001853 nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00001854 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00001855 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001856 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
1857 // We must ignore such methods.
1858 if (A->args_size() == 0)
1859 return;
1860 // FIXME -- deal with exclusive vs. shared unlock functions?
Aaron Ballman0491afa2014-04-18 13:13:15 +00001861 getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
1862 getMutexIDs(LocksReleased, A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00001863 CapDiagKind = ClassifyDiagnostic(A);
Aaron Ballman0491afa2014-04-18 13:13:15 +00001864 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001865 if (A->args_size() == 0)
1866 return;
Aaron Ballman18d85ae2014-03-20 16:02:49 +00001867 getMutexIDs(A->isShared() ? SharedLocksAcquired
1868 : ExclusiveLocksAcquired,
1869 A, nullptr, D);
Aaron Ballmane0449042014-04-01 21:43:23 +00001870 CapDiagKind = ClassifyDiagnostic(A);
DeLesley Hutchinsc4a6e512012-07-02 21:59:24 +00001871 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
1872 // Don't try to check trylock functions for now
1873 return;
1874 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
1875 // Don't try to check trylock functions for now
1876 return;
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001877 }
1878 }
DeLesley Hutchins09bcefc2012-07-05 21:16:29 +00001879
1880 // FIXME -- Loc can be wrong here.
Aaron Ballmane0449042014-04-01 21:43:23 +00001881 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1882 addLock(InitialLockset, ExclusiveLockToAdd, LockData(Loc, LK_Exclusive),
1883 CapDiagKind);
1884 for (const auto &SharedLockToAdd : SharedLocksToAdd)
1885 addLock(InitialLockset, SharedLockToAdd, LockData(Loc, LK_Shared),
1886 CapDiagKind);
Caitlin Sadowski6525fb22011-09-15 17:43:08 +00001887 }
1888
Aaron Ballmane80bfcd2014-04-17 21:44:08 +00001889 for (const auto *CurrBlock : *SortedGraph) {
Caitlin Sadowski33208342011-09-09 16:11:56 +00001890 int CurrBlockID = CurrBlock->getBlockID();
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001891 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
Caitlin Sadowski33208342011-09-09 16:11:56 +00001892
1893 // Use the default initial lockset in case there are no predecessors.
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001894 VisitedBlocks.insert(CurrBlock);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001895
1896 // Iterate through the predecessor blocks and warn if the lockset for all
1897 // predecessors is not the same. We take the entry lockset of the current
1898 // block to be the intersection of all previous locksets.
1899 // FIXME: By keeping the intersection, we may output more errors in future
1900 // for a lock which is not in the intersection, but was in the union. We
1901 // may want to also keep the union in future. As an example, let's say
1902 // the intersection contains Mutex L, and the union contains L and M.
1903 // Later we unlock M. At this point, we would output an error because we
1904 // never locked M; although the real error is probably that we forgot to
1905 // lock M on all code paths. Conversely, let's say that later we lock M.
1906 // In this case, we should compare against the intersection instead of the
1907 // union because the real error is probably that we forgot to unlock M on
1908 // all code paths.
1909 bool LocksetInitialized = false;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001910 SmallVector<CFGBlock *, 8> SpecialBlocks;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001911 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
1912 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
1913
1914 // if *PI -> CurrBlock is a back edge
Aaron Ballman0491afa2014-04-18 13:13:15 +00001915 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00001916 continue;
1917
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00001918 int PrevBlockID = (*PI)->getBlockID();
1919 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1920
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00001921 // Ignore edges from blocks that can't return.
DeLesley Hutchins9fa426a2013-01-18 22:15:45 +00001922 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
DeLesley Hutchinsa2587ef2012-03-02 22:02:58 +00001923 continue;
1924
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00001925 // Okay, we can reach this block from the entry.
1926 CurrBlockInfo->Reachable = true;
1927
Richard Smith815b29d2012-02-03 03:30:07 +00001928 // If the previous block ended in a 'continue' or 'break' statement, then
1929 // a difference in locksets is probably due to a bug in that block, rather
1930 // than in some other predecessor. In that case, keep the other
1931 // predecessor's lockset.
1932 if (const Stmt *Terminator = (*PI)->getTerminator()) {
1933 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
1934 SpecialBlocks.push_back(*PI);
1935 continue;
1936 }
1937 }
1938
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001939 FactSet PrevLockset;
1940 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001941
Caitlin Sadowski33208342011-09-09 16:11:56 +00001942 if (!LocksetInitialized) {
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001943 CurrBlockInfo->EntrySet = PrevLockset;
Caitlin Sadowski33208342011-09-09 16:11:56 +00001944 LocksetInitialized = true;
1945 } else {
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001946 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
1947 CurrBlockInfo->EntryLoc,
1948 LEK_LockedSomePredecessors);
Caitlin Sadowski33208342011-09-09 16:11:56 +00001949 }
1950 }
1951
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00001952 // Skip rest of block if it's not reachable.
1953 if (!CurrBlockInfo->Reachable)
1954 continue;
1955
Richard Smith815b29d2012-02-03 03:30:07 +00001956 // Process continue and break blocks. Assume that the lockset for the
1957 // resulting block is unaffected by any discrepancies in them.
Aaron Ballman0491afa2014-04-18 13:13:15 +00001958 for (const auto *PrevBlock : SpecialBlocks) {
Richard Smith815b29d2012-02-03 03:30:07 +00001959 int PrevBlockID = PrevBlock->getBlockID();
1960 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
1961
1962 if (!LocksetInitialized) {
1963 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
1964 LocksetInitialized = true;
1965 } else {
1966 // Determine whether this edge is a loop terminator for diagnostic
1967 // purposes. FIXME: A 'break' statement might be a loop terminator, but
1968 // it might also be part of a switch. Also, a subsequent destructor
1969 // might add to the lockset, in which case the real issue might be a
1970 // double lock on the other path.
1971 const Stmt *Terminator = PrevBlock->getTerminator();
1972 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
1973
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001974 FactSet PrevLockset;
1975 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
1976 PrevBlock, CurrBlock);
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001977
Richard Smith815b29d2012-02-03 03:30:07 +00001978 // Do not update EntrySet.
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00001979 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
1980 PrevBlockInfo->ExitLoc,
Richard Smith815b29d2012-02-03 03:30:07 +00001981 IsLoop ? LEK_LockedSomeLoopIterations
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00001982 : LEK_LockedSomePredecessors,
1983 false);
Richard Smith815b29d2012-02-03 03:30:07 +00001984 }
1985 }
1986
DeLesley Hutchins8c9d9572012-04-19 16:48:43 +00001987 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
1988
DeLesley Hutchins9b7022e2012-01-06 18:36:09 +00001989 // Visit all the statements in the basic block.
Caitlin Sadowski33208342011-09-09 16:11:56 +00001990 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
1991 BE = CurrBlock->end(); BI != BE; ++BI) {
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00001992 switch (BI->getKind()) {
1993 case CFGElement::Statement: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00001994 CFGStmt CS = BI->castAs<CFGStmt>();
1995 LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00001996 break;
1997 }
1998 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
1999 case CFGElement::AutomaticObjectDtor: {
David Blaikie2a01f5d2013-02-21 20:58:29 +00002000 CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
2001 CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
2002 AD.getDestructorDecl(AC.getASTContext()));
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002003 if (!DD->hasAttrs())
2004 break;
2005
2006 // Create a dummy expression,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002007 VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
John McCall113bee02012-03-10 09:33:50 +00002008 DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue,
David Blaikie2a01f5d2013-02-21 20:58:29 +00002009 AD.getTriggerStmt()->getLocEnd());
DeLesley Hutchinsf893e8a2011-10-21 20:51:27 +00002010 LocksetBuilder.handleCall(&DRE, DD);
2011 break;
2012 }
2013 default:
2014 break;
2015 }
Caitlin Sadowski33208342011-09-09 16:11:56 +00002016 }
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002017 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
Caitlin Sadowski33208342011-09-09 16:11:56 +00002018
2019 // For every back edge from CurrBlock (the end of the loop) to another block
2020 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2021 // the one held at the beginning of FirstLoopBlock. We can look up the
2022 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2023 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2024 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2025
2026 // if CurrBlock -> *SI is *not* a back edge
Craig Topper25542942014-05-20 04:30:07 +00002027 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
Caitlin Sadowski33208342011-09-09 16:11:56 +00002028 continue;
2029
2030 CFGBlock *FirstLoopBlock = *SI;
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002031 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2032 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2033 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2034 PreLoop->EntryLoc,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002035 LEK_LockedSomeLoopIterations,
2036 false);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002037 }
2038 }
2039
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002040 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2041 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002042
DeLesley Hutchins10958ca2012-09-21 17:57:00 +00002043 // Skip the final check if the exit block is unreachable.
2044 if (!Final->Reachable)
2045 return;
2046
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002047 // By default, we expect all locks held on entry to be held on exit.
2048 FactSet ExpectedExitSet = Initial->EntrySet;
2049
2050 // Adjust the expected exit set by adding or removing locks, as declared
2051 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2052 // issue the appropriate warning.
2053 // FIXME: the location here is not quite right.
Aaron Ballman0491afa2014-04-18 13:13:15 +00002054 for (const auto &Lock : ExclusiveLocksAcquired)
2055 ExpectedExitSet.addLock(FactMan, Lock,
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002056 LockData(D->getLocation(), LK_Exclusive));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002057 for (const auto &Lock : SharedLocksAcquired)
2058 ExpectedExitSet.addLock(FactMan, Lock,
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002059 LockData(D->getLocation(), LK_Shared));
Aaron Ballman0491afa2014-04-18 13:13:15 +00002060 for (const auto &Lock : LocksReleased)
2061 ExpectedExitSet.removeLock(FactMan, Lock);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002062
Caitlin Sadowski086fb952011-09-16 00:35:54 +00002063 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00002064 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
DeLesley Hutchinsebbf77012012-06-22 17:07:28 +00002065 Final->ExitLoc,
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00002066 LEK_LockedAtEndOfFunction,
DeLesley Hutchinsc9776fa2012-08-10 18:39:05 +00002067 LEK_NotLockedAtEndOfFunction,
2068 false);
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002069}
2070
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002071
2072/// \brief Check a function's CFG for thread-safety violations.
2073///
2074/// We traverse the blocks in the CFG, compute the set of mutexes that are held
2075/// at the end of each block, and issue warnings for thread safety violations.
2076/// Each block in the CFG is traversed exactly once.
Ted Kremenek81ce1c82011-10-24 01:32:45 +00002077void runThreadSafetyAnalysis(AnalysisDeclContext &AC,
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002078 ThreadSafetyHandler &Handler) {
2079 ThreadSafetyAnalyzer Analyzer(Handler);
2080 Analyzer.runAnalysis(AC);
Caitlin Sadowski33208342011-09-09 16:11:56 +00002081}
2082
2083/// \brief Helper function that returns a LockKind required for the given level
2084/// of access.
2085LockKind getLockKindFromAccessKind(AccessKind AK) {
2086 switch (AK) {
2087 case AK_Read :
2088 return LK_Shared;
2089 case AK_Written :
2090 return LK_Exclusive;
2091 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00002092 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski33208342011-09-09 16:11:56 +00002093}
DeLesley Hutchins3d312b12011-10-21 16:14:33 +00002094
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002095}} // end namespace clang::threadSafety