blob: 5f03b5832be4354fbc6870004a22dda3b77315bb [file] [log] [blame]
Caitlin Sadowski402aa062011-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//
Caitlin Sadowski19903462011-09-14 20:05:09 +000013// See http://clang.llvm.org/docs/LanguageExtensions.html#threadsafety for more
14// information.
Caitlin Sadowski402aa062011-09-09 16:11:56 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "clang/Analysis/Analyses/ThreadSafety.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000019#include "clang/Analysis/AnalysisContext.h"
20#include "clang/Analysis/CFG.h"
21#include "clang/Analysis/CFGStmtMap.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000022#include "clang/AST/DeclCXX.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtVisitor.h"
Caitlin Sadowskid5b16052011-09-09 23:00:59 +000026#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/SourceLocation.h"
Caitlin Sadowski402aa062011-09-09 16:11:56 +000028#include "llvm/ADT/BitVector.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/ImmutableMap.h"
31#include "llvm/ADT/PostOrderIterator.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringRef.h"
34#include <algorithm>
35#include <vector>
36
37using namespace clang;
38using namespace thread_safety;
39
Caitlin Sadowski19903462011-09-14 20:05:09 +000040// Key method definition
41ThreadSafetyHandler::~ThreadSafetyHandler() {}
42
Caitlin Sadowski402aa062011-09-09 16:11:56 +000043namespace {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +000044
Caitlin Sadowski402aa062011-09-09 16:11:56 +000045/// \brief Implements a set of CFGBlocks using a BitVector.
46///
47/// This class contains a minimal interface, primarily dictated by the SetType
48/// template parameter of the llvm::po_iterator template, as used with external
49/// storage. We also use this set to keep track of which CFGBlocks we visit
50/// during the analysis.
51class CFGBlockSet {
52 llvm::BitVector VisitedBlockIDs;
53
54public:
55 // po_iterator requires this iterator, but the only interface needed is the
56 // value_type typedef.
57 struct iterator {
58 typedef const CFGBlock *value_type;
59 };
60
61 CFGBlockSet() {}
62 CFGBlockSet(const CFG *G) : VisitedBlockIDs(G->getNumBlockIDs(), false) {}
63
64 /// \brief Set the bit associated with a particular CFGBlock.
65 /// This is the important method for the SetType template parameter.
66 bool insert(const CFGBlock *Block) {
67 // Note that insert() is called by po_iterator, which doesn't check to make
68 // sure that Block is non-null. Moreover, the CFGBlock iterator will
69 // occasionally hand out null pointers for pruned edges, so we catch those
70 // here.
71 if (Block == 0)
72 return false; // if an edge is trivially false.
73 if (VisitedBlockIDs.test(Block->getBlockID()))
74 return false;
75 VisitedBlockIDs.set(Block->getBlockID());
76 return true;
77 }
78
79 /// \brief Check if the bit for a CFGBlock has been already set.
80 /// This method is for tracking visited blocks in the main threadsafety loop.
81 /// Block must not be null.
82 bool alreadySet(const CFGBlock *Block) {
83 return VisitedBlockIDs.test(Block->getBlockID());
84 }
85};
86
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +000087
Caitlin Sadowski402aa062011-09-09 16:11:56 +000088/// \brief We create a helper class which we use to iterate through CFGBlocks in
89/// the topological order.
90class TopologicallySortedCFG {
91 typedef llvm::po_iterator<const CFG*, CFGBlockSet, true> po_iterator;
92
93 std::vector<const CFGBlock*> Blocks;
94
95public:
96 typedef std::vector<const CFGBlock*>::reverse_iterator iterator;
97
98 TopologicallySortedCFG(const CFG *CFGraph) {
99 Blocks.reserve(CFGraph->getNumBlockIDs());
100 CFGBlockSet BSet(CFGraph);
101
102 for (po_iterator I = po_iterator::begin(CFGraph, BSet),
103 E = po_iterator::end(CFGraph, BSet); I != E; ++I) {
104 Blocks.push_back(*I);
105 }
106 }
107
108 iterator begin() {
109 return Blocks.rbegin();
110 }
111
112 iterator end() {
113 return Blocks.rend();
114 }
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000115
116 bool empty() {
117 return begin() == end();
118 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000119};
120
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000121
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000122/// \brief A MutexID object uniquely identifies a particular mutex, and
123/// is built from an Expr* (i.e. calling a lock function).
124///
125/// Thread-safety analysis works by comparing lock expressions. Within the
126/// body of a function, an expression such as "x->foo->bar.mu" will resolve to
127/// a particular mutex object at run-time. Subsequent occurrences of the same
128/// expression (where "same" means syntactic equality) will refer to the same
129/// run-time object if three conditions hold:
130/// (1) Local variables in the expression, such as "x" have not changed.
131/// (2) Values on the heap that affect the expression have not changed.
132/// (3) The expression involves only pure function calls.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000133///
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000134/// The current implementation assumes, but does not verify, that multiple uses
135/// of the same lock expression satisfies these criteria.
136///
137/// Clang introduces an additional wrinkle, which is that it is difficult to
138/// derive canonical expressions, or compare expressions directly for equality.
139/// Thus, we identify a mutex not by an Expr, but by the set of named
140/// declarations that are referenced by the Expr. In other words,
141/// x->foo->bar.mu will be a four element vector with the Decls for
142/// mu, bar, and foo, and x. The vector will uniquely identify the expression
143/// for all practical purposes.
144///
145/// Note we will need to perform substitution on "this" and function parameter
146/// names when constructing a lock expression.
147///
148/// For example:
149/// class C { Mutex Mu; void lock() EXCLUSIVE_LOCK_FUNCTION(this->Mu); };
150/// void myFunc(C *X) { ... X->lock() ... }
151/// The original expression for the mutex acquired by myFunc is "this->Mu", but
152/// "X" is substituted for "this" so we get X->Mu();
153///
154/// For another example:
155/// foo(MyList *L) EXCLUSIVE_LOCKS_REQUIRED(L->Mu) { ... }
156/// MyList *MyL;
157/// foo(MyL); // requires lock MyL->Mu to be held
158class MutexID {
159 SmallVector<NamedDecl*, 2> DeclSeq;
160
161 /// Build a Decl sequence representing the lock from the given expression.
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000162 /// Recursive function that terminates on DeclRefExpr.
163 /// Note: this function merely creates a MutexID; it does not check to
164 /// ensure that the original expression is a valid mutex expression.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000165 void buildMutexID(Expr *Exp, Expr *Parent, int NumArgs,
166 const NamedDecl **FunArgDecls, Expr **FunArgs) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000167 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp)) {
DeLesley Hutchins81216392011-10-17 21:38:02 +0000168 if (FunArgDecls) {
169 // Substitute call arguments for references to function parameters
170 for (int i = 0; i < NumArgs; ++i) {
171 if (DRE->getDecl() == FunArgDecls[i]) {
172 buildMutexID(FunArgs[i], 0, 0, 0, 0);
173 return;
174 }
175 }
176 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000177 NamedDecl *ND = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
178 DeclSeq.push_back(ND);
179 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
180 NamedDecl *ND = ME->getMemberDecl();
181 DeclSeq.push_back(ND);
DeLesley Hutchins81216392011-10-17 21:38:02 +0000182 buildMutexID(ME->getBase(), Parent, NumArgs, FunArgDecls, FunArgs);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000183 } else if (isa<CXXThisExpr>(Exp)) {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000184 if (Parent)
DeLesley Hutchins81216392011-10-17 21:38:02 +0000185 buildMutexID(Parent, 0, 0, 0, 0);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000186 else
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000187 return; // mutexID is still valid in this case
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000188 } else if (UnaryOperator *UOE = dyn_cast<UnaryOperator>(Exp))
189 buildMutexID(UOE->getSubExpr(), Parent, NumArgs, FunArgDecls, FunArgs);
190 else if (CastExpr *CE = dyn_cast<CastExpr>(Exp))
DeLesley Hutchins81216392011-10-17 21:38:02 +0000191 buildMutexID(CE->getSubExpr(), Parent, NumArgs, FunArgDecls, FunArgs);
Caitlin Sadowski99107eb2011-09-09 16:21:55 +0000192 else
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000193 DeclSeq.clear(); // Mark as invalid lock expression.
194 }
195
196 /// \brief Construct a MutexID from an expression.
197 /// \param MutexExp The original mutex expression within an attribute
198 /// \param DeclExp An expression involving the Decl on which the attribute
199 /// occurs.
200 /// \param D The declaration to which the lock/unlock attribute is attached.
201 void buildMutexIDFromExp(Expr *MutexExp, Expr *DeclExp, const NamedDecl *D) {
202 Expr *Parent = 0;
DeLesley Hutchins81216392011-10-17 21:38:02 +0000203 unsigned NumArgs = 0;
204 Expr **FunArgs = 0;
205 SmallVector<const NamedDecl*, 8> FunArgDecls;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000206
207 if (DeclExp == 0) {
DeLesley Hutchins81216392011-10-17 21:38:02 +0000208 buildMutexID(MutexExp, 0, 0, 0, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000209 return;
210 }
211
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000212 // Examine DeclExp to find Parent and FunArgs, which are used to substitute
213 // for formal parameters when we call buildMutexID later.
DeLesley Hutchins81216392011-10-17 21:38:02 +0000214 if (MemberExpr *ME = dyn_cast<MemberExpr>(DeclExp)) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000215 Parent = ME->getBase();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000216 } else if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000217 Parent = CE->getImplicitObjectArgument();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000218 NumArgs = CE->getNumArgs();
219 FunArgs = CE->getArgs();
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000220 } else if (CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
221 Parent = 0; // FIXME -- get the parent from DeclStmt
222 NumArgs = CE->getNumArgs();
223 FunArgs = CE->getArgs();
DeLesley Hutchins81216392011-10-17 21:38:02 +0000224 }
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000225
226 // If the attribute has no arguments, then assume the argument is "this".
227 if (MutexExp == 0) {
DeLesley Hutchins81216392011-10-17 21:38:02 +0000228 buildMutexID(Parent, 0, 0, 0, 0);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000229 return;
230 }
DeLesley Hutchins81216392011-10-17 21:38:02 +0000231
232 // FIXME: handle default arguments
233 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
234 for (unsigned i = 0, ni = FD->getNumParams(); i < ni && i < NumArgs; ++i) {
235 FunArgDecls.push_back(FD->getParamDecl(i));
236 }
237 }
238 buildMutexID(MutexExp, Parent, NumArgs, &FunArgDecls.front(), FunArgs);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000239 }
240
241public:
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000242 /// \param MutexExp The original mutex expression within an attribute
243 /// \param DeclExp An expression involving the Decl on which the attribute
244 /// occurs.
245 /// \param D The declaration to which the lock/unlock attribute is attached.
246 /// Caller must check isValid() after construction.
247 MutexID(Expr* MutexExp, Expr *DeclExp, const NamedDecl* D) {
248 buildMutexIDFromExp(MutexExp, DeclExp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000249 }
250
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000251 /// Return true if this is a valid decl sequence.
252 /// Caller must call this by hand after construction to handle errors.
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000253 bool isValid() const {
254 return !DeclSeq.empty();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000255 }
256
257 bool operator==(const MutexID &other) const {
258 return DeclSeq == other.DeclSeq;
259 }
260
261 bool operator!=(const MutexID &other) const {
262 return !(*this == other);
263 }
264
265 // SmallVector overloads Operator< to do lexicographic ordering. Note that
266 // we use pointer equality (and <) to compare NamedDecls. This means the order
267 // of MutexIDs in a lockset is nondeterministic. In order to output
268 // diagnostics in a deterministic ordering, we must order all diagnostics to
269 // output by SourceLocation when iterating through this lockset.
270 bool operator<(const MutexID &other) const {
271 return DeclSeq < other.DeclSeq;
272 }
273
274 /// \brief Returns the name of the first Decl in the list for a given MutexID;
275 /// e.g. the lock expression foo.bar() has name "bar".
276 /// The caret will point unambiguously to the lock expression, so using this
277 /// name in diagnostics is a way to get simple, and consistent, mutex names.
278 /// We do not want to output the entire expression text for security reasons.
279 StringRef getName() const {
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000280 assert(isValid());
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000281 return DeclSeq.front()->getName();
282 }
283
284 void Profile(llvm::FoldingSetNodeID &ID) const {
285 for (SmallVectorImpl<NamedDecl*>::const_iterator I = DeclSeq.begin(),
286 E = DeclSeq.end(); I != E; ++I) {
287 ID.AddPointer(*I);
288 }
289 }
290};
291
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000292
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000293/// \brief This is a helper class that stores info about the most recent
294/// accquire of a Lock.
295///
296/// The main body of the analysis maps MutexIDs to LockDatas.
297struct LockData {
298 SourceLocation AcquireLoc;
299
300 /// \brief LKind stores whether a lock is held shared or exclusively.
301 /// Note that this analysis does not currently support either re-entrant
302 /// locking or lock "upgrading" and "downgrading" between exclusive and
303 /// shared.
304 ///
305 /// FIXME: add support for re-entrant locking and lock up/downgrading
306 LockKind LKind;
307
308 LockData(SourceLocation AcquireLoc, LockKind LKind)
309 : AcquireLoc(AcquireLoc), LKind(LKind) {}
310
311 bool operator==(const LockData &other) const {
312 return AcquireLoc == other.AcquireLoc && LKind == other.LKind;
313 }
314
315 bool operator!=(const LockData &other) const {
316 return !(*this == other);
317 }
318
319 void Profile(llvm::FoldingSetNodeID &ID) const {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000320 ID.AddInteger(AcquireLoc.getRawEncoding());
321 ID.AddInteger(LKind);
322 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000323};
324
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000325
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000326/// A Lockset maps each MutexID (defined above) to information about how it has
327/// been locked.
328typedef llvm::ImmutableMap<MutexID, LockData> Lockset;
329
330/// \brief We use this class to visit different types of expressions in
331/// CFGBlocks, and build up the lockset.
332/// An expression may cause us to add or remove locks from the lockset, or else
333/// output error messages related to missing locks.
334/// FIXME: In future, we may be able to not inherit from a visitor.
335class BuildLockset : public StmtVisitor<BuildLockset> {
336 ThreadSafetyHandler &Handler;
337 Lockset LSet;
338 Lockset::Factory &LocksetFactory;
339
340 // Helper functions
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000341 void removeLock(SourceLocation UnlockLoc, MutexID &Mutex);
342 void addLock(SourceLocation LockLoc, MutexID &Mutex, LockKind LK);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000343
344 template <class AttrType>
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000345 void addLocksToSet(LockKind LK, AttrType *Attr, Expr *Exp, NamedDecl *D);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000346
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000347 const ValueDecl *getValueDecl(Expr *Exp);
348 void warnIfMutexNotHeld (const NamedDecl *D, Expr *Exp, AccessKind AK,
349 Expr *MutexExp, ProtectedOperationKind POK);
350 void checkAccess(Expr *Exp, AccessKind AK);
351 void checkDereference(Expr *Exp, AccessKind AK);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000352 void handleCall(Expr *Exp, NamedDecl *D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000353
354 /// \brief Returns true if the lockset contains a lock, regardless of whether
355 /// the lock is held exclusively or shared.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000356 bool locksetContains(const MutexID &Lock) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000357 return LSet.lookup(Lock);
358 }
359
360 /// \brief Returns true if the lockset contains a lock with the passed in
361 /// locktype.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000362 bool locksetContains(const MutexID &Lock, LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000363 const LockData *LockHeld = LSet.lookup(Lock);
364 return (LockHeld && KindRequested == LockHeld->LKind);
365 }
366
367 /// \brief Returns true if the lockset contains a lock with at least the
368 /// passed in locktype. So for example, if we pass in LK_Shared, this function
369 /// returns true if the lock is held LK_Shared or LK_Exclusive. If we pass in
370 /// LK_Exclusive, this function returns true if the lock is held LK_Exclusive.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000371 bool locksetContainsAtLeast(const MutexID &Lock,
372 LockKind KindRequested) const {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000373 switch (KindRequested) {
374 case LK_Shared:
375 return locksetContains(Lock);
376 case LK_Exclusive:
377 return locksetContains(Lock, KindRequested);
378 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +0000379 llvm_unreachable("Unknown LockKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000380 }
381
382public:
383 BuildLockset(ThreadSafetyHandler &Handler, Lockset LS, Lockset::Factory &F)
384 : StmtVisitor<BuildLockset>(), Handler(Handler), LSet(LS),
385 LocksetFactory(F) {}
386
387 Lockset getLockset() {
388 return LSet;
389 }
390
391 void VisitUnaryOperator(UnaryOperator *UO);
392 void VisitBinaryOperator(BinaryOperator *BO);
393 void VisitCastExpr(CastExpr *CE);
394 void VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp);
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000395 void VisitCXXConstructExpr(CXXConstructExpr *Exp);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000396};
397
398/// \brief Add a new lock to the lockset, warning if the lock is already there.
399/// \param LockLoc The source location of the acquire
400/// \param LockExp The lock expression corresponding to the lock to be added
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000401void BuildLockset::addLock(SourceLocation LockLoc, MutexID &Mutex,
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000402 LockKind LK) {
Caitlin Sadowski1748b122011-09-16 00:35:54 +0000403 // FIXME: deal with acquired before/after annotations. We can write a first
404 // pass that does the transitive lookup lazily, and refine afterwards.
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000405 LockData NewLock(LockLoc, LK);
406
407 // FIXME: Don't always warn when we have support for reentrant locks.
408 if (locksetContains(Mutex))
409 Handler.handleDoubleLock(Mutex.getName(), LockLoc);
410 LSet = LocksetFactory.add(LSet, Mutex, NewLock);
411}
412
413/// \brief Remove a lock from the lockset, warning if the lock is not there.
414/// \param LockExp The lock expression corresponding to the lock to be removed
415/// \param UnlockLoc The source location of the unlock (only used in error msg)
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000416void BuildLockset::removeLock(SourceLocation UnlockLoc, MutexID &Mutex) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000417 Lockset NewLSet = LocksetFactory.remove(LSet, Mutex);
418 if(NewLSet == LSet)
419 Handler.handleUnmatchedUnlock(Mutex.getName(), UnlockLoc);
420
421 LSet = NewLSet;
422}
423
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000424/// \brief This function, parameterized by an attribute type, is used to add a
425/// set of locks specified as attribute arguments to the lockset.
426template <typename AttrType>
427void BuildLockset::addLocksToSet(LockKind LK, AttrType *Attr,
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000428 Expr *Exp, NamedDecl* FunDecl) {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000429 typedef typename AttrType::args_iterator iterator_type;
430
431 SourceLocation ExpLocation = Exp->getExprLoc();
432
433 if (Attr->args_size() == 0) {
434 // The mutex held is the "this" object.
435
436 MutexID Mutex(0, Exp, FunDecl);
437 if (!Mutex.isValid())
438 Handler.handleInvalidLockExp(Exp->getExprLoc());
439 else
440 addLock(ExpLocation, Mutex, LK);
441 return;
442 }
443
444 for (iterator_type I=Attr->args_begin(), E=Attr->args_end(); I != E; ++I) {
445 MutexID Mutex(*I, Exp, FunDecl);
446 if (!Mutex.isValid())
447 Handler.handleInvalidLockExp(Exp->getExprLoc());
448 else
449 addLock(ExpLocation, Mutex, LK);
450 }
451}
452
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000453/// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs
454const ValueDecl *BuildLockset::getValueDecl(Expr *Exp) {
455 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Exp))
456 return DR->getDecl();
457
458 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp))
459 return ME->getMemberDecl();
460
461 return 0;
462}
463
464/// \brief Warn if the LSet does not contain a lock sufficient to protect access
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000465/// of at least the passed in AccessKind.
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000466void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, Expr *Exp,
467 AccessKind AK, Expr *MutexExp,
468 ProtectedOperationKind POK) {
469 LockKind LK = getLockKindFromAccessKind(AK);
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000470
471 MutexID Mutex(MutexExp, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000472 if (!Mutex.isValid())
473 Handler.handleInvalidLockExp(MutexExp->getExprLoc());
474 else if (!locksetContainsAtLeast(Mutex, LK))
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000475 Handler.handleMutexNotHeld(D, POK, Mutex.getName(), LK, Exp->getExprLoc());
476}
477
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000478/// \brief This method identifies variable dereferences and checks pt_guarded_by
479/// and pt_guarded_var annotations. Note that we only check these annotations
480/// at the time a pointer is dereferenced.
481/// FIXME: We need to check for other types of pointer dereferences
482/// (e.g. [], ->) and deal with them here.
483/// \param Exp An expression that has been read or written.
484void BuildLockset::checkDereference(Expr *Exp, AccessKind AK) {
485 UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp);
486 if (!UO || UO->getOpcode() != clang::UO_Deref)
487 return;
488 Exp = UO->getSubExpr()->IgnoreParenCasts();
489
490 const ValueDecl *D = getValueDecl(Exp);
491 if(!D || !D->hasAttrs())
492 return;
493
494 if (D->getAttr<PtGuardedVarAttr>() && LSet.isEmpty())
495 Handler.handleNoMutexHeld(D, POK_VarDereference, AK, Exp->getExprLoc());
496
497 const AttrVec &ArgAttrs = D->getAttrs();
498 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
499 if (PtGuardedByAttr *PGBAttr = dyn_cast<PtGuardedByAttr>(ArgAttrs[i]))
500 warnIfMutexNotHeld(D, Exp, AK, PGBAttr->getArg(), POK_VarDereference);
501}
502
503/// \brief Checks guarded_by and guarded_var attributes.
504/// Whenever we identify an access (read or write) of a DeclRefExpr or
505/// MemberExpr, we need to check whether there are any guarded_by or
506/// guarded_var attributes, and make sure we hold the appropriate mutexes.
507void BuildLockset::checkAccess(Expr *Exp, AccessKind AK) {
508 const ValueDecl *D = getValueDecl(Exp);
509 if(!D || !D->hasAttrs())
510 return;
511
512 if (D->getAttr<GuardedVarAttr>() && LSet.isEmpty())
513 Handler.handleNoMutexHeld(D, POK_VarAccess, AK, Exp->getExprLoc());
514
515 const AttrVec &ArgAttrs = D->getAttrs();
516 for(unsigned i = 0, Size = ArgAttrs.size(); i < Size; ++i)
517 if (GuardedByAttr *GBAttr = dyn_cast<GuardedByAttr>(ArgAttrs[i]))
518 warnIfMutexNotHeld(D, Exp, AK, GBAttr->getArg(), POK_VarAccess);
519}
520
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000521/// \brief Process a function call, method call, constructor call,
522/// or destructor call. This involves looking at the attributes on the
523/// corresponding function/method/constructor/destructor, issuing warnings,
524/// and updating the locksets accordingly.
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000525///
526/// FIXME: For classes annotated with one of the guarded annotations, we need
527/// to treat const method calls as reads and non-const method calls as writes,
528/// and check that the appropriate locks are held. Non-const method calls with
529/// the same signature as const method calls can be also treated as reads.
530///
531/// FIXME: We need to also visit CallExprs to catch/check global functions.
Caitlin Sadowski1748b122011-09-16 00:35:54 +0000532///
533/// FIXME: Do not flag an error for member variables accessed in constructors/
534/// destructors
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000535void BuildLockset::handleCall(Expr *Exp, NamedDecl *D) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000536 SourceLocation ExpLocation = Exp->getExprLoc();
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000537
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000538 AttrVec &ArgAttrs = D->getAttrs();
539 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
540 Attr *Attr = ArgAttrs[i];
541 switch (Attr->getKind()) {
542 // When we encounter an exclusive lock function, we need to add the lock
543 // to our lockset with kind exclusive.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000544 case attr::ExclusiveLockFunction: {
545 ExclusiveLockFunctionAttr *A = cast<ExclusiveLockFunctionAttr>(Attr);
546 addLocksToSet(LK_Exclusive, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000547 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000548 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000549
550 // When we encounter a shared lock function, we need to add the lock
551 // to our lockset with kind shared.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000552 case attr::SharedLockFunction: {
553 SharedLockFunctionAttr *A = cast<SharedLockFunctionAttr>(Attr);
554 addLocksToSet(LK_Shared, A, Exp, D);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000555 break;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000556 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000557
558 // When we encounter an unlock function, we need to remove unlocked
559 // mutexes from the lockset, and flag a warning if they are not there.
560 case attr::UnlockFunction: {
561 UnlockFunctionAttr *UFAttr = cast<UnlockFunctionAttr>(Attr);
562
563 if (UFAttr->args_size() == 0) { // The lock held is the "this" object.
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000564 MutexID Mu(0, Exp, D);
565 if (!Mu.isValid())
566 Handler.handleInvalidLockExp(Exp->getExprLoc());
567 else
568 removeLock(ExpLocation, Mu);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000569 break;
570 }
571
572 for (UnlockFunctionAttr::args_iterator I = UFAttr->args_begin(),
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000573 E = UFAttr->args_end(); I != E; ++I) {
574 MutexID Mutex(*I, Exp, D);
575 if (!Mutex.isValid())
576 Handler.handleInvalidLockExp(Exp->getExprLoc());
577 else
578 removeLock(ExpLocation, Mutex);
579 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000580 break;
581 }
582
583 case attr::ExclusiveLocksRequired: {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000584 ExclusiveLocksRequiredAttr *ELRAttr =
585 cast<ExclusiveLocksRequiredAttr>(Attr);
586
587 for (ExclusiveLocksRequiredAttr::args_iterator
588 I = ELRAttr->args_begin(), E = ELRAttr->args_end(); I != E; ++I)
589 warnIfMutexNotHeld(D, Exp, AK_Written, *I, POK_FunctionCall);
590 break;
591 }
592
593 case attr::SharedLocksRequired: {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000594 SharedLocksRequiredAttr *SLRAttr = cast<SharedLocksRequiredAttr>(Attr);
595
596 for (SharedLocksRequiredAttr::args_iterator I = SLRAttr->args_begin(),
597 E = SLRAttr->args_end(); I != E; ++I)
598 warnIfMutexNotHeld(D, Exp, AK_Read, *I, POK_FunctionCall);
599 break;
600 }
601
602 case attr::LocksExcluded: {
603 LocksExcludedAttr *LEAttr = cast<LocksExcludedAttr>(Attr);
604 for (LocksExcludedAttr::args_iterator I = LEAttr->args_begin(),
605 E = LEAttr->args_end(); I != E; ++I) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000606 MutexID Mutex(*I, Exp, D);
Caitlin Sadowski194418f2011-09-14 20:00:24 +0000607 if (!Mutex.isValid())
608 Handler.handleInvalidLockExp((*I)->getExprLoc());
609 else if (locksetContains(Mutex))
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000610 Handler.handleFunExcludesLock(D->getName(), Mutex.getName(),
611 ExpLocation);
612 }
613 break;
614 }
615
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000616 // Ignore other (non thread-safety) attributes
617 default:
618 break;
619 }
620 }
621}
622
DeLesley Hutchinse0eaa852011-10-21 18:06:53 +0000623/// \brief For unary operations which read and write a variable, we need to
624/// check whether we hold any required mutexes. Reads are checked in
625/// VisitCastExpr.
626void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
627 switch (UO->getOpcode()) {
628 case clang::UO_PostDec:
629 case clang::UO_PostInc:
630 case clang::UO_PreDec:
631 case clang::UO_PreInc: {
632 Expr *SubExp = UO->getSubExpr()->IgnoreParenCasts();
633 checkAccess(SubExp, AK_Written);
634 checkDereference(SubExp, AK_Written);
635 break;
636 }
637 default:
638 break;
639 }
640}
641
642/// For binary operations which assign to a variable (writes), we need to check
643/// whether we hold any required mutexes.
644/// FIXME: Deal with non-primitive types.
645void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
646 if (!BO->isAssignmentOp())
647 return;
648 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
649 checkAccess(LHSExp, AK_Written);
650 checkDereference(LHSExp, AK_Written);
651}
652
653/// Whenever we do an LValue to Rvalue cast, we are reading a variable and
654/// need to ensure we hold any required mutexes.
655/// FIXME: Deal with non-primitive types.
656void BuildLockset::VisitCastExpr(CastExpr *CE) {
657 if (CE->getCastKind() != CK_LValueToRValue)
658 return;
659 Expr *SubExp = CE->getSubExpr()->IgnoreParenCasts();
660 checkAccess(SubExp, AK_Read);
661 checkDereference(SubExp, AK_Read);
662}
663
664
665void BuildLockset::VisitCXXMemberCallExpr(CXXMemberCallExpr *Exp) {
666 NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
667 if(!D || !D->hasAttrs())
668 return;
669 handleCall(Exp, D);
670}
671
672void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
673 NamedDecl *D = cast<NamedDecl>(Exp->getConstructor());
674 if(!D || !D->hasAttrs())
675 return;
676 handleCall(Exp, D);
677}
678
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000679
680/// \brief Class which implements the core thread safety analysis routines.
681class ThreadSafetyAnalyzer {
682 ThreadSafetyHandler &Handler;
683 Lockset::Factory LocksetFactory;
684
685public:
686 ThreadSafetyAnalyzer(ThreadSafetyHandler &H) : Handler(H) {}
687
688 Lockset intersectAndWarn(const Lockset LSet1, const Lockset LSet2,
689 LockErrorKind LEK);
690
691 Lockset addLock(Lockset &LSet, Expr *MutexExp, const NamedDecl *D,
692 LockKind LK, SourceLocation Loc);
693
694 void runAnalysis(AnalysisContext &AC);
695};
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000696
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000697/// \brief Compute the intersection of two locksets and issue warnings for any
698/// locks in the symmetric difference.
699///
700/// This function is used at a merge point in the CFG when comparing the lockset
701/// of each branch being merged. For example, given the following sequence:
702/// A; if () then B; else C; D; we need to check that the lockset after B and C
703/// are the same. In the event of a difference, we use the intersection of these
704/// two locksets at the start of D.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000705Lockset ThreadSafetyAnalyzer::intersectAndWarn(const Lockset LSet1,
706 const Lockset LSet2,
707 LockErrorKind LEK) {
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000708 Lockset Intersection = LSet1;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000709 for (Lockset::iterator I = LSet2.begin(), E = LSet2.end(); I != E; ++I) {
710 const MutexID &LSet2Mutex = I.getKey();
711 const LockData &LSet2LockData = I.getData();
712 if (const LockData *LD = LSet1.lookup(LSet2Mutex)) {
713 if (LD->LKind != LSet2LockData.LKind) {
714 Handler.handleExclusiveAndShared(LSet2Mutex.getName(),
715 LSet2LockData.AcquireLoc,
716 LD->AcquireLoc);
717 if (LD->LKind != LK_Exclusive)
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000718 Intersection = LocksetFactory.add(Intersection, LSet2Mutex,
719 LSet2LockData);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000720 }
721 } else {
722 Handler.handleMutexHeldEndOfScope(LSet2Mutex.getName(),
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000723 LSet2LockData.AcquireLoc, LEK);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000724 }
725 }
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000726
727 for (Lockset::iterator I = LSet1.begin(), E = LSet1.end(); I != E; ++I) {
728 if (!LSet2.contains(I.getKey())) {
729 const MutexID &Mutex = I.getKey();
730 const LockData &MissingLock = I.getData();
731 Handler.handleMutexHeldEndOfScope(Mutex.getName(),
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000732 MissingLock.AcquireLoc, LEK);
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000733 Intersection = LocksetFactory.remove(Intersection, Mutex);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000734 }
735 }
736 return Intersection;
737}
738
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000739Lockset ThreadSafetyAnalyzer::addLock(Lockset &LSet, Expr *MutexExp,
740 const NamedDecl *D,
741 LockKind LK, SourceLocation Loc) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000742 MutexID Mutex(MutexExp, 0, D);
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000743 if (!Mutex.isValid()) {
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000744 Handler.handleInvalidLockExp(MutexExp->getExprLoc());
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000745 return LSet;
746 }
747 LockData NewLock(Loc, LK);
748 return LocksetFactory.add(LSet, Mutex, NewLock);
749}
750
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000751/// \brief Check a function's CFG for thread-safety violations.
752///
753/// We traverse the blocks in the CFG, compute the set of mutexes that are held
754/// at the end of each block, and issue warnings for thread safety violations.
755/// Each block in the CFG is traversed exactly once.
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000756void ThreadSafetyAnalyzer::runAnalysis(AnalysisContext &AC) {
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000757 CFG *CFGraph = AC.getCFG();
758 if (!CFGraph) return;
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000759 const NamedDecl *D = dyn_cast_or_null<NamedDecl>(AC.getDecl());
760
761 if (!D)
762 return; // Ignore anonymous functions for now.
763 if (D->getAttr<NoThreadSafetyAnalysisAttr>())
764 return;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000765
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000766 // FIXME: Switch to SmallVector? Otherwise improve performance impact?
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000767 std::vector<Lockset> EntryLocksets(CFGraph->getNumBlockIDs(),
768 LocksetFactory.getEmptyMap());
769 std::vector<Lockset> ExitLocksets(CFGraph->getNumBlockIDs(),
770 LocksetFactory.getEmptyMap());
771
772 // We need to explore the CFG via a "topological" ordering.
773 // That way, we will be guaranteed to have information about required
774 // predecessor locksets when exploring a new block.
775 TopologicallySortedCFG SortedGraph(CFGraph);
776 CFGBlockSet VisitedBlocks(CFGraph);
777
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000778 // Add locks from exclusive_locks_required and shared_locks_required
779 // to initial lockset.
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000780 if (!SortedGraph.empty() && D->hasAttrs()) {
781 const CFGBlock *FirstBlock = *SortedGraph.begin();
782 Lockset &InitialLockset = EntryLocksets[FirstBlock->getBlockID()];
783 const AttrVec &ArgAttrs = D->getAttrs();
784 for(unsigned i = 0; i < ArgAttrs.size(); ++i) {
785 Attr *Attr = ArgAttrs[i];
Caitlin Sadowski1748b122011-09-16 00:35:54 +0000786 SourceLocation AttrLoc = Attr->getLocation();
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000787 if (SharedLocksRequiredAttr *SLRAttr
788 = dyn_cast<SharedLocksRequiredAttr>(Attr)) {
789 for (SharedLocksRequiredAttr::args_iterator
790 SLRIter = SLRAttr->args_begin(),
791 SLREnd = SLRAttr->args_end(); SLRIter != SLREnd; ++SLRIter)
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000792 InitialLockset = addLock(InitialLockset,
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000793 *SLRIter, D, LK_Shared,
Caitlin Sadowski1748b122011-09-16 00:35:54 +0000794 AttrLoc);
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000795 } else if (ExclusiveLocksRequiredAttr *ELRAttr
796 = dyn_cast<ExclusiveLocksRequiredAttr>(Attr)) {
797 for (ExclusiveLocksRequiredAttr::args_iterator
798 ELRIter = ELRAttr->args_begin(),
799 ELREnd = ELRAttr->args_end(); ELRIter != ELREnd; ++ELRIter)
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000800 InitialLockset = addLock(InitialLockset,
DeLesley Hutchins9f80a972011-10-17 21:33:35 +0000801 *ELRIter, D, LK_Exclusive,
Caitlin Sadowski1748b122011-09-16 00:35:54 +0000802 AttrLoc);
Caitlin Sadowskicb967512011-09-15 17:43:08 +0000803 }
804 }
805 }
806
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000807 for (TopologicallySortedCFG::iterator I = SortedGraph.begin(),
808 E = SortedGraph.end(); I!= E; ++I) {
809 const CFGBlock *CurrBlock = *I;
810 int CurrBlockID = CurrBlock->getBlockID();
811
812 VisitedBlocks.insert(CurrBlock);
813
814 // Use the default initial lockset in case there are no predecessors.
815 Lockset &Entryset = EntryLocksets[CurrBlockID];
816 Lockset &Exitset = ExitLocksets[CurrBlockID];
817
818 // Iterate through the predecessor blocks and warn if the lockset for all
819 // predecessors is not the same. We take the entry lockset of the current
820 // block to be the intersection of all previous locksets.
821 // FIXME: By keeping the intersection, we may output more errors in future
822 // for a lock which is not in the intersection, but was in the union. We
823 // may want to also keep the union in future. As an example, let's say
824 // the intersection contains Mutex L, and the union contains L and M.
825 // Later we unlock M. At this point, we would output an error because we
826 // never locked M; although the real error is probably that we forgot to
827 // lock M on all code paths. Conversely, let's say that later we lock M.
828 // In this case, we should compare against the intersection instead of the
829 // union because the real error is probably that we forgot to unlock M on
830 // all code paths.
831 bool LocksetInitialized = false;
832 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
833 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
834
835 // if *PI -> CurrBlock is a back edge
836 if (*PI == 0 || !VisitedBlocks.alreadySet(*PI))
837 continue;
838
839 int PrevBlockID = (*PI)->getBlockID();
840 if (!LocksetInitialized) {
841 Entryset = ExitLocksets[PrevBlockID];
842 LocksetInitialized = true;
843 } else {
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000844 Entryset = intersectAndWarn(Entryset, ExitLocksets[PrevBlockID],
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000845 LEK_LockedSomePredecessors);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000846 }
847 }
848
849 BuildLockset LocksetBuilder(Handler, Entryset, LocksetFactory);
850 for (CFGBlock::const_iterator BI = CurrBlock->begin(),
851 BE = CurrBlock->end(); BI != BE; ++BI) {
852 if (const CFGStmt *CfgStmt = dyn_cast<CFGStmt>(&*BI))
853 LocksetBuilder.Visit(const_cast<Stmt*>(CfgStmt->getStmt()));
854 }
855 Exitset = LocksetBuilder.getLockset();
856
857 // For every back edge from CurrBlock (the end of the loop) to another block
858 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
859 // the one held at the beginning of FirstLoopBlock. We can look up the
860 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
861 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
862 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
863
864 // if CurrBlock -> *SI is *not* a back edge
865 if (*SI == 0 || !VisitedBlocks.alreadySet(*SI))
866 continue;
867
868 CFGBlock *FirstLoopBlock = *SI;
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000869 Lockset PreLoop = EntryLocksets[FirstLoopBlock->getBlockID()];
870 Lockset LoopEnd = ExitLocksets[CurrBlockID];
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000871 intersectAndWarn(LoopEnd, PreLoop, LEK_LockedSomeLoopIterations);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000872 }
873 }
874
Caitlin Sadowski4e4bc752011-09-15 17:25:19 +0000875 Lockset InitialLockset = EntryLocksets[CFGraph->getEntry().getBlockID()];
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000876 Lockset FinalLockset = ExitLocksets[CFGraph->getExit().getBlockID()];
Caitlin Sadowski1748b122011-09-16 00:35:54 +0000877
878 // FIXME: Should we call this function for all blocks which exit the function?
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000879 intersectAndWarn(InitialLockset, FinalLockset, LEK_LockedAtEndOfFunction);
880}
881
882} // end anonymous namespace
883
884
885namespace clang {
886namespace thread_safety {
887
888/// \brief Check a function's CFG for thread-safety violations.
889///
890/// We traverse the blocks in the CFG, compute the set of mutexes that are held
891/// at the end of each block, and issue warnings for thread safety violations.
892/// Each block in the CFG is traversed exactly once.
893void runThreadSafetyAnalysis(AnalysisContext &AC,
894 ThreadSafetyHandler &Handler) {
895 ThreadSafetyAnalyzer Analyzer(Handler);
896 Analyzer.runAnalysis(AC);
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000897}
898
899/// \brief Helper function that returns a LockKind required for the given level
900/// of access.
901LockKind getLockKindFromAccessKind(AccessKind AK) {
902 switch (AK) {
903 case AK_Read :
904 return LK_Shared;
905 case AK_Written :
906 return LK_Exclusive;
907 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +0000908 llvm_unreachable("Unknown AccessKind");
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000909}
DeLesley Hutchinsa60448d2011-10-21 16:14:33 +0000910
Caitlin Sadowski402aa062011-09-09 16:11:56 +0000911}} // end namespace clang::thread_safety