40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseMap.h"
42#include "llvm/ADT/ImmutableMap.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/SmallVector.h"
45#include "llvm/ADT/StringRef.h"
46#include "llvm/Support/Allocator.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/Support/raw_ostream.h"
62using namespace threadSafety;
70 const Expr *DeclExp, StringRef Kind) {
84class CapExprSet :
public SmallVector<CapabilityExpr, 4> {
119 SourceKind Source : 8;
128 virtual ~FactEntry() =
default;
133 bool asserted()
const {
return Source == Asserted; }
134 bool declared()
const {
return Source == Declared; }
135 bool managed()
const {
return Source == Managed; }
138 handleRemovalFromIntersection(
const FactSet &FSet, FactManager &FactMan,
141 virtual void handleLock(FactSet &FSet, FactManager &FactMan,
142 const FactEntry &entry,
144 virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
155using FactID =
unsigned short;
161 std::vector<std::unique_ptr<const FactEntry>> Facts;
164 FactID newFact(std::unique_ptr<FactEntry> Entry) {
165 Facts.push_back(std::move(Entry));
166 return static_cast<unsigned short>(Facts.size() - 1);
169 const FactEntry &operator[](FactID F)
const {
return *Facts[F]; }
186 using iterator = FactVec::iterator;
187 using const_iterator = FactVec::const_iterator;
189 iterator begin() {
return FactIDs.begin(); }
190 const_iterator begin()
const {
return FactIDs.begin(); }
192 iterator end() {
return FactIDs.end(); }
193 const_iterator end()
const {
return FactIDs.end(); }
195 bool isEmpty()
const {
return FactIDs.size() == 0; }
198 bool isEmpty(FactManager &FactMan)
const {
199 for (
const auto FID : *
this) {
200 if (!FactMan[FID].negative())
206 void addLockByID(FactID ID) { FactIDs.push_back(ID); }
208 FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
209 FactID F = FM.newFact(std::move(Entry));
210 FactIDs.push_back(F);
215 unsigned n = FactIDs.size();
219 for (
unsigned i = 0; i < n-1; ++i) {
220 if (FM[FactIDs[i]].
matches(CapE)) {
221 FactIDs[i] = FactIDs[n-1];
226 if (FM[FactIDs[n-1]].
matches(CapE)) {
233 iterator findLockIter(FactManager &FM,
const CapabilityExpr &CapE) {
234 return std::find_if(begin(), end(), [&](FactID ID) {
235 return FM[
ID].matches(CapE);
239 const FactEntry *findLock(FactManager &FM,
const CapabilityExpr &CapE)
const {
240 auto I = std::find_if(begin(), end(), [&](FactID ID) {
241 return FM[
ID].matches(CapE);
243 return I != end() ? &FM[*I] :
nullptr;
246 const FactEntry *findLockUniv(FactManager &FM,
248 auto I = std::find_if(begin(), end(), [&](FactID ID) ->
bool {
249 return FM[
ID].matchesUniv(CapE);
251 return I != end() ? &FM[*I] :
nullptr;
254 const FactEntry *findPartialMatch(FactManager &FM,
256 auto I = std::find_if(begin(), end(), [&](FactID ID) ->
bool {
257 return FM[
ID].partiallyMatches(CapE);
259 return I != end() ? &FM[*I] :
nullptr;
262 bool containsMutexDecl(FactManager &FM,
const ValueDecl* Vd)
const {
263 auto I = std::find_if(begin(), end(), [&](FactID ID) ->
bool {
264 return FM[
ID].valueDecl() == Vd;
270class ThreadSafetyAnalyzer;
275namespace threadSafety {
285 BeforeInfo() =
default;
286 BeforeInfo(BeforeInfo &&) =
default;
290 llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>;
291 using CycleMap = llvm::DenseMap<const ValueDecl *, bool>;
297 ThreadSafetyAnalyzer& Analyzer);
300 ThreadSafetyAnalyzer &Analyzer);
304 ThreadSafetyAnalyzer& Analyzer,
317class LocalVariableMap;
319using LocalVarContext = llvm::ImmutableMap<const NamedDecl *, unsigned>;
322enum CFGBlockSide { CBS_Entry, CBS_Exit };
335 LocalVarContext EntryContext;
338 LocalVarContext ExitContext;
350 bool Reachable =
false;
352 const FactSet &getSet(CFGBlockSide Side)
const {
353 return Side == CBS_Entry ? EntrySet : ExitSet;
357 return Side == CBS_Entry ? EntryLoc : ExitLoc;
361 CFGBlockInfo(LocalVarContext EmptyCtx)
362 : EntryContext(EmptyCtx), ExitContext(EmptyCtx) {}
365 static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
381class LocalVariableMap {
383 using Context = LocalVarContext;
389 struct VarDefinition {
391 friend class LocalVariableMap;
397 const Expr *Exp =
nullptr;
405 bool isReference() {
return !Exp; }
410 :
Dec(D), Exp(E), Ctx(
C) {}
413 VarDefinition(
const NamedDecl *D,
unsigned R, Context
C)
414 :
Dec(D), Ref(R), Ctx(
C) {}
418 Context::Factory ContextFactory;
419 std::vector<VarDefinition> VarDefinitions;
420 std::vector<std::pair<const Stmt *, Context>> SavedContexts;
425 VarDefinitions.push_back(VarDefinition(
nullptr, 0u, getEmptyContext()));
429 const VarDefinition* lookup(
const NamedDecl *D, Context Ctx) {
430 const unsigned *i = Ctx.lookup(D);
433 assert(*i < VarDefinitions.size());
434 return &VarDefinitions[*i];
441 const unsigned *
P = Ctx.lookup(D);
447 if (VarDefinitions[i].Exp) {
448 Ctx = VarDefinitions[i].Ctx;
449 return VarDefinitions[i].Exp;
451 i = VarDefinitions[i].Ref;
456 Context getEmptyContext() {
return ContextFactory.getEmptyMap(); }
461 Context getNextContext(
unsigned &CtxIndex,
const Stmt *S, Context
C) {
462 if (SavedContexts[CtxIndex+1].first == S) {
464 Context Result = SavedContexts[CtxIndex].second;
470 void dumpVarDefinitionName(
unsigned i) {
472 llvm::errs() <<
"Undefined";
477 llvm::errs() <<
"<<NULL>>";
480 Dec->printName(llvm::errs());
481 llvm::errs() <<
"." << i <<
" " << ((
const void*) Dec);
486 for (
unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
487 const Expr *Exp = VarDefinitions[i].Exp;
488 unsigned Ref = VarDefinitions[i].Ref;
490 dumpVarDefinitionName(i);
491 llvm::errs() <<
" = ";
492 if (Exp) Exp->
dump();
494 dumpVarDefinitionName(Ref);
495 llvm::errs() <<
"\n";
501 void dumpContext(Context
C) {
502 for (Context::iterator I =
C.begin(), E =
C.end(); I != E; ++I) {
505 const unsigned *i =
C.lookup(D);
506 llvm::errs() <<
" -> ";
507 dumpVarDefinitionName(*i);
508 llvm::errs() <<
"\n";
514 std::vector<CFGBlockInfo> &BlockInfo);
517 friend class VarMapBuilder;
520 unsigned getContextIndex() {
return SavedContexts.size()-1; }
523 void saveContext(
const Stmt *S, Context
C) {
524 SavedContexts.push_back(std::make_pair(S,
C));
529 Context addDefinition(
const NamedDecl *D,
const Expr *Exp, Context Ctx) {
530 assert(!Ctx.contains(D));
531 unsigned newID = VarDefinitions.size();
532 Context NewCtx = ContextFactory.add(Ctx, D, newID);
533 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
538 Context addReference(
const NamedDecl *D,
unsigned i, Context Ctx) {
539 unsigned newID = VarDefinitions.size();
540 Context NewCtx = ContextFactory.add(Ctx, D, newID);
541 VarDefinitions.push_back(VarDefinition(D, i, Ctx));
547 Context updateDefinition(
const NamedDecl *D,
Expr *Exp, Context Ctx) {
548 if (Ctx.contains(D)) {
549 unsigned newID = VarDefinitions.size();
550 Context NewCtx = ContextFactory.remove(Ctx, D);
551 NewCtx = ContextFactory.add(NewCtx, D, newID);
552 VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
560 Context clearDefinition(
const NamedDecl *D, Context Ctx) {
561 Context NewCtx = Ctx;
562 if (NewCtx.contains(D)) {
563 NewCtx = ContextFactory.remove(NewCtx, D);
564 NewCtx = ContextFactory.add(NewCtx, D, 0);
570 Context removeDefinition(
const NamedDecl *D, Context Ctx) {
571 Context NewCtx = Ctx;
572 if (NewCtx.contains(D)) {
573 NewCtx = ContextFactory.remove(NewCtx, D);
578 Context intersectContexts(Context C1, Context C2);
579 Context createReferenceContext(Context
C);
580 void intersectBackEdge(Context C1, Context C2);
586CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
587 return CFGBlockInfo(M.getEmptyContext());
595 LocalVariableMap* VMap;
596 LocalVariableMap::Context Ctx;
598 VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context
C)
599 : VMap(VM), Ctx(
C) {}
601 void VisitDeclStmt(
const DeclStmt *S);
608void VarMapBuilder::VisitDeclStmt(
const DeclStmt *S) {
609 bool modifiedCtx =
false;
611 for (
const auto *D : DGrp) {
612 if (
const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
613 const Expr *E = VD->getInit();
618 Ctx = VMap->addDefinition(VD, E, Ctx);
624 VMap->saveContext(S, Ctx);
628void VarMapBuilder::VisitBinaryOperator(
const BinaryOperator *BO) {
635 if (
const auto *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
637 if (Ctx.lookup(VDec)) {
639 Ctx = VMap->updateDefinition(VDec, BO->
getRHS(), Ctx);
642 Ctx = VMap->clearDefinition(VDec, Ctx);
643 VMap->saveContext(BO, Ctx);
651LocalVariableMap::Context
652LocalVariableMap::intersectContexts(Context C1, Context C2) {
654 for (
const auto &
P : C1) {
656 const unsigned *i2 = C2.lookup(Dec);
658 Result = removeDefinition(Dec, Result);
659 else if (*i2 !=
P.second)
660 Result = clearDefinition(Dec, Result);
668LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context
C) {
669 Context Result = getEmptyContext();
670 for (
const auto &
P :
C)
671 Result = addReference(
P.first,
P.second, Result);
678void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
679 for (
const auto &
P : C1) {
680 unsigned i1 =
P.second;
681 VarDefinition *VDef = &VarDefinitions[i1];
682 assert(VDef->isReference());
684 const unsigned *i2 = C2.lookup(
P.first);
685 if (!i2 || (*i2 != i1))
727void LocalVariableMap::traverseCFG(
CFG *CFGraph,
729 std::vector<CFGBlockInfo> &BlockInfo) {
732 for (
const auto *CurrBlock : *SortedGraph) {
733 unsigned CurrBlockID = CurrBlock->getBlockID();
734 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
736 VisitedBlocks.insert(CurrBlock);
739 bool HasBackEdges =
false;
742 PE = CurrBlock->pred_end(); PI != PE; ++PI) {
744 if (*PI ==
nullptr || !VisitedBlocks.alreadySet(*PI)) {
749 unsigned PrevBlockID = (*PI)->getBlockID();
750 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
753 CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
757 CurrBlockInfo->EntryContext =
758 intersectContexts(CurrBlockInfo->EntryContext,
759 PrevBlockInfo->ExitContext);
766 CurrBlockInfo->EntryContext =
767 createReferenceContext(CurrBlockInfo->EntryContext);
770 saveContext(
nullptr, CurrBlockInfo->EntryContext);
771 CurrBlockInfo->EntryIndex = getContextIndex();
774 VarMapBuilder VMapBuilder(
this, CurrBlockInfo->EntryContext);
775 for (
const auto &BI : *CurrBlock) {
776 switch (BI.getKind()) {
779 VMapBuilder.Visit(CS.
getStmt());
786 CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
790 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
792 if (*SI ==
nullptr || !VisitedBlocks.alreadySet(*SI))
796 Context LoopBegin = BlockInfo[FirstLoopBlock->
getBlockID()].EntryContext;
797 Context LoopEnd = CurrBlockInfo->ExitContext;
798 intersectBackEdge(LoopBegin, LoopEnd);
804 saveContext(
nullptr, BlockInfo[exitID].ExitContext);
811 std::vector<CFGBlockInfo> &BlockInfo) {
812 for (
const auto *CurrBlock : *SortedGraph) {
813 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
817 if (
const Stmt *S = CurrBlock->getTerminatorStmt()) {
818 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getBeginLoc();
821 BE = CurrBlock->rend(); BI != BE; ++BI) {
823 if (std::optional<CFGStmt> CS = BI->getAs<
CFGStmt>()) {
824 CurrBlockInfo->ExitLoc = CS->getStmt()->getBeginLoc();
830 if (CurrBlockInfo->ExitLoc.isValid()) {
833 for (
const auto &BI : *CurrBlock) {
835 if (std::optional<CFGStmt> CS = BI.getAs<
CFGStmt>()) {
836 CurrBlockInfo->EntryLoc = CS->getStmt()->getBeginLoc();
840 }
else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
841 CurrBlock != &CFGraph->
getExit()) {
844 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
845 BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
846 }
else if (CurrBlock->succ_size() == 1 && *CurrBlock->succ_begin()) {
849 CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
850 BlockInfo[(*CurrBlock->succ_begin())->getBlockID()].EntryLoc;
857class LockableFactEntry :
public FactEntry {
860 SourceKind Src = Acquired)
861 : FactEntry(CE, LK, Loc, Src) {}
864 handleRemovalFromIntersection(
const FactSet &FSet, FactManager &FactMan,
867 if (!asserted() && !negative() && !isUniversal()) {
873 void handleLock(FactSet &FSet, FactManager &FactMan,
const FactEntry &entry,
879 void handleUnlock(FactSet &FSet, FactManager &FactMan,
883 FSet.removeLock(FactMan, Cp);
885 FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
891class ScopedLockableFactEntry :
public FactEntry {
893 enum UnderlyingCapabilityKind {
896 UCK_ReleasedExclusive,
899 struct UnderlyingCapability {
901 UnderlyingCapabilityKind
Kind;
911 UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_Acquired});
915 UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedExclusive});
919 UnderlyingMutexes.push_back(UnderlyingCapability{M, UCK_ReleasedShared});
923 handleRemovalFromIntersection(
const FactSet &FSet, FactManager &FactMan,
926 for (
const auto &UnderlyingMutex : UnderlyingMutexes) {
927 const auto *Entry = FSet.findLock(FactMan, UnderlyingMutex.Cap);
928 if ((UnderlyingMutex.Kind == UCK_Acquired && Entry) ||
929 (UnderlyingMutex.Kind != UCK_Acquired && !Entry)) {
933 UnderlyingMutex.Cap.toString(), loc(),
939 void handleLock(FactSet &FSet, FactManager &FactMan,
const FactEntry &entry,
941 for (
const auto &UnderlyingMutex : UnderlyingMutexes) {
942 if (UnderlyingMutex.Kind == UCK_Acquired)
943 lock(FSet, FactMan, UnderlyingMutex.Cap, entry.kind(), entry.loc(),
946 unlock(FSet, FactMan, UnderlyingMutex.Cap, entry.loc(), &Handler);
950 void handleUnlock(FactSet &FSet, FactManager &FactMan,
954 assert(!Cp.
negative() &&
"Managing object cannot be negative.");
955 for (
const auto &UnderlyingMutex : UnderlyingMutexes) {
959 if (UnderlyingMutex.Kind == UCK_Acquired) {
960 unlock(FSet, FactMan, UnderlyingMutex.Cap, UnlockLoc, TSHandler);
962 LockKind kind = UnderlyingMutex.Kind == UCK_ReleasedShared
965 lock(FSet, FactMan, UnderlyingMutex.Cap, kind, UnlockLoc, TSHandler);
969 FSet.removeLock(FactMan, Cp);
973 void lock(FactSet &FSet, FactManager &FactMan,
const CapabilityExpr &Cp,
976 if (
const FactEntry *Fact = FSet.findLock(FactMan, Cp)) {
981 FSet.removeLock(FactMan, !Cp);
982 FSet.addLock(FactMan,
983 std::make_unique<LockableFactEntry>(Cp, kind, loc, Managed));
987 void unlock(FactSet &FSet, FactManager &FactMan,
const CapabilityExpr &Cp,
989 if (FSet.findLock(FactMan, Cp)) {
990 FSet.removeLock(FactMan, Cp);
991 FSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
993 }
else if (Handler) {
995 if (
const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
996 PrevLoc =
Neg->loc();
1003class ThreadSafetyAnalyzer {
1004 friend class BuildLockset;
1007 llvm::BumpPtrAllocator Bpa;
1013 LocalVariableMap LocalVarMap;
1014 FactManager FactMan;
1015 std::vector<CFGBlockInfo> BlockInfo;
1021 : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
1025 void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
1026 bool ReqAttr =
false);
1030 template <
typename AttrType>
1031 void getMutexIDs(CapExprSet &Mtxs, AttrType *
Attr,
const Expr *Exp,
1034 template <
class AttrType>
1035 void getMutexIDs(CapExprSet &Mtxs, AttrType *
Attr,
const Expr *Exp,
1038 Expr *BrE,
bool Neg);
1040 const CallExpr* getTrylockCallExpr(
const Stmt *Cond, LocalVarContext
C,
1043 void getEdgeLockset(FactSet &Result,
const FactSet &ExitSet,
1047 bool join(
const FactEntry &a,
const FactEntry &
b,
bool CanModify);
1049 void intersectAndWarn(FactSet &EntrySet,
const FactSet &ExitSet,
1053 void intersectAndWarn(FactSet &EntrySet,
const FactSet &ExitSet,
1055 intersectAndWarn(EntrySet, ExitSet, JoinLoc, LEK, LEK);
1065 ThreadSafetyAnalyzer& Analyzer) {
1067 BeforeInfo *Info =
nullptr;
1071 std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
1073 InfoPtr.reset(
new BeforeInfo());
1074 Info = InfoPtr.get();
1077 for (
const auto *At : Vd->
attrs()) {
1078 switch (At->getKind()) {
1079 case attr::AcquiredBefore: {
1080 const auto *A = cast<AcquiredBeforeAttr>(At);
1083 for (
const auto *Arg : A->args()) {
1085 Analyzer.SxBuilder.translateAttrExpr(Arg,
nullptr);
1087 Info->Vect.push_back(Cpvd);
1088 const auto It = BMap.find(Cpvd);
1089 if (It == BMap.end())
1095 case attr::AcquiredAfter: {
1096 const auto *A = cast<AcquiredAfterAttr>(At);
1099 for (
const auto *Arg : A->args()) {
1101 Analyzer.SxBuilder.translateAttrExpr(Arg,
nullptr);
1105 ArgInfo->Vect.push_back(Vd);
1118BeforeSet::BeforeInfo *
1120 ThreadSafetyAnalyzer &Analyzer) {
1121 auto It = BMap.find(Vd);
1122 BeforeInfo *Info =
nullptr;
1123 if (It == BMap.end())
1126 Info = It->second.get();
1127 assert(Info &&
"BMap contained nullptr?");
1133 const FactSet& FSet,
1134 ThreadSafetyAnalyzer& Analyzer,
1146 if (Info->Visited == 1)
1149 if (Info->Visited == 2)
1152 if (Info->Vect.empty())
1155 InfoVect.push_back(Info);
1157 for (
const auto *Vdb : Info->Vect) {
1159 if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
1160 StringRef L1 = StartVd->
getName();
1161 StringRef L2 = Vdb->getName();
1162 Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
1166 if (!CycMap.contains(Vd)) {
1167 CycMap.insert(std::make_pair(Vd,
true));
1169 Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->
getLocation());
1179 for (
auto *Info : InfoVect)
1185 if (
const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
1188 if (
const auto *DR = dyn_cast<DeclRefExpr>(Exp))
1189 return DR->getDecl();
1191 if (
const auto *ME = dyn_cast<MemberExpr>(Exp))
1192 return ME->getMemberDecl();
1199template <
typename Ty>
1200class has_arg_iterator_range {
1201 using yes =
char[1];
1204 template <
typename Inner>
1205 static yes& test(Inner *I,
decltype(I->args()) * =
nullptr);
1208 static no& test(...);
1211 static const bool value =
sizeof(test<Ty>(
nullptr)) ==
sizeof(yes);
1216bool ThreadSafetyAnalyzer::inCurrentScope(
const CapabilityExpr &CapE) {
1218 assert(SExp &&
"Null expressions should be ignored");
1220 if (
const auto *LP = dyn_cast<til::LiteralPtr>(SExp)) {
1233 if (
const auto *
P = dyn_cast<til::Project>(SExp)) {
1245void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
1246 std::unique_ptr<FactEntry> Entry,
1248 if (Entry->shouldIgnore())
1251 if (!ReqAttr && !Entry->negative()) {
1254 const FactEntry *Nen = FSet.findLock(FactMan, NegC);
1256 FSet.removeLock(FactMan, NegC);
1259 if (inCurrentScope(*Entry) && !Entry->asserted())
1267 !Entry->asserted() && !Entry->declared()) {
1268 GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *
this,
1269 Entry->loc(), Entry->getKind());
1273 if (
const FactEntry *Cp = FSet.findLock(FactMan, *Entry)) {
1274 if (!Entry->asserted())
1275 Cp->handleLock(FSet, FactMan, *Entry, Handler);
1277 FSet.addLock(FactMan, std::move(Entry));
1283void ThreadSafetyAnalyzer::removeLock(FactSet &FSet,
const CapabilityExpr &Cp,
1285 bool FullyRemove,
LockKind ReceivedKind) {
1289 const FactEntry *LDat = FSet.findLock(FactMan, Cp);
1292 if (
const FactEntry *Neg = FSet.findLock(FactMan, !Cp))
1293 PrevLoc =
Neg->loc();
1301 if (ReceivedKind !=
LK_Generic && LDat->kind() != ReceivedKind) {
1303 ReceivedKind, LDat->loc(), UnlockLoc);
1306 LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler);
1311template <
typename AttrType>
1312void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *
Attr,
1315 if (
Attr->args_size() == 0) {
1317 CapabilityExpr Cp = SxBuilder.translateAttrExpr(
nullptr, D, Exp, Self);
1324 Mtxs.push_back_nodup(Cp);
1328 for (
const auto *Arg :
Attr->args()) {
1329 CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, Self);
1336 Mtxs.push_back_nodup(Cp);
1343template <
class AttrType>
1344void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *
Attr,
1348 Expr *BrE,
bool Neg) {
1350 bool branch =
false;
1351 if (
const auto *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
1352 branch = BLE->getValue();
1353 else if (
const auto *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
1354 branch = ILE->getValue().getBoolValue();
1356 int branchnum = branch ? 0 : 1;
1358 branchnum = !branchnum;
1363 SE = PredBlock->
succ_end(); SI != SE && i < 2; ++SI, ++i) {
1364 if (*SI == CurrBlock && i == branchnum)
1365 getMutexIDs(Mtxs,
Attr, Exp, D);
1370 if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
1373 }
else if (
const auto *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
1374 TCond = BLE->getValue();
1376 }
else if (
const auto *ILE = dyn_cast<IntegerLiteral>(E)) {
1377 TCond = ILE->getValue().getBoolValue();
1379 }
else if (
auto *CE = dyn_cast<ImplicitCastExpr>(E))
1387const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(
const Stmt *Cond,
1393 if (
const auto *CallExp = dyn_cast<CallExpr>(Cond)) {
1394 if (CallExp->getBuiltinCallee() == Builtin::BI__builtin_expect)
1395 return getTrylockCallExpr(CallExp->getArg(0),
C, Negate);
1398 else if (
const auto *PE = dyn_cast<ParenExpr>(Cond))
1399 return getTrylockCallExpr(PE->getSubExpr(),
C, Negate);
1400 else if (
const auto *CE = dyn_cast<ImplicitCastExpr>(Cond))
1401 return getTrylockCallExpr(CE->getSubExpr(),
C, Negate);
1402 else if (
const auto *FE = dyn_cast<FullExpr>(Cond))
1403 return getTrylockCallExpr(FE->getSubExpr(),
C, Negate);
1404 else if (
const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
1405 const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(),
C);
1406 return getTrylockCallExpr(E,
C, Negate);
1408 else if (
const auto *UOP = dyn_cast<UnaryOperator>(Cond)) {
1409 if (UOP->getOpcode() == UO_LNot) {
1411 return getTrylockCallExpr(UOP->getSubExpr(),
C, Negate);
1415 else if (
const auto *BOP = dyn_cast<BinaryOperator>(Cond)) {
1416 if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
1417 if (BOP->getOpcode() == BO_NE)
1422 if (!TCond) Negate = !Negate;
1423 return getTrylockCallExpr(BOP->getLHS(),
C, Negate);
1427 if (!TCond) Negate = !Negate;
1428 return getTrylockCallExpr(BOP->getRHS(),
C, Negate);
1432 if (BOP->getOpcode() == BO_LAnd) {
1434 return getTrylockCallExpr(BOP->getRHS(),
C, Negate);
1436 if (BOP->getOpcode() == BO_LOr)
1437 return getTrylockCallExpr(BOP->getRHS(),
C, Negate);
1439 }
else if (
const auto *COP = dyn_cast<ConditionalOperator>(Cond)) {
1443 if (TCond && !FCond)
1444 return getTrylockCallExpr(COP->getCond(),
C, Negate);
1445 if (!TCond && FCond) {
1447 return getTrylockCallExpr(COP->getCond(),
C, Negate);
1457void ThreadSafetyAnalyzer::getEdgeLockset(FactSet&
Result,
1458 const FactSet &ExitSet,
1468 bool Negate =
false;
1469 const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->
getBlockID()];
1470 const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
1472 const auto *Exp = getTrylockCallExpr(Cond, LVarCtx, Negate);
1476 auto *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
1477 if(!FunDecl || !FunDecl->hasAttrs())
1480 CapExprSet ExclusiveLocksToAdd;
1481 CapExprSet SharedLocksToAdd;
1484 for (
const auto *
Attr : FunDecl->attrs()) {
1486 case attr::TryAcquireCapability: {
1487 auto *A = cast<TryAcquireCapabilityAttr>(
Attr);
1488 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
1489 Exp, FunDecl, PredBlock, CurrBlock, A->getSuccessValue(),
1493 case attr::ExclusiveTrylockFunction: {
1494 const auto *A = cast<ExclusiveTrylockFunctionAttr>(
Attr);
1495 getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
1496 A->getSuccessValue(), Negate);
1499 case attr::SharedTrylockFunction: {
1500 const auto *A = cast<SharedTrylockFunctionAttr>(
Attr);
1501 getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl, PredBlock, CurrBlock,
1502 A->getSuccessValue(), Negate);
1512 for (
const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
1513 addLock(
Result, std::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
1515 for (
const auto &SharedLockToAdd : SharedLocksToAdd)
1516 addLock(
Result, std::make_unique<LockableFactEntry>(SharedLockToAdd,
1528 friend class ThreadSafetyAnalyzer;
1530 ThreadSafetyAnalyzer *Analyzer;
1533 llvm::SmallDenseMap<const Expr *, til::LiteralPtr *> ConstructedObjects;
1534 LocalVariableMap::Context LVarCtx;
1555 bool SkipFirstParam =
false);
1558 BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
1560 LVarCtx(Info.EntryContext), CtxIndex(Info.EntryIndex) {}
1564 void VisitCastExpr(
const CastExpr *CE);
1565 void VisitCallExpr(
const CallExpr *Exp);
1567 void VisitDeclStmt(
const DeclStmt *S);
1575void BuildLockset::warnIfMutexNotHeld(
const NamedDecl *D,
const Expr *Exp,
1583 Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp, Self);
1593 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
1595 Analyzer->Handler.handleFunExcludesLock(
1602 if (!Analyzer->inCurrentScope(Cp))
1606 LDat = FSet.findLock(Analyzer->FactMan, Cp);
1608 Analyzer->Handler.handleNegativeNotHeld(D, Cp.
toString(), Loc);
1613 const FactEntry *LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
1614 bool NoError =
true;
1617 LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
1620 std::string PartMatchStr = LDat->toString();
1621 StringRef PartMatchName(PartMatchStr);
1622 Analyzer->Handler.handleMutexNotHeld(Cp.
getKind(), D, POK, Cp.
toString(),
1623 LK, Loc, &PartMatchName);
1626 Analyzer->Handler.handleMutexNotHeld(Cp.
getKind(), D, POK, Cp.
toString(),
1632 if (NoError && LDat && !LDat->isAtLeast(LK)) {
1633 Analyzer->Handler.handleMutexNotHeld(Cp.
getKind(), D, POK, Cp.
toString(),
1639void BuildLockset::warnIfMutexHeld(
const NamedDecl *D,
const Expr *Exp,
1643 Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp, Self);
1651 const FactEntry *LDat = FSet.findLock(Analyzer->FactMan, Cp);
1671 while (
const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
1672 const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
1674 if (
const auto *E = VD->getInit()) {
1685 if (
const auto *UO = dyn_cast<UnaryOperator>(Exp)) {
1687 if (UO->getOpcode() == UO_Deref)
1688 checkPtAccess(UO->getSubExpr(), AK, POK);
1692 if (
const auto *BO = dyn_cast<BinaryOperator>(Exp)) {
1695 return checkAccess(BO->
getLHS(), AK, POK);
1697 return checkPtAccess(BO->
getLHS(), AK, POK);
1703 if (
const auto *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
1704 checkPtAccess(AE->getLHS(), AK, POK);
1708 if (
const auto *ME = dyn_cast<MemberExpr>(Exp)) {
1710 checkPtAccess(ME->getBase(), AK, POK);
1712 checkAccess(ME->getBase(), AK, POK);
1719 if (D->
hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
1720 Analyzer->Handler.handleNoMutexHeld(D, POK, AK, Loc);
1724 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
nullptr, Loc);
1732 if (
const auto *PE = dyn_cast<ParenExpr>(Exp)) {
1733 Exp = PE->getSubExpr();
1736 if (
const auto *CE = dyn_cast<CastExpr>(Exp)) {
1737 if (CE->getCastKind() == CK_ArrayToPointerDecay) {
1740 checkAccess(CE->getSubExpr(), AK, POK);
1743 Exp = CE->getSubExpr();
1757 if (D->
hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
1758 Analyzer->Handler.handleNoMutexHeld(D, PtPOK, AK, Exp->
getExprLoc());
1761 warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
nullptr,
1779void BuildLockset::handleCall(
const Expr *Exp,
const NamedDecl *D,
1781 CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
1782 CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
1783 CapExprSet ScopedReqsAndExcludes;
1791 std::pair<til::LiteralPtr *, StringRef> Placeholder =
1792 Analyzer->SxBuilder.createThisPlaceholder(Exp);
1793 [[maybe_unused]]
auto inserted =
1794 ConstructedObjects.insert({Exp, Placeholder.first});
1795 assert(inserted.second &&
"Are we visiting the same expression again?");
1796 if (isa<CXXConstructExpr>(Exp))
1797 Self = Placeholder.first;
1798 if (TagT->getDecl()->hasAttr<ScopedLockableAttr>())
1799 Scp =
CapabilityExpr(Placeholder.first, Placeholder.second,
false);
1807 switch (At->getKind()) {
1810 case attr::AcquireCapability: {
1811 const auto *A = cast<AcquireCapabilityAttr>(At);
1812 Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
1813 : ExclusiveLocksToAdd,
1821 case attr::AssertExclusiveLock: {
1822 const auto *A = cast<AssertExclusiveLockAttr>(At);
1824 CapExprSet AssertLocks;
1825 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self);
1826 for (
const auto &AssertLock : AssertLocks)
1828 FSet, std::make_unique<LockableFactEntry>(
1832 case attr::AssertSharedLock: {
1833 const auto *A = cast<AssertSharedLockAttr>(At);
1835 CapExprSet AssertLocks;
1836 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self);
1837 for (
const auto &AssertLock : AssertLocks)
1839 FSet, std::make_unique<LockableFactEntry>(
1840 AssertLock,
LK_Shared, Loc, FactEntry::Asserted));
1844 case attr::AssertCapability: {
1845 const auto *A = cast<AssertCapabilityAttr>(At);
1846 CapExprSet AssertLocks;
1847 Analyzer->getMutexIDs(AssertLocks, A, Exp, D, Self);
1848 for (
const auto &AssertLock : AssertLocks)
1849 Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(
1852 Loc, FactEntry::Asserted));
1858 case attr::ReleaseCapability: {
1859 const auto *A = cast<ReleaseCapabilityAttr>(At);
1861 Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, Self);
1862 else if (A->isShared())
1863 Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, Self);
1865 Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, Self);
1869 case attr::RequiresCapability: {
1870 const auto *A = cast<RequiresCapabilityAttr>(At);
1871 for (
auto *Arg : A->args()) {
1876 Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, Self);
1881 case attr::LocksExcluded: {
1882 const auto *A = cast<LocksExcludedAttr>(At);
1883 for (
auto *Arg : A->args()) {
1884 warnIfMutexHeld(D, Exp, Arg, Self, Loc);
1887 Analyzer->getMutexIDs(ScopedReqsAndExcludes, A, Exp, D, Self);
1900 bool Dtor = isa<CXXDestructorDecl>(D);
1901 for (
const auto &M : ExclusiveLocksToRemove)
1902 Analyzer->removeLock(FSet, M, Loc, Dtor,
LK_Exclusive);
1903 for (
const auto &M : SharedLocksToRemove)
1904 Analyzer->removeLock(FSet, M, Loc, Dtor,
LK_Shared);
1905 for (
const auto &M : GenericLocksToRemove)
1906 Analyzer->removeLock(FSet, M, Loc, Dtor,
LK_Generic);
1909 FactEntry::SourceKind Source =
1910 !Scp.
shouldIgnore() ? FactEntry::Managed : FactEntry::Acquired;
1911 for (
const auto &M : ExclusiveLocksToAdd)
1912 Analyzer->addLock(FSet, std::make_unique<LockableFactEntry>(M,
LK_Exclusive,
1914 for (
const auto &M : SharedLocksToAdd)
1916 FSet, std::make_unique<LockableFactEntry>(M,
LK_Shared, Loc, Source));
1920 auto ScopedEntry = std::make_unique<ScopedLockableFactEntry>(Scp, Loc);
1921 for (
const auto &M : ExclusiveLocksToAdd)
1922 ScopedEntry->addLock(M);
1923 for (
const auto &M : SharedLocksToAdd)
1924 ScopedEntry->addLock(M);
1925 for (
const auto &M : ScopedReqsAndExcludes)
1926 ScopedEntry->addLock(M);
1927 for (
const auto &M : ExclusiveLocksToRemove)
1928 ScopedEntry->addExclusiveUnlock(M);
1929 for (
const auto &M : SharedLocksToRemove)
1930 ScopedEntry->addSharedUnlock(M);
1931 Analyzer->addLock(FSet, std::move(ScopedEntry));
1938void BuildLockset::VisitUnaryOperator(
const UnaryOperator *UO) {
1954void BuildLockset::VisitBinaryOperator(
const BinaryOperator *BO) {
1959 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
1967void BuildLockset::VisitCastExpr(
const CastExpr *CE) {
1973void BuildLockset::examineArguments(
const FunctionDecl *FD,
1976 bool SkipFirstParam) {
1986 if (FD->
hasAttr<NoThreadSafetyAnalysisAttr>())
1990 auto Param = Params.begin();
1995 for (
auto Arg = ArgBegin; Param != Params.end() && Arg != ArgEnd;
2003void BuildLockset::VisitCallExpr(
const CallExpr *Exp) {
2004 if (
const auto *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
2005 const auto *ME = dyn_cast<MemberExpr>(CE->getCallee());
2010 if (ME->isArrow()) {
2012 checkPtAccess(CE->getImplicitObjectArgument(),
AK_Read);
2015 checkAccess(CE->getImplicitObjectArgument(),
AK_Read);
2019 examineArguments(CE->getDirectCallee(), CE->arg_begin(), CE->arg_end());
2020 }
else if (
const auto *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
2028 case OO_PercentEqual:
2032 case OO_LessLessEqual:
2033 case OO_GreaterGreaterEqual:
2034 checkAccess(OE->getArg(1),
AK_Read);
2044 if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
2046 checkPtAccess(OE->getArg(0),
AK_Read);
2051 const Expr *Obj = OE->getArg(0);
2057 examineArguments(FD, std::next(OE->arg_begin()), OE->arg_end(),
2058 !isa<CXXMethodDecl>(FD));
2066 auto *D = dyn_cast_or_null<NamedDecl>(Exp->
getCalleeDecl());
2085 if (
auto *CE = dyn_cast<CastExpr>(E))
2088 if (
auto *CE = dyn_cast<CastExpr>(E))
2089 if (CE->
getCastKind() == CK_ConstructorConversion ||
2092 if (
auto *BTE = dyn_cast<CXXBindTemporaryExpr>(E))
2093 E = BTE->getSubExpr();
2097void BuildLockset::VisitDeclStmt(
const DeclStmt *S) {
2099 LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
2101 for (
auto *D : S->getDeclGroup()) {
2102 if (
auto *VD = dyn_cast_or_null<VarDecl>(D)) {
2103 const Expr *E = VD->getInit();
2109 if (
auto *EWC = dyn_cast<ExprWithCleanups>(E))
2113 if (
auto Object = ConstructedObjects.find(E);
2114 Object != ConstructedObjects.end()) {
2115 Object->second->setClangDecl(VD);
2116 ConstructedObjects.erase(Object);
2122void BuildLockset::VisitMaterializeTemporaryExpr(
2127 Object != ConstructedObjects.end()) {
2128 Object->second->setClangDecl(ExtD);
2129 ConstructedObjects.erase(Object);
2139bool ThreadSafetyAnalyzer::join(
const FactEntry &A,
const FactEntry &B,
2141 if (A.kind() != B.kind()) {
2144 if ((A.managed() || A.asserted()) && (B.managed() || B.asserted())) {
2146 bool ShouldTakeB = B.kind() ==
LK_Shared;
2147 if (CanModify || !ShouldTakeB)
2156 return CanModify && A.asserted() && !B.asserted();
2174void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &EntrySet,
2175 const FactSet &ExitSet,
2179 FactSet EntrySetOrig = EntrySet;
2182 for (
const auto &Fact : ExitSet) {
2183 const FactEntry &ExitFact = FactMan[Fact];
2185 FactSet::iterator EntryIt = EntrySet.findLockIter(FactMan, ExitFact);
2186 if (EntryIt != EntrySet.end()) {
2187 if (join(FactMan[*EntryIt], ExitFact,
2190 }
else if (!ExitFact.managed()) {
2191 ExitFact.handleRemovalFromIntersection(ExitSet, FactMan, JoinLoc,
2197 for (
const auto &Fact : EntrySetOrig) {
2198 const FactEntry *EntryFact = &FactMan[Fact];
2199 const FactEntry *ExitFact = ExitSet.findLock(FactMan, *EntryFact);
2203 EntryFact->handleRemovalFromIntersection(EntrySetOrig, FactMan, JoinLoc,
2206 EntrySet.removeLock(FactMan, *EntryFact);
2219 if (std::optional<CFGStmt> S =
Last.getAs<
CFGStmt>()) {
2220 if (isa<CXXThrowExpr>(S->getStmt()))
2235 if (!walker.
init(AC))
2243 const auto *CurrentFunction = dyn_cast<FunctionDecl>(D);
2244 CurrentMethod = dyn_cast<CXXMethodDecl>(D);
2246 if (D->
hasAttr<NoThreadSafetyAnalysisAttr>())
2253 if (isa<CXXConstructorDecl>(D))
2255 if (isa<CXXDestructorDecl>(D))
2261 CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
2273 LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
2278 CapExprSet ExclusiveLocksAcquired;
2279 CapExprSet SharedLocksAcquired;
2280 CapExprSet LocksReleased;
2287 FactSet &InitialLockset = BlockInfo[FirstBlock->
getBlockID()].EntrySet;
2289 CapExprSet ExclusiveLocksToAdd;
2290 CapExprSet SharedLocksToAdd;
2295 if (
const auto *A = dyn_cast<RequiresCapabilityAttr>(
Attr)) {
2296 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2298 }
else if (
const auto *A = dyn_cast<ReleaseCapabilityAttr>(
Attr)) {
2301 if (A->args_size() == 0)
2303 getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
2305 getMutexIDs(LocksReleased, A,
nullptr, D);
2306 }
else if (
const auto *A = dyn_cast<AcquireCapabilityAttr>(
Attr)) {
2307 if (A->args_size() == 0)
2309 getMutexIDs(A->isShared() ? SharedLocksAcquired
2310 : ExclusiveLocksAcquired,
2312 }
else if (isa<ExclusiveTrylockFunctionAttr>(
Attr)) {
2315 }
else if (isa<SharedTrylockFunctionAttr>(
Attr)) {
2318 }
else if (isa<TryAcquireCapabilityAttr>(
Attr)) {
2325 for (
const auto &Mu : ExclusiveLocksToAdd) {
2326 auto Entry = std::make_unique<LockableFactEntry>(Mu,
LK_Exclusive, Loc,
2327 FactEntry::Declared);
2328 addLock(InitialLockset, std::move(Entry),
true);
2330 for (
const auto &Mu : SharedLocksToAdd) {
2331 auto Entry = std::make_unique<LockableFactEntry>(Mu,
LK_Shared, Loc,
2332 FactEntry::Declared);
2333 addLock(InitialLockset, std::move(Entry),
true);
2337 for (
const auto *CurrBlock : *SortedGraph) {
2338 unsigned CurrBlockID = CurrBlock->
getBlockID();
2339 CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
2342 VisitedBlocks.insert(CurrBlock);
2357 bool LocksetInitialized =
false;
2359 PE = CurrBlock->
pred_end(); PI != PE; ++PI) {
2361 if (*PI ==
nullptr || !VisitedBlocks.alreadySet(*PI))
2364 unsigned PrevBlockID = (*PI)->getBlockID();
2365 CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
2372 CurrBlockInfo->Reachable =
true;
2374 FactSet PrevLockset;
2375 getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
2377 if (!LocksetInitialized) {
2378 CurrBlockInfo->EntrySet = PrevLockset;
2379 LocksetInitialized =
true;
2385 CurrBlockInfo->EntrySet, PrevLockset, CurrBlockInfo->EntryLoc,
2386 isa_and_nonnull<ContinueStmt>((*PI)->getTerminatorStmt())
2393 if (!CurrBlockInfo->Reachable)
2396 BuildLockset LocksetBuilder(
this, *CurrBlockInfo);
2399 for (
const auto &BI : *CurrBlock) {
2400 switch (BI.getKind()) {
2403 LocksetBuilder.Visit(CS.
getStmt());
2410 if (!DD->hasAttrs())
2413 LocksetBuilder.handleCall(
nullptr, DD,
2423 if (
auto Object = LocksetBuilder.ConstructedObjects.find(
2424 TD.getBindTemporaryExpr()->getSubExpr());
2425 Object != LocksetBuilder.ConstructedObjects.end()) {
2429 LocksetBuilder.handleCall(
nullptr, DD,
Object->second,
2430 TD.getBindTemporaryExpr()->getEndLoc());
2431 LocksetBuilder.ConstructedObjects.erase(Object);
2439 CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
2446 SE = CurrBlock->succ_end(); SI != SE; ++SI) {
2448 if (*SI ==
nullptr || !VisitedBlocks.alreadySet(*SI))
2452 CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->
getBlockID()];
2453 CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
2454 intersectAndWarn(PreLoop->EntrySet, LoopEnd->ExitSet, PreLoop->EntryLoc,
2463 if (!Final->Reachable)
2467 FactSet ExpectedExitSet = Initial->EntrySet;
2473 for (
const auto &Lock : ExclusiveLocksAcquired)
2474 ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2476 for (
const auto &Lock : SharedLocksAcquired)
2477 ExpectedExitSet.addLock(FactMan, std::make_unique<LockableFactEntry>(
2479 for (
const auto &Lock : LocksReleased)
2480 ExpectedExitSet.removeLock(FactMan, Lock);
2483 intersectAndWarn(ExpectedExitSet, Final->ExitSet, Final->ExitLoc,
2499 ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
2500 Analyzer.runAnalysis(AC);
2514 llvm_unreachable(
"Unknown AccessKind");
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Defines enum values for all the target-independent builtin functions.
static void dump(llvm::raw_ostream &OS, StringRef FunctionName, ArrayRef< CounterExpression > Expressions, ArrayRef< CounterMappingRegion > Regions)
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines an enumeration for C++ overloaded operators.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static void warnInvalidLock(ThreadSafetyHandler &Handler, const Expr *MutexExp, const NamedDecl *D, const Expr *DeclExp, StringRef Kind)
Issue a warning about an invalid lock expression.
static bool getStaticBooleanValue(Expr *E, bool &TCond)
static bool neverReturns(const CFGBlock *B)
static void findBlockLocations(CFG *CFGraph, const PostOrderCFGView *SortedGraph, std::vector< CFGBlockInfo > &BlockInfo)
Find the appropriate source locations to use when producing diagnostics for each block in the CFG.
static const ValueDecl * getValueDecl(const Expr *Exp)
Gets the value decl pointer from DeclRefExprs or MemberExprs.
static const Expr * UnpackConstruction(const Expr *E)
TypePropertyCache< Private > Cache
C Language Family Type Representation.
AnalysisDeclContext contains the context data for the function, method or block under analysis.
ASTContext & getASTContext() const
Attr - This represents one attribute.
attr::Kind getKind() const
SourceLocation getLocation() const
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isAssignmentOp(Opcode Opc)
Represents C++ object destructor implicitly generated for automatic object or temporary bound to cons...
const VarDecl * getVarDecl() const
const Stmt * getTriggerStmt() const
Represents a single basic block in a source-level CFG.
bool hasNoReturnElement() const
succ_iterator succ_begin()
Stmt * getTerminatorStmt()
AdjacentBlocks::const_iterator const_pred_iterator
pred_iterator pred_begin()
unsigned getBlockID() const
Stmt * getTerminatorCondition(bool StripParens=true)
AdjacentBlocks::const_iterator const_succ_iterator
Represents a top-level expression in a basic block.
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type.
const CXXDestructorDecl * getDestructorDecl(ASTContext &astContext) const
const Stmt * getStmt() const
Represents C++ object destructor implicitly generated at the end of full expression for temporary obj...
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
unsigned getNumBlockIDs() const
Returns the total number of BlockIDs allocated (which start at 0).
Represents a call to a C++ constructor.
Expr * getArg(unsigned Arg)
Return the specified argument.
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Represents a C++ constructor within a class.
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Represents a static or instance method of a struct/union/class.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
CastKind getCastKind() const
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
DeclContext * getDeclContext()
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Represents a function declaration or definition.
ArrayRef< ParmVarDecl * > parameters() const
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
This represents a decl that may have a name.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Implements a set of CFGBlocks using a BitVector.
A (possibly-)qualified type.
bool isTrivialType(const ASTContext &Context) const
Return true if this is a trivial type per (C++0x [basic.types]p9)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
Stmt - This represents one statement.
SourceLocation getEndLoc() const LLVM_READONLY
void dump() const
Dumps the specified AST fragment and all subtrees to llvm::errs().
bool isReferenceType() const
const T * getAs() const
Member-template getAs<specific type>'.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Expr * getSubExpr() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
void checkBeforeAfter(const ValueDecl *Vd, const FactSet &FSet, ThreadSafetyAnalyzer &Analyzer, SourceLocation Loc, StringRef CapKind)
Return true if any mutexes in FSet are in the acquired_before set of Vd.
BeforeInfo * insertAttrExprs(const ValueDecl *Vd, ThreadSafetyAnalyzer &Analyzer)
Process acquired_before and acquired_after attributes on Vd.
BeforeInfo * getBeforeInfoForDecl(const ValueDecl *Vd, ThreadSafetyAnalyzer &Analyzer)
const PostOrderCFGView * getSortedGraph() const
const NamedDecl * getDecl() const
bool init(AnalysisDeclContext &AC)
const CFG * getGraph() const
bool shouldIgnore() const
bool equals(const CapabilityExpr &other) const
const til::SExpr * sexpr() const
std::string toString() const
const ValueDecl * valueDecl() const
StringRef getKind() const
Handler class for thread safety warnings.
virtual ~ThreadSafetyHandler()
virtual void handleInvalidLockExp(SourceLocation Loc)
Warn about lock expressions which fail to resolve to lockable objects.
virtual void enterFunction(const FunctionDecl *FD)
Called by the analysis when starting analysis of a function.
virtual void handleIncorrectUnlockKind(StringRef Kind, Name LockName, LockKind Expected, LockKind Received, SourceLocation LocLocked, SourceLocation LocUnlock)
Warn about an unlock function call that attempts to unlock a lock with the incorrect lock kind.
virtual void leaveFunction(const FunctionDecl *FD)
Called by the analysis when finishing analysis of a function.
virtual void handleExclusiveAndShared(StringRef Kind, Name LockName, SourceLocation Loc1, SourceLocation Loc2)
Warn when a mutex is held exclusively and shared at the same point.
virtual void handleUnmatchedUnlock(StringRef Kind, Name LockName, SourceLocation Loc, SourceLocation LocPreviousUnlock)
Warn about unlock function calls that do not have a prior matching lock expression.
virtual void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg, SourceLocation Loc)
Warn when acquiring a lock that the negative capability is not held.
virtual void handleMutexHeldEndOfScope(StringRef Kind, Name LockName, SourceLocation LocLocked, SourceLocation LocEndOfScope, LockErrorKind LEK)
Warn about situations where a mutex is sometimes held and sometimes not.
virtual void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked, SourceLocation LocDoubleLock)
Warn about lock function calls for locks which are already held.
A Literal pointer to an object allocated in memory.
Base class for AST nodes in the typed intermediate language.
internal::Matcher< T > traverse(TraversalKind TK, const internal::Matcher< T > &InnerMatcher)
Causes all nested matchers to be matched with the specified traversal kind.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
bool Dec(InterpState &S, CodePtr OpPC)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value decreased by ...
bool Neg(InterpState &S, CodePtr OpPC)
bool matches(const til::SExpr *E1, const til::SExpr *E2)
LockKind getLockKindFromAccessKind(AccessKind AK)
Helper function that returns a LockKind required for the given level of access.
@ LEK_NotLockedAtEndOfFunction
@ LEK_LockedSomePredecessors
@ LEK_LockedAtEndOfFunction
@ LEK_LockedSomeLoopIterations
void threadSafetyCleanup(BeforeSet *Cache)
AccessKind
This enum distinguishes between different ways to access (read or write) a variable.
@ AK_Written
Writing a variable.
@ AK_Read
Reading a variable.
LockKind
This enum distinguishes between different kinds of lock actions.
@ LK_Shared
Shared/reader lock of a mutex.
@ LK_Exclusive
Exclusive/writer lock of a mutex.
@ LK_Generic
Can be either Shared or Exclusive.
void runThreadSafetyAnalysis(AnalysisDeclContext &AC, ThreadSafetyHandler &Handler, BeforeSet **Bset)
Check a function's CFG for thread-safety violations.
ProtectedOperationKind
This enum distinguishes between different kinds of operations that may need to be protected by locks.
@ POK_PtPassByRef
Passing a pt-guarded variable by reference.
@ POK_VarDereference
Dereferencing a variable (e.g. p in *p = 5;)
@ POK_PassByRef
Passing a guarded variable by reference.
@ POK_VarAccess
Reading or writing a variable (e.g. x in x = 5;)
@ POK_FunctionCall
Making a function call (e.g. fool())
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
Iterator for iterating over Stmt * arrays that contain only T *.