1 //===- ThreadSafety.cpp ---------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // A intra-procedural analysis for thread safety (e.g. deadlocks and race
10 // conditions), based off of an annotation system.
12 // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
13 // for more information.
15 //===----------------------------------------------------------------------===//
17 #include "clang/Analysis/Analyses/ThreadSafety.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/OperationKinds.h"
25 #include "clang/AST/Stmt.h"
26 #include "clang/AST/StmtVisitor.h"
27 #include "clang/AST/Type.h"
28 #include "clang/Analysis/Analyses/PostOrderCFGView.h"
29 #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
30 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
31 #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
32 #include "clang/Analysis/Analyses/ThreadSafetyUtil.h"
33 #include "clang/Analysis/AnalysisDeclContext.h"
34 #include "clang/Analysis/CFG.h"
35 #include "clang/Basic/Builtins.h"
36 #include "clang/Basic/LLVM.h"
37 #include "clang/Basic/OperatorKinds.h"
38 #include "clang/Basic/SourceLocation.h"
39 #include "clang/Basic/Specifiers.h"
40 #include "llvm/ADT/ArrayRef.h"
41 #include "llvm/ADT/DenseMap.h"
42 #include "llvm/ADT/ImmutableMap.h"
43 #include "llvm/ADT/Optional.h"
44 #include "llvm/ADT/PointerIntPair.h"
45 #include "llvm/ADT/STLExtras.h"
46 #include "llvm/ADT/SmallVector.h"
47 #include "llvm/ADT/StringRef.h"
48 #include "llvm/Support/Allocator.h"
49 #include "llvm/Support/Casting.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/raw_ostream.h"
58 #include <type_traits>
62 using namespace clang;
63 using namespace threadSafety;
65 // Key method definition
66 ThreadSafetyHandler::~ThreadSafetyHandler() = default;
68 /// Issue a warning about an invalid lock expression
69 static void warnInvalidLock(ThreadSafetyHandler &Handler,
70 const Expr *MutexExp, const NamedDecl *D,
71 const Expr *DeclExp, StringRef Kind) {
74 Loc = DeclExp->getExprLoc();
76 // FIXME: add a note about the attribute location in MutexExp or D
78 Handler.handleInvalidLockExp(Kind, Loc);
83 /// A set of CapabilityExpr objects, which are compiled from thread safety
84 /// attributes on a function.
85 class CapExprSet : public SmallVector<CapabilityExpr, 4> {
87 /// Push M onto list, but discard duplicates.
88 void push_back_nodup(const CapabilityExpr &CapE) {
89 iterator It = std::find_if(begin(), end(),
90 [=](const CapabilityExpr &CapE2) {
91 return CapE.equals(CapE2);
101 /// This is a helper class that stores a fact that is known at a
102 /// particular point in program execution. Currently, a fact is a capability,
103 /// along with additional information, such as where it was acquired, whether
104 /// it is exclusive or shared, etc.
106 /// FIXME: this analysis does not currently support re-entrant locking.
107 class FactEntry : public CapabilityExpr {
109 /// Exclusive or shared.
112 /// Where it was acquired.
113 SourceLocation AcquireLoc;
115 /// True if the lock was asserted.
118 /// True if the lock was declared.
122 FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
123 bool Asrt, bool Declrd = false)
124 : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
126 virtual ~FactEntry() = default;
128 LockKind kind() const { return LKind; }
129 SourceLocation loc() const { return AcquireLoc; }
130 bool asserted() const { return Asserted; }
131 bool declared() const { return Declared; }
133 void setDeclared(bool D) { Declared = D; }
136 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
137 SourceLocation JoinLoc, LockErrorKind LEK,
138 ThreadSafetyHandler &Handler) const = 0;
139 virtual void handleLock(FactSet &FSet, FactManager &FactMan,
140 const FactEntry &entry, ThreadSafetyHandler &Handler,
141 StringRef DiagKind) const = 0;
142 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
143 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
144 bool FullyRemove, ThreadSafetyHandler &Handler,
145 StringRef DiagKind) const = 0;
147 // Return true if LKind >= LK, where exclusive > shared
148 bool isAtLeast(LockKind LK) const {
149 return (LKind == LK_Exclusive) || (LK == LK_Shared);
153 using FactID = unsigned short;
155 /// FactManager manages the memory for all facts that are created during
156 /// the analysis of a single routine.
159 std::vector<std::unique_ptr<const FactEntry>> Facts;
162 FactID newFact(std::unique_ptr<FactEntry> Entry) {
163 Facts.push_back(std::move(Entry));
164 return static_cast<unsigned short>(Facts.size() - 1);
167 const FactEntry &operator[](FactID F) const { return *Facts[F]; }
170 /// A FactSet is the set of facts that are known to be true at a
171 /// particular program point. FactSets must be small, because they are
172 /// frequently copied, and are thus implemented as a set of indices into a
173 /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
174 /// locks, so we can get away with doing a linear search for lookup. Note
175 /// that a hashtable or map is inappropriate in this case, because lookups
176 /// may involve partial pattern matches, rather than exact matches.
179 using FactVec = SmallVector<FactID, 4>;
184 using iterator = FactVec::iterator;
185 using const_iterator = FactVec::const_iterator;
187 iterator begin() { return FactIDs.begin(); }
188 const_iterator begin() const { return FactIDs.begin(); }
190 iterator end() { return FactIDs.end(); }
191 const_iterator end() const { return FactIDs.end(); }
193 bool isEmpty() const { return FactIDs.size() == 0; }
195 // Return true if the set contains only negative facts
196 bool isEmpty(FactManager &FactMan) const {
197 for (const auto FID : *this) {
198 if (!FactMan[FID].negative())
204 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
206 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
207 FactID F = FM.newFact(std::move(Entry));
208 FactIDs.push_back(F);
212 bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
213 unsigned n = FactIDs.size();
217 for (unsigned i = 0; i < n-1; ++i) {
218 if (FM[FactIDs[i]].matches(CapE)) {
219 FactIDs[i] = FactIDs[n-1];
224 if (FM[FactIDs[n-1]].matches(CapE)) {
231 iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
232 return std::find_if(begin(), end(), [&](FactID ID) {
233 return FM[ID].matches(CapE);
237 const FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
238 auto I = std::find_if(begin(), end(), [&](FactID ID) {
239 return FM[ID].matches(CapE);
241 return I != end() ? &FM[*I] : nullptr;
244 const FactEntry *findLockUniv(FactManager &FM,
245 const CapabilityExpr &CapE) const {
246 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
247 return FM[ID].matchesUniv(CapE);
249 return I != end() ? &FM[*I] : nullptr;
252 const FactEntry *findPartialMatch(FactManager &FM,
253 const CapabilityExpr &CapE) const {
254 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
255 return FM[ID].partiallyMatches(CapE);
257 return I != end() ? &FM[*I] : nullptr;
260 bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
261 auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
262 return FM[ID].valueDecl() == Vd;
268 class ThreadSafetyAnalyzer;
273 namespace threadSafety {
277 using BeforeVect = SmallVector<const ValueDecl *, 4>;
283 BeforeInfo() = default;
284 BeforeInfo(BeforeInfo &&) = default;
288 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
289 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
292 BeforeSet() = default;
294 BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
295 ThreadSafetyAnalyzer& Analyzer);
297 BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
298 ThreadSafetyAnalyzer &Analyzer);
300 void checkBeforeAfter(const ValueDecl* Vd,
302 ThreadSafetyAnalyzer& Analyzer,
303 SourceLocation Loc, StringRef CapKind);
310 } // namespace threadSafety
315 class LocalVariableMap;
317 using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
319 /// A side (entry or exit) of a CFG node.
320 enum CFGBlockSide { CBS_Entry, CBS_Exit };
322 /// CFGBlockInfo is a struct which contains all the information that is
323 /// maintained for each block in the CFG. See LocalVariableMap for more
324 /// information about the contexts.
325 struct CFGBlockInfo {
326 // Lockset held at entry to block
329 // Lockset held at exit from block
332 // Context held at entry to block
333 LocalVarContext EntryContext;
335 // Context held at exit from block
336 LocalVarContext ExitContext;
338 // Location of first statement in block
339 SourceLocation EntryLoc;
341 // Location of last statement in block.
342 SourceLocation ExitLoc;
344 // Used to replay contexts later
347 // Is this block reachable?
348 bool Reachable = false;
350 const FactSet &getSet(CFGBlockSide Side) const {
351 return Side == CBS_Entry ? EntrySet : ExitSet;
354 SourceLocation getLocation(CFGBlockSide Side) const {
355 return Side == CBS_Entry ? EntryLoc : ExitLoc;
359 CFGBlockInfo(LocalVarContext EmptyCtx)
360 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
363 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
366 // A LocalVariableMap maintains a map from local variables to their currently
367 // valid definitions. It provides SSA-like functionality when traversing the
368 // CFG. Like SSA, each definition or assignment to a variable is assigned a
369 // unique name (an integer), which acts as the SSA name for that definition.
370 // The total set of names is shared among all CFG basic blocks.
371 // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
372 // with their SSA-names. Instead, we compute a Context for each point in the
373 // code, which maps local variables to the appropriate SSA-name. This map
374 // changes with each assignment.
376 // The map is computed in a single pass over the CFG. Subsequent analyses can
377 // then query the map to find the appropriate Context for a statement, and use
378 // that Context to look up the definitions of variables.
379 class LocalVariableMap {
381 using Context = LocalVarContext;
383 /// A VarDefinition consists of an expression, representing the value of the
384 /// variable, along with the context in which that expression should be
385 /// interpreted. A reference VarDefinition does not itself contain this
386 /// information, but instead contains a pointer to a previous VarDefinition.
387 struct VarDefinition {
389 friend class LocalVariableMap;
391 // The original declaration for this variable.
392 const NamedDecl *Dec;
394 // The expression for this variable, OR
395 const Expr *Exp = nullptr;
397 // Reference to another VarDefinition
400 // The map with which Exp should be interpreted.
403 bool isReference() { return !Exp; }
406 // Create ordinary variable definition
407 VarDefinition(const NamedDecl *D, const Expr *E, Context C)
408 : Dec(D), Exp(E), Ctx(C) {}
410 // Create reference to previous definition
411 VarDefinition(const NamedDecl *D, unsigned R, Context C)
412 : Dec(D), Ref(R), Ctx(C) {}
416 Context::Factory ContextFactory;
417 std::vector<VarDefinition> VarDefinitions;
418 std::vector<unsigned> CtxIndices;
419 std::vector<std::pair<const Stmt *, Context>> SavedContexts;
423 // index 0 is a placeholder for undefined variables (aka phi-nodes).
424 VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
427 /// Look up a definition, within the given context.
428 const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
429 const unsigned *i = Ctx.lookup(D);
432 assert(*i < VarDefinitions.size());
433 return &VarDefinitions[*i];
436 /// Look up the definition for D within the given context. Returns
437 /// NULL if the expression is not statically known. If successful, also
438 /// modifies Ctx to hold the context of the return Expr.
439 const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
440 const unsigned *P = Ctx.lookup(D);
446 if (VarDefinitions[i].Exp) {
447 Ctx = VarDefinitions[i].Ctx;
448 return VarDefinitions[i].Exp;
450 i = VarDefinitions[i].Ref;
455 Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
457 /// Return the next context after processing S. This function is used by
458 /// clients of the class to get the appropriate context when traversing the
459 /// CFG. It must be called for every assignment or DeclStmt.
460 Context getNextContext(unsigned &CtxIndex, const Stmt *S, Context C) {
461 if (SavedContexts[CtxIndex+1].first == S) {
463 Context Result = SavedContexts[CtxIndex].second;
469 void dumpVarDefinitionName(unsigned i) {
471 llvm::errs() << "Undefined";
474 const NamedDecl *Dec = VarDefinitions[i].Dec;
476 llvm::errs() << "<<NULL>>";
479 Dec->printName(llvm::errs());
480 llvm::errs() << "." << i << " " << ((const void*) Dec);
483 /// Dumps an ASCII representation of the variable map to llvm::errs()
485 for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
486 const Expr *Exp = VarDefinitions[i].Exp;
487 unsigned Ref = VarDefinitions[i].Ref;
489 dumpVarDefinitionName(i);
490 llvm::errs() << " = ";
491 if (Exp) Exp->dump();
493 dumpVarDefinitionName(Ref);
494 llvm::errs() << "\n";
499 /// Dumps an ASCII representation of a Context to llvm::errs()
500 void dumpContext(Context C) {
501 for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
502 const NamedDecl *D = I.getKey();
503 D->printName(llvm::errs());
504 const unsigned *i = C.lookup(D);
505 llvm::errs() << " -> ";
506 dumpVarDefinitionName(*i);
507 llvm::errs() << "\n";
511 /// Builds the variable map.
512 void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
513 std::vector<CFGBlockInfo> &BlockInfo);
516 friend class VarMapBuilder;
518 // Get the current context index
519 unsigned getContextIndex() { return SavedContexts.size()-1; }
521 // Save the current context for later replay
522 void saveContext(const Stmt *S, Context C) {
523 SavedContexts.push_back(std::make_pair(S, C));
526 // Adds a new definition to the given context, and returns a new context.
527 // This method should be called when declaring a new variable.
528 Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
529 assert(!Ctx.contains(D));
530 unsigned newID = VarDefinitions.size();
531 Context NewCtx = ContextFactory.add(Ctx, D, newID);
532 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
536 // Add a new reference to an existing definition.
537 Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
538 unsigned newID = VarDefinitions.size();
539 Context NewCtx = ContextFactory.add(Ctx, D, newID);
540 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
544 // Updates a definition only if that definition is already in the map.
545 // This method should be called when assigning to an existing variable.
546 Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
547 if (Ctx.contains(D)) {
548 unsigned newID = VarDefinitions.size();
549 Context NewCtx = ContextFactory.remove(Ctx, D);
550 NewCtx = ContextFactory.add(NewCtx, D, newID);
551 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
557 // Removes a definition from the context, but keeps the variable name
558 // as a valid variable. The index 0 is a placeholder for cleared definitions.
559 Context clearDefinition(const NamedDecl *D, Context Ctx) {
560 Context NewCtx = Ctx;
561 if (NewCtx.contains(D)) {
562 NewCtx = ContextFactory.remove(NewCtx, D);
563 NewCtx = ContextFactory.add(NewCtx, D, 0);
568 // Remove a definition entirely frmo the context.
569 Context removeDefinition(const NamedDecl *D, Context Ctx) {
570 Context NewCtx = Ctx;
571 if (NewCtx.contains(D)) {
572 NewCtx = ContextFactory.remove(NewCtx, D);
577 Context intersectContexts(Context C1, Context C2);
578 Context createReferenceContext(Context C);
579 void intersectBackEdge(Context C1, Context C2);
584 // This has to be defined after LocalVariableMap.
585 CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
586 return CFGBlockInfo(M.getEmptyContext());
591 /// Visitor which builds a LocalVariableMap
592 class VarMapBuilder : public ConstStmtVisitor<VarMapBuilder> {
594 LocalVariableMap* VMap;
595 LocalVariableMap::Context Ctx;
597 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
598 : VMap(VM), Ctx(C) {}
600 void VisitDeclStmt(const DeclStmt *S);
601 void VisitBinaryOperator(const BinaryOperator *BO);
606 // Add new local variables to the variable map
607 void VarMapBuilder::VisitDeclStmt(const DeclStmt *S) {
608 bool modifiedCtx = false;
609 const DeclGroupRef DGrp = S->getDeclGroup();
610 for (const auto *D : DGrp) {
611 if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
612 const Expr *E = VD->getInit();
614 // Add local variables with trivial type to the variable map
615 QualType T = VD->getType();
616 if (T.isTrivialType(VD->getASTContext())) {
617 Ctx = VMap->addDefinition(VD, E, Ctx);
623 VMap->saveContext(S, Ctx);
626 // Update local variable definitions in variable map
627 void VarMapBuilder::VisitBinaryOperator(const BinaryOperator *BO) {
628 if (!BO->isAssignmentOp())
631 Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
633 // Update the variable map and current context.
634 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
635 const ValueDecl *VDec = DRE->getDecl();
636 if (Ctx.lookup(VDec)) {
637 if (BO->getOpcode() == BO_Assign)
638 Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
640 // FIXME -- handle compound assignment operators
641 Ctx = VMap->clearDefinition(VDec, Ctx);
642 VMap->saveContext(BO, Ctx);
647 // Computes the intersection of two contexts. The intersection is the
648 // set of variables which have the same definition in both contexts;
649 // variables with different definitions are discarded.
650 LocalVariableMap::Context
651 LocalVariableMap::intersectContexts(Context C1, Context C2) {
653 for (const auto &P : C1) {
654 const NamedDecl *Dec = P.first;
655 const unsigned *i2 = C2.lookup(Dec);
656 if (!i2) // variable doesn't exist on second path
657 Result = removeDefinition(Dec, Result);
658 else if (*i2 != P.second) // variable exists, but has different definition
659 Result = clearDefinition(Dec, Result);
664 // For every variable in C, create a new variable that refers to the
665 // definition in C. Return a new context that contains these new variables.
666 // (We use this for a naive implementation of SSA on loop back-edges.)
667 LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
668 Context Result = getEmptyContext();
669 for (const auto &P : C)
670 Result = addReference(P.first, P.second, Result);
674 // This routine also takes the intersection of C1 and C2, but it does so by
675 // altering the VarDefinitions. C1 must be the result of an earlier call to
676 // createReferenceContext.
677 void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
678 for (const auto &P : C1) {
679 unsigned i1 = P.second;
680 VarDefinition *VDef = &VarDefinitions[i1];
681 assert(VDef->isReference());
683 const unsigned *i2 = C2.lookup(P.first);
684 if (!i2 || (*i2 != i1))
685 VDef->Ref = 0; // Mark this variable as undefined
689 // Traverse the CFG in topological order, so all predecessors of a block
690 // (excluding back-edges) are visited before the block itself. At
691 // each point in the code, we calculate a Context, which holds the set of
692 // variable definitions which are visible at that point in execution.
693 // Visible variables are mapped to their definitions using an array that
694 // contains all definitions.
696 // At join points in the CFG, the set is computed as the intersection of
697 // the incoming sets along each edge, E.g.
699 // { Context | VarDefinitions }
700 // int x = 0; { x -> x1 | x1 = 0 }
701 // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
702 // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
703 // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
704 // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
706 // This is essentially a simpler and more naive version of the standard SSA
707 // algorithm. Those definitions that remain in the intersection are from blocks
708 // that strictly dominate the current block. We do not bother to insert proper
709 // phi nodes, because they are not used in our analysis; instead, wherever
710 // a phi node would be required, we simply remove that definition from the
711 // context (E.g. x above).
713 // The initial traversal does not capture back-edges, so those need to be
714 // handled on a separate pass. Whenever the first pass encounters an
715 // incoming back edge, it duplicates the context, creating new definitions
716 // that refer back to the originals. (These correspond to places where SSA
717 // might have to insert a phi node.) On the second pass, these definitions are
718 // set to NULL if the variable has changed on the back-edge (i.e. a phi
719 // node was actually required.) E.g.
721 // { Context | VarDefinitions }
722 // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
723 // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
724 // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
725 // ... { y -> y1 | x3 = 2, x2 = 1, ... }
726 void LocalVariableMap::traverseCFG(CFG *CFGraph,
727 const PostOrderCFGView *SortedGraph,
728 std::vector<CFGBlockInfo> &BlockInfo) {
729 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
731 CtxIndices.resize(CFGraph->getNumBlockIDs());
733 for (const auto *CurrBlock : *SortedGraph) {
734 unsigned CurrBlockID = CurrBlock->getBlockID();
735 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
737 VisitedBlocks.insert(CurrBlock);
739 // Calculate the entry context for the current block
740 bool HasBackEdges = false;
742 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
743 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
744 // if *PI -> CurrBlock is a back edge, so skip it
745 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
750 unsigned PrevBlockID = (*PI)->getBlockID();
751 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
754 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
758 CurrBlockInfo->EntryContext =
759 intersectContexts(CurrBlockInfo->EntryContext,
760 PrevBlockInfo->ExitContext);
764 // Duplicate the context if we have back-edges, so we can call
765 // intersectBackEdges later.
767 CurrBlockInfo->EntryContext =
768 createReferenceContext(CurrBlockInfo->EntryContext);
770 // Create a starting context index for the current block
771 saveContext(nullptr, CurrBlockInfo->EntryContext);
772 CurrBlockInfo->EntryIndex = getContextIndex();
774 // Visit all the statements in the basic block.
775 VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
776 for (const auto &BI : *CurrBlock) {
777 switch (BI.getKind()) {
778 case CFGElement::Statement: {
779 CFGStmt CS = BI.castAs<CFGStmt>();
780 VMapBuilder.Visit(CS.getStmt());
787 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
789 // Mark variables on back edges as "unknown" if they've been changed.
790 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
791 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
792 // if CurrBlock -> *SI is *not* a back edge
793 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
796 CFGBlock *FirstLoopBlock = *SI;
797 Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
798 Context LoopEnd = CurrBlockInfo->ExitContext;
799 intersectBackEdge(LoopBegin, LoopEnd);
803 // Put an extra entry at the end of the indexed context array
804 unsigned exitID = CFGraph->getExit().getBlockID();
805 saveContext(nullptr, BlockInfo[exitID].ExitContext);
808 /// Find the appropriate source locations to use when producing diagnostics for
809 /// each block in the CFG.
810 static void findBlockLocations(CFG *CFGraph,
811 const PostOrderCFGView *SortedGraph,
812 std::vector<CFGBlockInfo> &BlockInfo) {
813 for (const auto *CurrBlock : *SortedGraph) {
814 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
816 // Find the source location of the last statement in the block, if the
817 // block is not empty.
818 if (const Stmt *S = CurrBlock->getTerminatorStmt()) {
819 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
821 for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
822 BE = CurrBlock->rend(); BI != BE; ++BI) {
823 // FIXME: Handle other CFGElement kinds.
824 if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
825 CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
831 if (CurrBlockInfo->ExitLoc.isValid()) {
832 // This block contains at least one statement. Find the source location
833 // of the first statement in the block.
834 for (const auto &BI : *CurrBlock) {
835 // FIXME: Handle other CFGElement kinds.
836 if (Optional<CFGStmt> CS = BI.getAs<CFGStmt>()) {
837 CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
841 } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
842 CurrBlock != &CFGraph->getExit()) {
843 // The block is empty, and has a single predecessor. Use its exit
845 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
846 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
853 class LockableFactEntry : public FactEntry {
855 /// managed by ScopedLockable object
859 LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
860 bool Mng = false, bool Asrt = false)
861 : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
864 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
865 SourceLocation JoinLoc, LockErrorKind LEK,
866 ThreadSafetyHandler &Handler) const override {
867 if (!Managed && !asserted() && !negative() && !isUniversal()) {
868 Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
873 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
874 ThreadSafetyHandler &Handler,
875 StringRef DiagKind) const override {
876 Handler.handleDoubleLock(DiagKind, entry.toString(), loc(), entry.loc());
879 void handleUnlock(FactSet &FSet, FactManager &FactMan,
880 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
881 bool FullyRemove, ThreadSafetyHandler &Handler,
882 StringRef DiagKind) const override {
883 FSet.removeLock(FactMan, Cp);
884 if (!Cp.negative()) {
885 FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
886 !Cp, LK_Exclusive, UnlockLoc));
891 class ScopedLockableFactEntry : public FactEntry {
893 enum UnderlyingCapabilityKind {
894 UCK_Acquired, ///< Any kind of acquired capability.
895 UCK_ReleasedShared, ///< Shared capability that was released.
896 UCK_ReleasedExclusive, ///< Exclusive capability that was released.
899 using UnderlyingCapability =
900 llvm::PointerIntPair<const til::SExpr *, 2, UnderlyingCapabilityKind>;
902 SmallVector<UnderlyingCapability, 4> UnderlyingMutexes;
905 ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc)
906 : FactEntry(CE, LK_Exclusive, Loc, false) {}
908 void addExclusiveLock(const CapabilityExpr &M) {
909 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
912 void addSharedLock(const CapabilityExpr &M) {
913 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_Acquired);
916 void addExclusiveUnlock(const CapabilityExpr &M) {
917 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedExclusive);
920 void addSharedUnlock(const CapabilityExpr &M) {
921 UnderlyingMutexes.emplace_back(M.sexpr(), UCK_ReleasedShared);
925 handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
926 SourceLocation JoinLoc, LockErrorKind LEK,
927 ThreadSafetyHandler &Handler) const override {
928 for (const auto &UnderlyingMutex : UnderlyingMutexes) {
929 const auto *Entry = FSet.findLock(
930 FactMan, CapabilityExpr(UnderlyingMutex.getPointer(), false));
931 if ((UnderlyingMutex.getInt() == UCK_Acquired && Entry) ||
932 (UnderlyingMutex.getInt() != UCK_Acquired && !Entry)) {
933 // If this scoped lock manages another mutex, and if the underlying
934 // mutex is still/not held, then warn about the underlying mutex.
935 Handler.handleMutexHeldEndOfScope(
936 "mutex", sx::toString(UnderlyingMutex.getPointer()), loc(), JoinLoc,
942 void handleLock(FactSet &FSet, FactManager &FactMan, const FactEntry &entry,
943 ThreadSafetyHandler &Handler,
944 StringRef DiagKind) const override {
945 for (const auto &UnderlyingMutex : UnderlyingMutexes) {
946 CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
948 if (UnderlyingMutex.getInt() == UCK_Acquired)
949 lock(FSet, FactMan, UnderCp, entry.kind(), entry.loc(), &Handler,
952 unlock(FSet, FactMan, UnderCp, entry.loc(), &Handler, DiagKind);
956 void handleUnlock(FactSet &FSet, FactManager &FactMan,
957 const CapabilityExpr &Cp, SourceLocation UnlockLoc,
958 bool FullyRemove, ThreadSafetyHandler &Handler,
959 StringRef DiagKind) const override {
960 assert(!Cp.negative() && "Managing object cannot be negative.");
961 for (const auto &UnderlyingMutex : UnderlyingMutexes) {
962 CapabilityExpr UnderCp(UnderlyingMutex.getPointer(), false);
964 // Remove/lock the underlying mutex if it exists/is still unlocked; warn
965 // on double unlocking/locking if we're not destroying the scoped object.
966 ThreadSafetyHandler *TSHandler = FullyRemove ? nullptr : &Handler;
967 if (UnderlyingMutex.getInt() == UCK_Acquired) {
968 unlock(FSet, FactMan, UnderCp, UnlockLoc, TSHandler, DiagKind);
970 LockKind kind = UnderlyingMutex.getInt() == UCK_ReleasedShared
973 lock(FSet, FactMan, UnderCp, kind, UnlockLoc, TSHandler, DiagKind);
977 FSet.removeLock(FactMan, Cp);
981 void lock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
982 LockKind kind, SourceLocation loc, ThreadSafetyHandler *Handler,
983 StringRef DiagKind) const {
984 if (const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
986 Handler->handleDoubleLock(DiagKind, Cp.toString(), Fact->loc(), loc);
988 FSet.removeLock(FactMan, !Cp);
989 FSet.addLock(FactMan,
990 std::make_unique<LockableFactEntry>(Cp, kind, loc));
994 void unlock(FactSet &FSet, FactManager &FactMan, const CapabilityExpr &Cp,
995 SourceLocation loc, ThreadSafetyHandler *Handler,
996 StringRef DiagKind) const {
997 if (FSet.findLock(FactMan, Cp)) {
998 FSet.removeLock(FactMan, Cp);
999 FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
1000 !Cp, LK_Exclusive, loc));
1001 } else if (Handler) {
1002 Handler->handleUnmatchedUnlock(DiagKind, Cp.toString(), loc);
1007 /// Class which implements the core thread safety analysis routines.
1008 class ThreadSafetyAnalyzer {
1009 friend class BuildLockset;
1010 friend class threadSafety::BeforeSet;
1012 llvm::BumpPtrAllocator Bpa;
1013 threadSafety::til::MemRegionRef Arena;
1014 threadSafety::SExprBuilder SxBuilder;
1016 ThreadSafetyHandler &Handler;
1017 const CXXMethodDecl *CurrentMethod;
1018 LocalVariableMap LocalVarMap;
1019 FactManager FactMan;
1020 std::vector<CFGBlockInfo> BlockInfo;
1022 BeforeSet *GlobalBeforeSet;
1025 ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
1026 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
1028 bool inCurrentScope(const CapabilityExpr &CapE);
1030 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
1031 StringRef DiagKind, bool ReqAttr = false);
1032 void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
1033 SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
1034 StringRef DiagKind);
1036 template <typename AttrType>
1037 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1038 const NamedDecl *D, VarDecl *SelfDecl = nullptr);
1040 template <class AttrType>
1041 void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, const Expr *Exp,
1043 const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
1044 Expr *BrE, bool Neg);
1046 const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
1049 void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
1050 const CFGBlock* PredBlock,
1051 const CFGBlock *CurrBlock);
1053 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1054 SourceLocation JoinLoc,
1055 LockErrorKind LEK1, LockErrorKind LEK2,
1058 void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
1059 SourceLocation JoinLoc, LockErrorKind LEK1,
1061 intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
1064 void runAnalysis(AnalysisDeclContext &AC);
1069 /// Process acquired_before and acquired_after attributes on Vd.
1070 BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
1071 ThreadSafetyAnalyzer& Analyzer) {
1072 // Create a new entry for Vd.
1073 BeforeInfo *Info = nullptr;
1075 // Keep InfoPtr in its own scope in case BMap is modified later and the
1076 // reference becomes invalid.
1077 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1079 InfoPtr.reset(new BeforeInfo());
1080 Info = InfoPtr.get();
1083 for (const auto *At : Vd->attrs()) {
1084 switch (At->getKind()) {
1085 case attr::AcquiredBefore: {
1086 const auto *A = cast<AcquiredBeforeAttr>(At);
1088 // Read exprs from the attribute, and add them to BeforeVect.
1089 for (const auto *Arg : A->args()) {
1091 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1092 if (const ValueDecl *Cpvd = Cp.valueDecl()) {
1093 Info->Vect.push_back(Cpvd);
1094 const auto It = BMap.find(Cpvd);
1095 if (It == BMap.end())
1096 insertAttrExprs(Cpvd, Analyzer);
1101 case attr::AcquiredAfter: {
1102 const auto *A = cast<AcquiredAfterAttr>(At);
1104 // Read exprs from the attribute, and add them to BeforeVect.
1105 for (const auto *Arg : A->args()) {
1107 Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
1108 if (const ValueDecl *ArgVd = Cp.valueDecl()) {
1109 // Get entry for mutex listed in attribute
1110 BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
1111 ArgInfo->Vect.push_back(Vd);
1124 BeforeSet::BeforeInfo *
1125 BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
1126 ThreadSafetyAnalyzer &Analyzer) {
1127 auto It = BMap.find(Vd);
1128 BeforeInfo *Info = nullptr;
1129 if (It == BMap.end())
1130 Info = insertAttrExprs(Vd, Analyzer);
1132 Info = It->second.get();
1133 assert(Info && "BMap contained nullptr?");
1137 /// Return true if any mutexes in FSet are in the acquired_before set of Vd.
1138 void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
1139 const FactSet& FSet,
1140 ThreadSafetyAnalyzer& Analyzer,
1141 SourceLocation Loc, StringRef CapKind) {
1142 SmallVector<BeforeInfo*, 8> InfoVect;
1144 // Do a depth-first traversal of Vd.
1145 // Return true if there are cycles.
1146 std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
1150 BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
1152 if (Info->Visited == 1)
1155 if (Info->Visited == 2)
1158 if (Info->Vect.empty())
1161 InfoVect.push_back(Info);
1163 for (const auto *Vdb : Info->Vect) {
1164 // Exclude mutexes in our immediate before set.
1165 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1166 StringRef L1 = StartVd->getName();
1167 StringRef L2 = Vdb->getName();
1168 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1170 // Transitively search other before sets, and warn on cycles.
1171 if (traverse(Vdb)) {
1172 if (CycMap.find(Vd) == CycMap.end()) {
1173 CycMap.insert(std::make_pair(Vd, true));
1174 StringRef L1 = Vd->getName();
1175 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
1185 for (auto *Info : InfoVect)
1189 /// Gets the value decl pointer from DeclRefExprs or MemberExprs.
1190 static const ValueDecl *getValueDecl(const Expr *Exp) {
1191 if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1192 return getValueDecl(CE->getSubExpr());
1194 if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1195 return DR->getDecl();
1197 if (const auto *ME = dyn_cast<MemberExpr>(Exp))
1198 return ME->getMemberDecl();
1205 template <typename Ty>
1206 class has_arg_iterator_range {
1207 using yes = char[1];
1210 template <typename Inner>
1211 static yes& test(Inner *I, decltype(I->args()) * = nullptr);
1214 static no& test(...);
1217 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
1222 static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
1223 return A->getName();
1226 static StringRef ClassifyDiagnostic(QualType VDT) {
1227 // We need to look at the declaration of the type of the value to determine
1228 // which it is. The type should either be a record or a typedef, or a pointer
1229 // or reference thereof.
1230 if (const auto *RT = VDT->getAs<RecordType>()) {
1231 if (const auto *RD = RT->getDecl())
1232 if (const auto *CA = RD->getAttr<CapabilityAttr>())
1233 return ClassifyDiagnostic(CA);
1234 } else if (const auto *TT = VDT->getAs<TypedefType>()) {
1235 if (const auto *TD = TT->getDecl())
1236 if (const auto *CA = TD->getAttr<CapabilityAttr>())
1237 return ClassifyDiagnostic(CA);
1238 } else if (VDT->isPointerType() || VDT->isReferenceType())
1239 return ClassifyDiagnostic(VDT->getPointeeType());
1244 static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
1245 assert(VD && "No ValueDecl passed");
1247 // The ValueDecl is the declaration of a mutex or role (hopefully).
1248 return ClassifyDiagnostic(VD->getType());
1251 template <typename AttrTy>
1252 static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
1254 ClassifyDiagnostic(const AttrTy *A) {
1255 if (const ValueDecl *VD = getValueDecl(A->getArg()))
1256 return ClassifyDiagnostic(VD);
1260 template <typename AttrTy>
1261 static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
1263 ClassifyDiagnostic(const AttrTy *A) {
1264 for (const auto *Arg : A->args()) {
1265 if (const ValueDecl *VD = getValueDecl(Arg))
1266 return ClassifyDiagnostic(VD);
1271 bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
1274 if (const auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
1275 const auto *VD = P->clangDecl();
1277 return VD->getDeclContext() == CurrentMethod->getDeclContext();
1282 /// Add a new lock to the lockset, warning if the lock is already there.
1283 /// \param ReqAttr -- true if this is part of an initial Requires attribute.
1284 void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1285 std::unique_ptr<FactEntry> Entry,
1286 StringRef DiagKind, bool ReqAttr) {
1287 if (Entry->shouldIgnore())
1290 if (!ReqAttr && !Entry->negative()) {
1291 // look for the negative capability, and remove it from the fact set.
1292 CapabilityExpr NegC = !*Entry;
1293 const FactEntry *Nen = FSet.findLock(FactMan, NegC);
1295 FSet.removeLock(FactMan, NegC);
1298 if (inCurrentScope(*Entry) && !Entry->asserted())
1299 Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
1300 NegC.toString(), Entry->loc());
1304 // Check before/after constraints
1305 if (Handler.issueBetaWarnings() &&
1306 !Entry->asserted() && !Entry->declared()) {
1307 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
1308 Entry->loc(), DiagKind);
1311 // FIXME: Don't always warn when we have support for reentrant locks.
1312 if (const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
1313 if (!Entry->asserted())
1314 Cp->handleLock(FSet, FactMan, *Entry, Handler, DiagKind);
1316 FSet.addLock(FactMan, std::move(Entry));
1320 /// Remove a lock from the lockset, warning if the lock is not there.
1321 /// \param UnlockLoc The source location of the unlock (only used in error msg)
1322 void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
1323 SourceLocation UnlockLoc,
1324 bool FullyRemove, LockKind ReceivedKind,
1325 StringRef DiagKind) {
1326 if (Cp.shouldIgnore())
1329 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
1331 Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
1335 // Generic lock removal doesn't care about lock kind mismatches, but
1336 // otherwise diagnose when the lock kinds are mismatched.
1337 if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
1338 Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(), LDat->kind(),
1339 ReceivedKind, LDat->loc(), UnlockLoc);
1342 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
1346 /// Extract the list of mutexIDs from the attribute on an expression,
1347 /// and push them onto Mtxs, discarding any duplicates.
1348 template <typename AttrType>
1349 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1350 const Expr *Exp, const NamedDecl *D,
1351 VarDecl *SelfDecl) {
1352 if (Attr->args_size() == 0) {
1353 // The mutex held is the "this" object.
1354 CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
1355 if (Cp.isInvalid()) {
1356 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1360 if (!Cp.shouldIgnore())
1361 Mtxs.push_back_nodup(Cp);
1365 for (const auto *Arg : Attr->args()) {
1366 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
1367 if (Cp.isInvalid()) {
1368 warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
1372 if (!Cp.shouldIgnore())
1373 Mtxs.push_back_nodup(Cp);
1377 /// Extract the list of mutexIDs from a trylock attribute. If the
1378 /// trylock applies to the given edge, then push them onto Mtxs, discarding
1380 template <class AttrType>
1381 void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
1382 const Expr *Exp, const NamedDecl *D,
1383 const CFGBlock *PredBlock,
1384 const CFGBlock *CurrBlock,
1385 Expr *BrE, bool Neg) {
1386 // Find out which branch has the lock
1387 bool branch = false;
1388 if (const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1389 branch = BLE->getValue();
1390 else if (const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1391 branch = ILE->getValue().getBoolValue();
1393 int branchnum = branch ? 0 : 1;
1395 branchnum = !branchnum;
1397 // If we've taken the trylock branch, then add the lock
1399 for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
1400 SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
1401 if (*SI == CurrBlock && i == branchnum)
1402 getMutexIDs(Mtxs, Attr, Exp, D);
1406 static bool getStaticBooleanValue(Expr *E, bool &TCond) {
1407 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1410 } else if (const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1411 TCond = BLE->getValue();
1413 } else if (const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
1414 TCond = ILE->getValue().getBoolValue();
1416 } else if (auto *CE = dyn_cast<ImplicitCastExpr>(E))
1417 return getStaticBooleanValue(CE->getSubExpr(), TCond);
1421 // If Cond can be traced back to a function call, return the call expression.
1422 // The negate variable should be called with false, and will be set to true
1423 // if the function call is negated, e.g. if (!mu.tryLock(...))
1424 const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
1430 if (const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
1431 if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
1432 return getTrylockCallExpr(CallExp->getArg(0), C, Negate);
1435 else if (const auto *PE = dyn_cast<ParenExpr>(Cond))
1436 return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
1437 else if (const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
1438 return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
1439 else if (const auto *FE = dyn_cast<FullExpr>(Cond))
1440 return getTrylockCallExpr(FE->getSubExpr(), C, Negate);
1441 else if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1442 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
1443 return getTrylockCallExpr(E, C, Negate);
1445 else if (const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
1446 if (UOP->getOpcode() == UO_LNot) {
1448 return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
1452 else if (const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
1453 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1454 if (BOP->getOpcode() == BO_NE)
1458 if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
1459 if (!TCond) Negate = !Negate;
1460 return getTrylockCallExpr(BOP->getLHS(), C, Negate);
1463 if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
1464 if (!TCond) Negate = !Negate;
1465 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1469 if (BOP->getOpcode() == BO_LAnd) {
1470 // LHS must have been evaluated in a different block.
1471 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1473 if (BOP->getOpcode() == BO_LOr)
1474 return getTrylockCallExpr(BOP->getRHS(), C, Negate);
1476 } else if (const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
1478 if (getStaticBooleanValue(COP->getTrueExpr(), TCond) &&
1479 getStaticBooleanValue(COP->getFalseExpr(), FCond)) {
1480 if (TCond && !FCond)
1481 return getTrylockCallExpr(COP->getCond(), C, Negate);
1482 if (!TCond && FCond) {
1484 return getTrylockCallExpr(COP->getCond(), C, Negate);
1491 /// Find the lockset that holds on the edge between PredBlock
1492 /// and CurrBlock. The edge set is the exit set of PredBlock (passed
1493 /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
1494 void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
1495 const FactSet &ExitSet,
1496 const CFGBlock *PredBlock,
1497 const CFGBlock *CurrBlock) {
1500 const Stmt *Cond = PredBlock->getTerminatorCondition();
1501 // We don't acquire try-locks on ?: branches, only when its result is used.
1502 if (!Cond || isa<ConditionalOperator>(PredBlock->getTerminatorStmt()))
1505 bool Negate = false;
1506 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
1507 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1508 StringRef CapDiagKind = "mutex";
1510 const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
1514 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1515 if(!FunDecl || !FunDecl->hasAttrs())
1518 CapExprSet ExclusiveLocksToAdd;
1519 CapExprSet SharedLocksToAdd;
1521 // If the condition is a call to a Trylock function, then grab the attributes
1522 for (const auto *Attr : FunDecl->attrs()) {
1523 switch (Attr->getKind()) {
1524 case attr::TryAcquireCapability: {
1525 auto *A = cast<TryAcquireCapabilityAttr>(Attr);
1526 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1527 Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1529 CapDiagKind = ClassifyDiagnostic(A);
1532 case attr::ExclusiveTrylockFunction: {
1533 const auto *A = cast<ExclusiveTrylockFunctionAttr>(Attr);
1534 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
1535 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1536 CapDiagKind = ClassifyDiagnostic(A);
1539 case attr::SharedTrylockFunction: {
1540 const auto *A = cast<SharedTrylockFunctionAttr>(Attr);
1541 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
1542 PredBlock, CurrBlock, A->getSuccessValue(), Negate);
1543 CapDiagKind = ClassifyDiagnostic(A);
1551 // Add and remove locks.
1552 SourceLocation Loc = Exp->getExprLoc();
1553 for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1554 addLock(Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1557 for (const auto &SharedLockToAdd : SharedLocksToAdd)
1558 addLock(Result, std::make_unique<LockableFactEntry>(SharedLockToAdd,
1565 /// We use this class to visit different types of expressions in
1566 /// CFGBlocks, and build up the lockset.
1567 /// An expression may cause us to add or remove locks from the lockset, or else
1568 /// output error messages related to missing locks.
1569 /// FIXME: In future, we may be able to not inherit from a visitor.
1570 class BuildLockset : public ConstStmtVisitor<BuildLockset> {
1571 friend class ThreadSafetyAnalyzer;
1573 ThreadSafetyAnalyzer *Analyzer;
1575 LocalVariableMap::Context LVarCtx;
1579 void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
1580 Expr *MutexExp, ProtectedOperationKind POK,
1581 StringRef DiagKind, SourceLocation Loc);
1582 void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
1583 StringRef DiagKind);
1585 void checkAccess(const Expr *Exp, AccessKind AK,
1586 ProtectedOperationKind POK = POK_VarAccess);
1587 void checkPtAccess(const Expr *Exp, AccessKind AK,
1588 ProtectedOperationKind POK = POK_VarAccess);
1590 void handleCall(const Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
1591 void examineArguments(const FunctionDecl *FD,
1592 CallExpr::const_arg_iterator ArgBegin,
1593 CallExpr::const_arg_iterator ArgEnd,
1594 bool SkipFirstParam = false);
1597 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1598 : ConstStmtVisitor<BuildLockset>(), Analyzer(Anlzr), FSet(Info.EntrySet),
1599 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
1601 void VisitUnaryOperator(const UnaryOperator *UO);
1602 void VisitBinaryOperator(const BinaryOperator *BO);
1603 void VisitCastExpr(const CastExpr *CE);
1604 void VisitCallExpr(const CallExpr *Exp);
1605 void VisitCXXConstructExpr(const CXXConstructExpr *Exp);
1606 void VisitDeclStmt(const DeclStmt *S);
1611 /// Warn if the LSet does not contain a lock sufficient to protect access
1612 /// of at least the passed in AccessKind.
1613 void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
1614 AccessKind AK, Expr *MutexExp,
1615 ProtectedOperationKind POK,
1616 StringRef DiagKind, SourceLocation Loc) {
1617 LockKind LK = getLockKindFromAccessKind(AK);
1619 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1620 if (Cp.isInvalid()) {
1621 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1623 } else if (Cp.shouldIgnore()) {
1627 if (Cp.negative()) {
1628 // Negative capabilities act like locks excluded
1629 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1631 Analyzer->Handler.handleFunExcludesLock(
1632 DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
1636 // If this does not refer to a negative capability in the same class,
1638 if (!Analyzer->inCurrentScope(Cp))
1641 // Otherwise the negative requirement must be propagated to the caller.
1642 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1644 Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
1650 const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
1651 bool NoError = true;
1653 // No exact match found. Look for a partial match.
1654 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1656 // Warn that there's no precise match.
1657 std::string PartMatchStr = LDat->toString();
1658 StringRef PartMatchName(PartMatchStr);
1659 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1660 LK, Loc, &PartMatchName);
1662 // Warn that there's no match at all.
1663 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1668 // Make sure the mutex we found is the right kind.
1669 if (NoError && LDat && !LDat->isAtLeast(LK)) {
1670 Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
1675 /// Warn if the LSet contains the given lock.
1676 void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
1677 Expr *MutexExp, StringRef DiagKind) {
1678 CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
1679 if (Cp.isInvalid()) {
1680 warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
1682 } else if (Cp.shouldIgnore()) {
1686 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
1688 Analyzer->Handler.handleFunExcludesLock(
1689 DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
1693 /// Checks guarded_by and pt_guarded_by attributes.
1694 /// Whenever we identify an access (read or write) to a DeclRefExpr that is
1695 /// marked with guarded_by, we must ensure the appropriate mutexes are held.
1696 /// Similarly, we check if the access is to an expression that dereferences
1697 /// a pointer marked with pt_guarded_by.
1698 void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
1699 ProtectedOperationKind POK) {
1700 Exp = Exp->IgnoreImplicit()->IgnoreParenCasts();
1702 SourceLocation Loc = Exp->getExprLoc();
1704 // Local variables of reference type cannot be re-assigned;
1705 // map them to their initializer.
1706 while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1707 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1708 if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
1709 if (const auto *E = VD->getInit()) {
1710 // Guard against self-initialization. e.g., int &i = i;
1720 if (const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
1722 if (UO->getOpcode() == UO_Deref)
1723 checkPtAccess(UO->getSubExpr(), AK, POK);
1727 if (const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1728 checkPtAccess(AE->getLHS(), AK, POK);
1732 if (const auto *ME = dyn_cast<MemberExpr>(Exp)) {
1734 checkPtAccess(ME->getBase(), AK, POK);
1736 checkAccess(ME->getBase(), AK, POK);
1739 const ValueDecl *D = getValueDecl(Exp);
1740 if (!D || !D->hasAttrs())
1743 if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
1744 Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
1747 for (const auto *I : D->specific_attrs<GuardedByAttr>())
1748 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
1749 ClassifyDiagnostic(I), Loc);
1752 /// Checks pt_guarded_by and pt_guarded_var attributes.
1753 /// POK is the same operationKind that was passed to checkAccess.
1754 void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
1755 ProtectedOperationKind POK) {
1757 if (const auto *PE = dyn_cast<ParenExpr>(Exp)) {
1758 Exp = PE->getSubExpr();
1761 if (const auto *CE = dyn_cast<CastExpr>(Exp)) {
1762 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1763 // If it's an actual array, and not a pointer, then it's elements
1764 // are protected by GUARDED_BY, not PT_GUARDED_BY;
1765 checkAccess(CE->getSubExpr(), AK, POK);
1768 Exp = CE->getSubExpr();
1774 // Pass by reference warnings are under a different flag.
1775 ProtectedOperationKind PtPOK = POK_VarDereference;
1776 if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
1778 const ValueDecl *D = getValueDecl(Exp);
1779 if (!D || !D->hasAttrs())
1782 if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
1783 Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
1786 for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
1787 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
1788 ClassifyDiagnostic(I), Exp->getExprLoc());
1791 /// Process a function call, method call, constructor call,
1792 /// or destructor call. This involves looking at the attributes on the
1793 /// corresponding function/method/constructor/destructor, issuing warnings,
1794 /// and updating the locksets accordingly.
1796 /// FIXME: For classes annotated with one of the guarded annotations, we need
1797 /// to treat const method calls as reads and non-const method calls as writes,
1798 /// and check that the appropriate locks are held. Non-const method calls with
1799 /// the same signature as const method calls can be also treated as reads.
1801 void BuildLockset::handleCall(const Expr *Exp, const NamedDecl *D,
1803 SourceLocation Loc = Exp->getExprLoc();
1804 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1805 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1806 CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
1807 StringRef CapDiagKind = "mutex";
1809 // Figure out if we're constructing an object of scoped lockable class
1810 bool isScopedVar = false;
1812 if (const auto *CD = dyn_cast<const CXXConstructorDecl>(D)) {
1813 const CXXRecordDecl* PD = CD->getParent();
1814 if (PD && PD->hasAttr<ScopedLockableAttr>())
1819 for(const Attr *At : D->attrs()) {
1820 switch (At->getKind()) {
1821 // When we encounter a lock function, we need to add the lock to our
1823 case attr::AcquireCapability: {
1824 const auto *A = cast<AcquireCapabilityAttr>(At);
1825 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1826 : ExclusiveLocksToAdd,
1829 CapDiagKind = ClassifyDiagnostic(A);
1833 // An assert will add a lock to the lockset, but will not generate
1834 // a warning if it is already there, and will not generate a warning
1835 // if it is not removed.
1836 case attr::AssertExclusiveLock: {
1837 const auto *A = cast<AssertExclusiveLockAttr>(At);
1839 CapExprSet AssertLocks;
1840 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1841 for (const auto &AssertLock : AssertLocks)
1842 Analyzer->addLock(FSet,
1843 std::make_unique<LockableFactEntry>(
1844 AssertLock, LK_Exclusive, Loc, false, true),
1845 ClassifyDiagnostic(A));
1848 case attr::AssertSharedLock: {
1849 const auto *A = cast<AssertSharedLockAttr>(At);
1851 CapExprSet AssertLocks;
1852 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1853 for (const auto &AssertLock : AssertLocks)
1854 Analyzer->addLock(FSet,
1855 std::make_unique<LockableFactEntry>(
1856 AssertLock, LK_Shared, Loc, false, true),
1857 ClassifyDiagnostic(A));
1861 case attr::AssertCapability: {
1862 const auto *A = cast<AssertCapabilityAttr>(At);
1863 CapExprSet AssertLocks;
1864 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
1865 for (const auto &AssertLock : AssertLocks)
1866 Analyzer->addLock(FSet,
1867 std::make_unique<LockableFactEntry>(
1869 A->isShared() ? LK_Shared : LK_Exclusive, Loc,
1871 ClassifyDiagnostic(A));
1875 // When we encounter an unlock function, we need to remove unlocked
1876 // mutexes from the lockset, and flag a warning if they are not there.
1877 case attr::ReleaseCapability: {
1878 const auto *A = cast<ReleaseCapabilityAttr>(At);
1880 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
1881 else if (A->isShared())
1882 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
1884 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
1886 CapDiagKind = ClassifyDiagnostic(A);
1890 case attr::RequiresCapability: {
1891 const auto *A = cast<RequiresCapabilityAttr>(At);
1892 for (auto *Arg : A->args()) {
1893 warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
1894 POK_FunctionCall, ClassifyDiagnostic(A),
1896 // use for adopting a lock
1898 Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
1899 : ScopedExclusiveReqs,
1906 case attr::LocksExcluded: {
1907 const auto *A = cast<LocksExcludedAttr>(At);
1908 for (auto *Arg : A->args())
1909 warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
1913 // Ignore attributes unrelated to thread-safety
1919 // Remove locks first to allow lock upgrading/downgrading.
1920 // FIXME -- should only fully remove if the attribute refers to 'this'.
1921 bool Dtor = isa<CXXDestructorDecl>(D);
1922 for (const auto &M : ExclusiveLocksToRemove)
1923 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
1924 for (const auto &M : SharedLocksToRemove)
1925 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
1926 for (const auto &M : GenericLocksToRemove)
1927 Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
1930 for (const auto &M : ExclusiveLocksToAdd)
1931 Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(
1932 M, LK_Exclusive, Loc, isScopedVar),
1934 for (const auto &M : SharedLocksToAdd)
1935 Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(
1936 M, LK_Shared, Loc, isScopedVar),
1940 // Add the managing object as a dummy mutex, mapped to the underlying mutex.
1941 SourceLocation MLoc = VD->getLocation();
1942 DeclRefExpr DRE(VD->getASTContext(), VD, false, VD->getType(), VK_LValue,
1944 // FIXME: does this store a pointer to DRE?
1945 CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
1947 auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, MLoc);
1948 for (const auto &M : ExclusiveLocksToAdd)
1949 ScopedEntry->addExclusiveLock(M);
1950 for (const auto &M : ScopedExclusiveReqs)
1951 ScopedEntry->addExclusiveLock(M);
1952 for (const auto &M : SharedLocksToAdd)
1953 ScopedEntry->addSharedLock(M);
1954 for (const auto &M : ScopedSharedReqs)
1955 ScopedEntry->addSharedLock(M);
1956 for (const auto &M : ExclusiveLocksToRemove)
1957 ScopedEntry->addExclusiveUnlock(M);
1958 for (const auto &M : SharedLocksToRemove)
1959 ScopedEntry->addSharedUnlock(M);
1960 Analyzer->addLock(FSet, std::move(ScopedEntry), CapDiagKind);
1964 /// For unary operations which read and write a variable, we need to
1965 /// check whether we hold any required mutexes. Reads are checked in
1967 void BuildLockset::VisitUnaryOperator(const UnaryOperator *UO) {
1968 switch (UO->getOpcode()) {
1973 checkAccess(UO->getSubExpr(), AK_Written);
1980 /// For binary operations which assign to a variable (writes), we need to check
1981 /// whether we hold any required mutexes.
1982 /// FIXME: Deal with non-primitive types.
1983 void BuildLockset::VisitBinaryOperator(const BinaryOperator *BO) {
1984 if (!BO->isAssignmentOp())
1987 // adjust the context
1988 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1990 checkAccess(BO->getLHS(), AK_Written);
1993 /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
1994 /// need to ensure we hold any required mutexes.
1995 /// FIXME: Deal with non-primitive types.
1996 void BuildLockset::VisitCastExpr(const CastExpr *CE) {
1997 if (CE->getCastKind() != CK_LValueToRValue)
1999 checkAccess(CE->getSubExpr(), AK_Read);
2002 void BuildLockset::examineArguments(const FunctionDecl *FD,
2003 CallExpr::const_arg_iterator ArgBegin,
2004 CallExpr::const_arg_iterator ArgEnd,
2005 bool SkipFirstParam) {
2006 // Currently we can't do anything if we don't know the function declaration.
2010 // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
2011 // only turns off checking within the body of a function, but we also
2012 // use it to turn off checking in arguments to the function. This
2013 // could result in some false negatives, but the alternative is to
2014 // create yet another attribute.
2015 if (FD->hasAttr<NoThreadSafetyAnalysisAttr>())
2018 const ArrayRef<ParmVarDecl *> Params = FD->parameters();
2019 auto Param = Params.begin();
2023 // There can be default arguments, so we stop when one iterator is at end().
2024 for (auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd;
2026 QualType Qt = (*Param)->getType();
2027 if (Qt->isReferenceType())
2028 checkAccess(*Arg, AK_Read, POK_PassByRef);
2032 void BuildLockset::VisitCallExpr(const CallExpr *Exp) {
2033 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2034 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
2035 // ME can be null when calling a method pointer
2036 const CXXMethodDecl *MD = CE->getMethodDecl();
2039 if (ME->isArrow()) {
2041 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2042 else // FIXME -- should be AK_Written
2043 checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
2046 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2047 else // FIXME -- should be AK_Written
2048 checkAccess(CE->getImplicitObjectArgument(), AK_Read);
2052 examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
2053 } else if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2054 auto OEop = OE->getOperator();
2057 const Expr *Target = OE->getArg(0);
2058 const Expr *Source = OE->getArg(1);
2059 checkAccess(Target, AK_Written);
2060 checkAccess(Source, AK_Read);
2066 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
2067 // Grrr. operator* can be multiplication...
2068 checkPtAccess(OE->getArg(0), AK_Read);
2072 // TODO: get rid of this, and rely on pass-by-ref instead.
2073 const Expr *Obj = OE->getArg(0);
2074 checkAccess(Obj, AK_Read);
2075 // Check the remaining arguments. For method operators, the first
2076 // argument is the implicit self argument, and doesn't appear in the
2077 // FunctionDecl, but for non-methods it does.
2078 const FunctionDecl *FD = OE->getDirectCallee();
2079 examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
2080 /*SkipFirstParam*/ !isa<CXXMethodDecl>(FD));
2085 examineArguments(Exp->getDirectCallee(), Exp->arg_begin(), Exp->arg_end());
2088 auto *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
2089 if(!D || !D->hasAttrs())
2094 void BuildLockset::VisitCXXConstructExpr(const CXXConstructExpr *Exp) {
2095 const CXXConstructorDecl *D = Exp->getConstructor();
2096 if (D && D->isCopyConstructor()) {
2097 const Expr* Source = Exp->getArg(0);
2098 checkAccess(Source, AK_Read);
2100 examineArguments(D, Exp->arg_begin(), Exp->arg_end());
2104 static CXXConstructorDecl *
2105 findConstructorForByValueReturn(const CXXRecordDecl *RD) {
2106 // Prefer a move constructor over a copy constructor. If there's more than
2107 // one copy constructor or more than one move constructor, we arbitrarily
2108 // pick the first declared such constructor rather than trying to guess which
2109 // one is more appropriate.
2110 CXXConstructorDecl *CopyCtor = nullptr;
2111 for (auto *Ctor : RD->ctors()) {
2112 if (Ctor->isDeleted())
2114 if (Ctor->isMoveConstructor())
2116 if (!CopyCtor && Ctor->isCopyConstructor())
2122 static Expr *buildFakeCtorCall(CXXConstructorDecl *CD, ArrayRef<Expr *> Args,
2123 SourceLocation Loc) {
2124 ASTContext &Ctx = CD->getASTContext();
2125 return CXXConstructExpr::Create(Ctx, Ctx.getRecordType(CD->getParent()), Loc,
2126 CD, true, Args, false, false, false, false,
2127 CXXConstructExpr::CK_Complete,
2128 SourceRange(Loc, Loc));
2131 void BuildLockset::VisitDeclStmt(const DeclStmt *S) {
2132 // adjust the context
2133 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2135 for (auto *D : S->getDeclGroup()) {
2136 if (auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2137 Expr *E = VD->getInit();
2140 E = E->IgnoreParens();
2142 // handle constructors that involve temporaries
2143 if (auto *EWC = dyn_cast<ExprWithCleanups>(E))
2144 E = EWC->getSubExpr();
2145 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2146 E = BTE->getSubExpr();
2148 if (const auto *CE = dyn_cast<CXXConstructExpr>(E)) {
2149 const auto *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
2150 if (!CtorD || !CtorD->hasAttrs())
2152 handleCall(E, CtorD, VD);
2153 } else if (isa<CallExpr>(E) && E->isRValue()) {
2154 // If the object is initialized by a function call that returns a
2155 // scoped lockable by value, use the attributes on the copy or move
2156 // constructor to figure out what effect that should have on the
2158 // FIXME: Is this really the best way to handle this situation?
2159 auto *RD = E->getType()->getAsCXXRecordDecl();
2160 if (!RD || !RD->hasAttr<ScopedLockableAttr>())
2162 CXXConstructorDecl *CtorD = findConstructorForByValueReturn(RD);
2163 if (!CtorD || !CtorD->hasAttrs())
2165 handleCall(buildFakeCtorCall(CtorD, {E}, E->getBeginLoc()), CtorD, VD);
2171 /// Compute the intersection of two locksets and issue warnings for any
2172 /// locks in the symmetric difference.
2174 /// This function is used at a merge point in the CFG when comparing the lockset
2175 /// of each branch being merged. For example, given the following sequence:
2176 /// A; if () then B; else C; D; we need to check that the lockset after B and C
2177 /// are the same. In the event of a difference, we use the intersection of these
2178 /// two locksets at the start of D.
2180 /// \param FSet1 The first lockset.
2181 /// \param FSet2 The second lockset.
2182 /// \param JoinLoc The location of the join point for error reporting
2183 /// \param LEK1 The error message to report if a mutex is missing from LSet1
2184 /// \param LEK2 The error message to report if a mutex is missing from Lset2
2185 void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
2186 const FactSet &FSet2,
2187 SourceLocation JoinLoc,
2191 FactSet FSet1Orig = FSet1;
2193 // Find locks in FSet2 that conflict or are not in FSet1, and warn.
2194 for (const auto &Fact : FSet2) {
2195 const FactEntry *LDat1 = nullptr;
2196 const FactEntry *LDat2 = &FactMan[Fact];
2197 FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
2198 if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
2201 if (LDat1->kind() != LDat2->kind()) {
2202 Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
2203 LDat2->loc(), LDat1->loc());
2204 if (Modify && LDat1->kind() != LK_Exclusive) {
2205 // Take the exclusive lock, which is the one in FSet2.
2209 else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
2210 // The non-asserted lock in FSet2 is the one we want to track.
2214 LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
2219 // Find locks in FSet1 that are not in FSet2, and remove them.
2220 for (const auto &Fact : FSet1Orig) {
2221 const FactEntry *LDat1 = &FactMan[Fact];
2222 const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
2225 LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
2228 FSet1.removeLock(FactMan, *LDat1);
2233 // Return true if block B never continues to its successors.
2234 static bool neverReturns(const CFGBlock *B) {
2235 if (B->hasNoReturnElement())
2240 CFGElement Last = B->back();
2241 if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
2242 if (isa<CXXThrowExpr>(S->getStmt()))
2248 /// Check a function's CFG for thread-safety violations.
2250 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2251 /// at the end of each block, and issue warnings for thread safety violations.
2252 /// Each block in the CFG is traversed exactly once.
2253 void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
2254 // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
2255 // For now, we just use the walker to set things up.
2256 threadSafety::CFGWalker walker;
2257 if (!walker.init(AC))
2260 // AC.dumpCFG(true);
2261 // threadSafety::printSCFG(walker);
2263 CFG *CFGraph = walker.getGraph();
2264 const NamedDecl *D = walker.getDecl();
2265 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
2266 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
2268 if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
2271 // FIXME: Do something a bit more intelligent inside constructor and
2272 // destructor code. Constructors and destructors must assume unique access
2273 // to 'this', so checks on member variable access is disabled, but we should
2274 // still enable checks on other objects.
2275 if (isa<CXXConstructorDecl>(D))
2276 return; // Don't check inside constructors.
2277 if (isa<CXXDestructorDecl>(D))
2278 return; // Don't check inside destructors.
2280 Handler.enterFunction(CurrentFunction);
2282 BlockInfo.resize(CFGraph->getNumBlockIDs(),
2283 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2285 // We need to explore the CFG via a "topological" ordering.
2286 // That way, we will be guaranteed to have information about required
2287 // predecessor locksets when exploring a new block.
2288 const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
2289 PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
2291 // Mark entry block as reachable
2292 BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
2294 // Compute SSA names for local variables
2295 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2297 // Fill in source locations for all CFGBlocks.
2298 findBlockLocations(CFGraph, SortedGraph, BlockInfo);
2300 CapExprSet ExclusiveLocksAcquired;
2301 CapExprSet SharedLocksAcquired;
2302 CapExprSet LocksReleased;
2304 // Add locks from exclusive_locks_required and shared_locks_required
2305 // to initial lockset. Also turn off checking for lock and unlock functions.
2306 // FIXME: is there a more intelligent way to check lock/unlock functions?
2307 if (!SortedGraph->empty() && D->hasAttrs()) {
2308 const CFGBlock *FirstBlock = *SortedGraph->begin();
2309 FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
2311 CapExprSet ExclusiveLocksToAdd;
2312 CapExprSet SharedLocksToAdd;
2313 StringRef CapDiagKind = "mutex";
2315 SourceLocation Loc = D->getLocation();
2316 for (const auto *Attr : D->attrs()) {
2317 Loc = Attr->getLocation();
2318 if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
2319 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2321 CapDiagKind = ClassifyDiagnostic(A);
2322 } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
2323 // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
2324 // We must ignore such methods.
2325 if (A->args_size() == 0)
2327 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2329 getMutexIDs(LocksReleased, A, nullptr, D);
2330 CapDiagKind = ClassifyDiagnostic(A);
2331 } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
2332 if (A->args_size() == 0)
2334 getMutexIDs(A->isShared() ? SharedLocksAcquired
2335 : ExclusiveLocksAcquired,
2337 CapDiagKind = ClassifyDiagnostic(A);
2338 } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
2339 // Don't try to check trylock functions for now.
2341 } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
2342 // Don't try to check trylock functions for now.
2344 } else if (isa<TryAcquireCapabilityAttr>(Attr)) {
2345 // Don't try to check trylock functions for now.
2350 // FIXME -- Loc can be wrong here.
2351 for (const auto &Mu : ExclusiveLocksToAdd) {
2352 auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
2353 Entry->setDeclared(true);
2354 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2356 for (const auto &Mu : SharedLocksToAdd) {
2357 auto Entry = std::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
2358 Entry->setDeclared(true);
2359 addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
2363 for (const auto *CurrBlock : *SortedGraph) {
2364 unsigned CurrBlockID = CurrBlock->getBlockID();
2365 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2367 // Use the default initial lockset in case there are no predecessors.
2368 VisitedBlocks.insert(CurrBlock);
2370 // Iterate through the predecessor blocks and warn if the lockset for all
2371 // predecessors is not the same. We take the entry lockset of the current
2372 // block to be the intersection of all previous locksets.
2373 // FIXME: By keeping the intersection, we may output more errors in future
2374 // for a lock which is not in the intersection, but was in the union. We
2375 // may want to also keep the union in future. As an example, let's say
2376 // the intersection contains Mutex L, and the union contains L and M.
2377 // Later we unlock M. At this point, we would output an error because we
2378 // never locked M; although the real error is probably that we forgot to
2379 // lock M on all code paths. Conversely, let's say that later we lock M.
2380 // In this case, we should compare against the intersection instead of the
2381 // union because the real error is probably that we forgot to unlock M on
2383 bool LocksetInitialized = false;
2384 SmallVector<CFGBlock *, 8> SpecialBlocks;
2385 for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
2386 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
2387 // if *PI -> CurrBlock is a back edge
2388 if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
2391 unsigned PrevBlockID = (*PI)->getBlockID();
2392 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2394 // Ignore edges from blocks that can't return.
2395 if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
2398 // Okay, we can reach this block from the entry.
2399 CurrBlockInfo->Reachable = true;
2401 // If the previous block ended in a 'continue' or 'break' statement, then
2402 // a difference in locksets is probably due to a bug in that block, rather
2403 // than in some other predecessor. In that case, keep the other
2404 // predecessor's lockset.
2405 if (const Stmt *Terminator = (*PI)->getTerminatorStmt()) {
2406 if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
2407 SpecialBlocks.push_back(*PI);
2412 FactSet PrevLockset;
2413 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2415 if (!LocksetInitialized) {
2416 CurrBlockInfo->EntrySet = PrevLockset;
2417 LocksetInitialized = true;
2419 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2420 CurrBlockInfo->EntryLoc,
2421 LEK_LockedSomePredecessors);
2425 // Skip rest of block if it's not reachable.
2426 if (!CurrBlockInfo->Reachable)
2429 // Process continue and break blocks. Assume that the lockset for the
2430 // resulting block is unaffected by any discrepancies in them.
2431 for (const auto *PrevBlock : SpecialBlocks) {
2432 unsigned PrevBlockID = PrevBlock->getBlockID();
2433 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2435 if (!LocksetInitialized) {
2436 CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
2437 LocksetInitialized = true;
2439 // Determine whether this edge is a loop terminator for diagnostic
2440 // purposes. FIXME: A 'break' statement might be a loop terminator, but
2441 // it might also be part of a switch. Also, a subsequent destructor
2442 // might add to the lockset, in which case the real issue might be a
2443 // double lock on the other path.
2444 const Stmt *Terminator = PrevBlock->getTerminatorStmt();
2445 bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
2447 FactSet PrevLockset;
2448 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
2449 PrevBlock, CurrBlock);
2451 // Do not update EntrySet.
2452 intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
2453 PrevBlockInfo->ExitLoc,
2454 IsLoop ? LEK_LockedSomeLoopIterations
2455 : LEK_LockedSomePredecessors,
2460 BuildLockset LocksetBuilder(this, *CurrBlockInfo);
2462 // Visit all the statements in the basic block.
2463 for (const auto &BI : *CurrBlock) {
2464 switch (BI.getKind()) {
2465 case CFGElement::Statement: {
2466 CFGStmt CS = BI.castAs<CFGStmt>();
2467 LocksetBuilder.Visit(CS.getStmt());
2470 // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
2471 case CFGElement::AutomaticObjectDtor: {
2472 CFGAutomaticObjDtor AD = BI.castAs<CFGAutomaticObjDtor>();
2473 const auto *DD = AD.getDestructorDecl(AC.getASTContext());
2474 if (!DD->hasAttrs())
2477 // Create a dummy expression,
2478 auto *VD = const_cast<VarDecl *>(AD.getVarDecl());
2479 DeclRefExpr DRE(VD->getASTContext(), VD, false,
2480 VD->getType().getNonReferenceType(), VK_LValue,
2481 AD.getTriggerStmt()->getEndLoc());
2482 LocksetBuilder.handleCall(&DRE, DD);
2489 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2491 // For every back edge from CurrBlock (the end of the loop) to another block
2492 // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
2493 // the one held at the beginning of FirstLoopBlock. We can look up the
2494 // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
2495 for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
2496 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2497 // if CurrBlock -> *SI is *not* a back edge
2498 if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
2501 CFGBlock *FirstLoopBlock = *SI;
2502 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
2503 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2504 intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
2506 LEK_LockedSomeLoopIterations,
2511 CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
2512 CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
2514 // Skip the final check if the exit block is unreachable.
2515 if (!Final->Reachable)
2518 // By default, we expect all locks held on entry to be held on exit.
2519 FactSet ExpectedExitSet = Initial->EntrySet;
2521 // Adjust the expected exit set by adding or removing locks, as declared
2522 // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
2523 // issue the appropriate warning.
2524 // FIXME: the location here is not quite right.
2525 for (const auto &Lock : ExclusiveLocksAcquired)
2526 ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2527 Lock, LK_Exclusive, D->getLocation()));
2528 for (const auto &Lock : SharedLocksAcquired)
2529 ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2530 Lock, LK_Shared, D->getLocation()));
2531 for (const auto &Lock : LocksReleased)
2532 ExpectedExitSet.removeLock(FactMan, Lock);
2534 // FIXME: Should we call this function for all blocks which exit the function?
2535 intersectAndWarn(ExpectedExitSet, Final->ExitSet,
2537 LEK_LockedAtEndOfFunction,
2538 LEK_NotLockedAtEndOfFunction,
2541 Handler.leaveFunction(CurrentFunction);
2544 /// Check a function's CFG for thread-safety violations.
2546 /// We traverse the blocks in the CFG, compute the set of mutexes that are held
2547 /// at the end of each block, and issue warnings for thread safety violations.
2548 /// Each block in the CFG is traversed exactly once.
2549 void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
2550 ThreadSafetyHandler &Handler,
2553 *BSet = new BeforeSet;
2554 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
2555 Analyzer.runAnalysis(AC);
2558 void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
2560 /// Helper function that returns a LockKind required for the given level
2562 LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
2567 return LK_Exclusive;
2569 llvm_unreachable("Unknown AccessKind");