ThreadSafety.cpp 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404
  1. //===- ThreadSafety.cpp ----------------------------------------*- C++ --*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // A intra-procedural analysis for thread safety (e.g. deadlocks and race
  11. // conditions), based off of an annotation system.
  12. //
  13. // See http://clang.llvm.org/docs/ThreadSafetyAnalysis.html
  14. // for more information.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "clang/Analysis/Analyses/ThreadSafety.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtVisitor.h"
  23. #include "clang/Analysis/Analyses/PostOrderCFGView.h"
  24. #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
  25. #include "clang/Analysis/Analyses/ThreadSafetyLogical.h"
  26. #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
  27. #include "clang/Analysis/Analyses/ThreadSafetyTraverse.h"
  28. #include "clang/Analysis/AnalysisContext.h"
  29. #include "clang/Analysis/CFG.h"
  30. #include "clang/Analysis/CFGStmtMap.h"
  31. #include "clang/Basic/OperatorKinds.h"
  32. #include "clang/Basic/SourceLocation.h"
  33. #include "clang/Basic/SourceManager.h"
  34. #include "llvm/ADT/ImmutableMap.h"
  35. #include "llvm/ADT/PostOrderIterator.h"
  36. #include "llvm/ADT/SmallVector.h"
  37. #include "llvm/ADT/StringRef.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <algorithm>
  40. #include <ostream>
  41. #include <sstream>
  42. #include <utility>
  43. #include <vector>
  44. using namespace clang;
  45. using namespace threadSafety;
  46. // Key method definition
  47. ThreadSafetyHandler::~ThreadSafetyHandler() {}
  48. namespace {
  49. class TILPrinter :
  50. public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
  51. /// Issue a warning about an invalid lock expression
  52. static void warnInvalidLock(ThreadSafetyHandler &Handler,
  53. const Expr *MutexExp, const NamedDecl *D,
  54. const Expr *DeclExp, StringRef Kind) {
  55. SourceLocation Loc;
  56. if (DeclExp)
  57. Loc = DeclExp->getExprLoc();
  58. // FIXME: add a note about the attribute location in MutexExp or D
  59. if (Loc.isValid())
  60. Handler.handleInvalidLockExp(Kind, Loc);
  61. }
  62. /// \brief A set of CapabilityInfo objects, which are compiled from the
  63. /// requires attributes on a function.
  64. class CapExprSet : public SmallVector<CapabilityExpr, 4> {
  65. public:
  66. /// \brief Push M onto list, but discard duplicates.
  67. void push_back_nodup(const CapabilityExpr &CapE) {
  68. iterator It = std::find_if(begin(), end(),
  69. [=](const CapabilityExpr &CapE2) {
  70. return CapE.equals(CapE2);
  71. });
  72. if (It == end())
  73. push_back(CapE);
  74. }
  75. };
  76. class FactManager;
  77. class FactSet;
  78. /// \brief This is a helper class that stores a fact that is known at a
  79. /// particular point in program execution. Currently, a fact is a capability,
  80. /// along with additional information, such as where it was acquired, whether
  81. /// it is exclusive or shared, etc.
  82. ///
  83. /// FIXME: this analysis does not currently support either re-entrant
  84. /// locking or lock "upgrading" and "downgrading" between exclusive and
  85. /// shared.
  86. class FactEntry : public CapabilityExpr {
  87. private:
  88. LockKind LKind; ///< exclusive or shared
  89. SourceLocation AcquireLoc; ///< where it was acquired.
  90. bool Asserted; ///< true if the lock was asserted
  91. bool Declared; ///< true if the lock was declared
  92. public:
  93. FactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
  94. bool Asrt, bool Declrd = false)
  95. : CapabilityExpr(CE), LKind(LK), AcquireLoc(Loc), Asserted(Asrt),
  96. Declared(Declrd) {}
  97. virtual ~FactEntry() {}
  98. LockKind kind() const { return LKind; }
  99. SourceLocation loc() const { return AcquireLoc; }
  100. bool asserted() const { return Asserted; }
  101. bool declared() const { return Declared; }
  102. void setDeclared(bool D) { Declared = D; }
  103. virtual void
  104. handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
  105. SourceLocation JoinLoc, LockErrorKind LEK,
  106. ThreadSafetyHandler &Handler) const = 0;
  107. virtual void handleUnlock(FactSet &FSet, FactManager &FactMan,
  108. const CapabilityExpr &Cp, SourceLocation UnlockLoc,
  109. bool FullyRemove, ThreadSafetyHandler &Handler,
  110. StringRef DiagKind) const = 0;
  111. // Return true if LKind >= LK, where exclusive > shared
  112. bool isAtLeast(LockKind LK) {
  113. return (LKind == LK_Exclusive) || (LK == LK_Shared);
  114. }
  115. };
  116. typedef unsigned short FactID;
  117. /// \brief FactManager manages the memory for all facts that are created during
  118. /// the analysis of a single routine.
  119. class FactManager {
  120. private:
  121. std::vector<std::unique_ptr<FactEntry>> Facts;
  122. public:
  123. FactID newFact(std::unique_ptr<FactEntry> Entry) {
  124. Facts.push_back(std::move(Entry));
  125. return static_cast<unsigned short>(Facts.size() - 1);
  126. }
  127. const FactEntry &operator[](FactID F) const { return *Facts[F]; }
  128. FactEntry &operator[](FactID F) { return *Facts[F]; }
  129. };
  130. /// \brief A FactSet is the set of facts that are known to be true at a
  131. /// particular program point. FactSets must be small, because they are
  132. /// frequently copied, and are thus implemented as a set of indices into a
  133. /// table maintained by a FactManager. A typical FactSet only holds 1 or 2
  134. /// locks, so we can get away with doing a linear search for lookup. Note
  135. /// that a hashtable or map is inappropriate in this case, because lookups
  136. /// may involve partial pattern matches, rather than exact matches.
  137. class FactSet {
  138. private:
  139. typedef SmallVector<FactID, 4> FactVec;
  140. FactVec FactIDs;
  141. public:
  142. typedef FactVec::iterator iterator;
  143. typedef FactVec::const_iterator const_iterator;
  144. iterator begin() { return FactIDs.begin(); }
  145. const_iterator begin() const { return FactIDs.begin(); }
  146. iterator end() { return FactIDs.end(); }
  147. const_iterator end() const { return FactIDs.end(); }
  148. bool isEmpty() const { return FactIDs.size() == 0; }
  149. // Return true if the set contains only negative facts
  150. bool isEmpty(FactManager &FactMan) const {
  151. for (FactID FID : *this) {
  152. if (!FactMan[FID].negative())
  153. return false;
  154. }
  155. return true;
  156. }
  157. void addLockByID(FactID ID) { FactIDs.push_back(ID); }
  158. FactID addLock(FactManager &FM, std::unique_ptr<FactEntry> Entry) {
  159. FactID F = FM.newFact(std::move(Entry));
  160. FactIDs.push_back(F);
  161. return F;
  162. }
  163. bool removeLock(FactManager& FM, const CapabilityExpr &CapE) {
  164. unsigned n = FactIDs.size();
  165. if (n == 0)
  166. return false;
  167. for (unsigned i = 0; i < n-1; ++i) {
  168. if (FM[FactIDs[i]].matches(CapE)) {
  169. FactIDs[i] = FactIDs[n-1];
  170. FactIDs.pop_back();
  171. return true;
  172. }
  173. }
  174. if (FM[FactIDs[n-1]].matches(CapE)) {
  175. FactIDs.pop_back();
  176. return true;
  177. }
  178. return false;
  179. }
  180. iterator findLockIter(FactManager &FM, const CapabilityExpr &CapE) {
  181. return std::find_if(begin(), end(), [&](FactID ID) {
  182. return FM[ID].matches(CapE);
  183. });
  184. }
  185. FactEntry *findLock(FactManager &FM, const CapabilityExpr &CapE) const {
  186. auto I = std::find_if(begin(), end(), [&](FactID ID) {
  187. return FM[ID].matches(CapE);
  188. });
  189. return I != end() ? &FM[*I] : nullptr;
  190. }
  191. FactEntry *findLockUniv(FactManager &FM, const CapabilityExpr &CapE) const {
  192. auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
  193. return FM[ID].matchesUniv(CapE);
  194. });
  195. return I != end() ? &FM[*I] : nullptr;
  196. }
  197. FactEntry *findPartialMatch(FactManager &FM,
  198. const CapabilityExpr &CapE) const {
  199. auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
  200. return FM[ID].partiallyMatches(CapE);
  201. });
  202. return I != end() ? &FM[*I] : nullptr;
  203. }
  204. bool containsMutexDecl(FactManager &FM, const ValueDecl* Vd) const {
  205. auto I = std::find_if(begin(), end(), [&](FactID ID) -> bool {
  206. return FM[ID].valueDecl() == Vd;
  207. });
  208. return I != end();
  209. }
  210. };
  211. class ThreadSafetyAnalyzer;
  212. } // namespace
  213. namespace clang {
  214. namespace threadSafety {
  215. class BeforeSet {
  216. private:
  217. typedef SmallVector<const ValueDecl*, 4> BeforeVect;
  218. struct BeforeInfo {
  219. BeforeInfo() : Visited(0) {}
  220. BeforeInfo(BeforeInfo &&O) : Vect(std::move(O.Vect)), Visited(O.Visited) {}
  221. BeforeVect Vect;
  222. int Visited;
  223. };
  224. typedef llvm::DenseMap<const ValueDecl *, std::unique_ptr<BeforeInfo>>
  225. BeforeMap;
  226. typedef llvm::DenseMap<const ValueDecl*, bool> CycleMap;
  227. public:
  228. BeforeSet() { }
  229. BeforeInfo* insertAttrExprs(const ValueDecl* Vd,
  230. ThreadSafetyAnalyzer& Analyzer);
  231. BeforeInfo *getBeforeInfoForDecl(const ValueDecl *Vd,
  232. ThreadSafetyAnalyzer &Analyzer);
  233. void checkBeforeAfter(const ValueDecl* Vd,
  234. const FactSet& FSet,
  235. ThreadSafetyAnalyzer& Analyzer,
  236. SourceLocation Loc, StringRef CapKind);
  237. private:
  238. BeforeMap BMap;
  239. CycleMap CycMap;
  240. };
  241. } // end namespace threadSafety
  242. } // end namespace clang
  243. namespace {
  244. typedef llvm::ImmutableMap<const NamedDecl*, unsigned> LocalVarContext;
  245. class LocalVariableMap;
  246. /// A side (entry or exit) of a CFG node.
  247. enum CFGBlockSide { CBS_Entry, CBS_Exit };
  248. /// CFGBlockInfo is a struct which contains all the information that is
  249. /// maintained for each block in the CFG. See LocalVariableMap for more
  250. /// information about the contexts.
  251. struct CFGBlockInfo {
  252. FactSet EntrySet; // Lockset held at entry to block
  253. FactSet ExitSet; // Lockset held at exit from block
  254. LocalVarContext EntryContext; // Context held at entry to block
  255. LocalVarContext ExitContext; // Context held at exit from block
  256. SourceLocation EntryLoc; // Location of first statement in block
  257. SourceLocation ExitLoc; // Location of last statement in block.
  258. unsigned EntryIndex; // Used to replay contexts later
  259. bool Reachable; // Is this block reachable?
  260. const FactSet &getSet(CFGBlockSide Side) const {
  261. return Side == CBS_Entry ? EntrySet : ExitSet;
  262. }
  263. SourceLocation getLocation(CFGBlockSide Side) const {
  264. return Side == CBS_Entry ? EntryLoc : ExitLoc;
  265. }
  266. private:
  267. CFGBlockInfo(LocalVarContext EmptyCtx)
  268. : EntryContext(EmptyCtx), ExitContext(EmptyCtx), Reachable(false)
  269. { }
  270. public:
  271. static CFGBlockInfo getEmptyBlockInfo(LocalVariableMap &M);
  272. };
  273. // A LocalVariableMap maintains a map from local variables to their currently
  274. // valid definitions. It provides SSA-like functionality when traversing the
  275. // CFG. Like SSA, each definition or assignment to a variable is assigned a
  276. // unique name (an integer), which acts as the SSA name for that definition.
  277. // The total set of names is shared among all CFG basic blocks.
  278. // Unlike SSA, we do not rewrite expressions to replace local variables declrefs
  279. // with their SSA-names. Instead, we compute a Context for each point in the
  280. // code, which maps local variables to the appropriate SSA-name. This map
  281. // changes with each assignment.
  282. //
  283. // The map is computed in a single pass over the CFG. Subsequent analyses can
  284. // then query the map to find the appropriate Context for a statement, and use
  285. // that Context to look up the definitions of variables.
  286. class LocalVariableMap {
  287. public:
  288. typedef LocalVarContext Context;
  289. /// A VarDefinition consists of an expression, representing the value of the
  290. /// variable, along with the context in which that expression should be
  291. /// interpreted. A reference VarDefinition does not itself contain this
  292. /// information, but instead contains a pointer to a previous VarDefinition.
  293. struct VarDefinition {
  294. public:
  295. friend class LocalVariableMap;
  296. const NamedDecl *Dec; // The original declaration for this variable.
  297. const Expr *Exp; // The expression for this variable, OR
  298. unsigned Ref; // Reference to another VarDefinition
  299. Context Ctx; // The map with which Exp should be interpreted.
  300. bool isReference() { return !Exp; }
  301. private:
  302. // Create ordinary variable definition
  303. VarDefinition(const NamedDecl *D, const Expr *E, Context C)
  304. : Dec(D), Exp(E), Ref(0), Ctx(C)
  305. { }
  306. // Create reference to previous definition
  307. VarDefinition(const NamedDecl *D, unsigned R, Context C)
  308. : Dec(D), Exp(nullptr), Ref(R), Ctx(C)
  309. { }
  310. };
  311. private:
  312. Context::Factory ContextFactory;
  313. std::vector<VarDefinition> VarDefinitions;
  314. std::vector<unsigned> CtxIndices;
  315. std::vector<std::pair<Stmt*, Context> > SavedContexts;
  316. public:
  317. LocalVariableMap() {
  318. // index 0 is a placeholder for undefined variables (aka phi-nodes).
  319. VarDefinitions.push_back(VarDefinition(nullptr, 0u, getEmptyContext()));
  320. }
  321. /// Look up a definition, within the given context.
  322. const VarDefinition* lookup(const NamedDecl *D, Context Ctx) {
  323. const unsigned *i = Ctx.lookup(D);
  324. if (!i)
  325. return nullptr;
  326. assert(*i < VarDefinitions.size());
  327. return &VarDefinitions[*i];
  328. }
  329. /// Look up the definition for D within the given context. Returns
  330. /// NULL if the expression is not statically known. If successful, also
  331. /// modifies Ctx to hold the context of the return Expr.
  332. const Expr* lookupExpr(const NamedDecl *D, Context &Ctx) {
  333. const unsigned *P = Ctx.lookup(D);
  334. if (!P)
  335. return nullptr;
  336. unsigned i = *P;
  337. while (i > 0) {
  338. if (VarDefinitions[i].Exp) {
  339. Ctx = VarDefinitions[i].Ctx;
  340. return VarDefinitions[i].Exp;
  341. }
  342. i = VarDefinitions[i].Ref;
  343. }
  344. return nullptr;
  345. }
  346. Context getEmptyContext() { return ContextFactory.getEmptyMap(); }
  347. /// Return the next context after processing S. This function is used by
  348. /// clients of the class to get the appropriate context when traversing the
  349. /// CFG. It must be called for every assignment or DeclStmt.
  350. Context getNextContext(unsigned &CtxIndex, Stmt *S, Context C) {
  351. if (SavedContexts[CtxIndex+1].first == S) {
  352. CtxIndex++;
  353. Context Result = SavedContexts[CtxIndex].second;
  354. return Result;
  355. }
  356. return C;
  357. }
  358. void dumpVarDefinitionName(unsigned i) {
  359. if (i == 0) {
  360. llvm::errs() << "Undefined";
  361. return;
  362. }
  363. const NamedDecl *Dec = VarDefinitions[i].Dec;
  364. if (!Dec) {
  365. llvm::errs() << "<<NULL>>";
  366. return;
  367. }
  368. Dec->printName(llvm::errs());
  369. llvm::errs() << "." << i << " " << ((const void*) Dec);
  370. }
  371. /// Dumps an ASCII representation of the variable map to llvm::errs()
  372. void dump() {
  373. for (unsigned i = 1, e = VarDefinitions.size(); i < e; ++i) {
  374. const Expr *Exp = VarDefinitions[i].Exp;
  375. unsigned Ref = VarDefinitions[i].Ref;
  376. dumpVarDefinitionName(i);
  377. llvm::errs() << " = ";
  378. if (Exp) Exp->dump();
  379. else {
  380. dumpVarDefinitionName(Ref);
  381. llvm::errs() << "\n";
  382. }
  383. }
  384. }
  385. /// Dumps an ASCII representation of a Context to llvm::errs()
  386. void dumpContext(Context C) {
  387. for (Context::iterator I = C.begin(), E = C.end(); I != E; ++I) {
  388. const NamedDecl *D = I.getKey();
  389. D->printName(llvm::errs());
  390. const unsigned *i = C.lookup(D);
  391. llvm::errs() << " -> ";
  392. dumpVarDefinitionName(*i);
  393. llvm::errs() << "\n";
  394. }
  395. }
  396. /// Builds the variable map.
  397. void traverseCFG(CFG *CFGraph, const PostOrderCFGView *SortedGraph,
  398. std::vector<CFGBlockInfo> &BlockInfo);
  399. protected:
  400. // Get the current context index
  401. unsigned getContextIndex() { return SavedContexts.size()-1; }
  402. // Save the current context for later replay
  403. void saveContext(Stmt *S, Context C) {
  404. SavedContexts.push_back(std::make_pair(S,C));
  405. }
  406. // Adds a new definition to the given context, and returns a new context.
  407. // This method should be called when declaring a new variable.
  408. Context addDefinition(const NamedDecl *D, const Expr *Exp, Context Ctx) {
  409. assert(!Ctx.contains(D));
  410. unsigned newID = VarDefinitions.size();
  411. Context NewCtx = ContextFactory.add(Ctx, D, newID);
  412. VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
  413. return NewCtx;
  414. }
  415. // Add a new reference to an existing definition.
  416. Context addReference(const NamedDecl *D, unsigned i, Context Ctx) {
  417. unsigned newID = VarDefinitions.size();
  418. Context NewCtx = ContextFactory.add(Ctx, D, newID);
  419. VarDefinitions.push_back(VarDefinition(D, i, Ctx));
  420. return NewCtx;
  421. }
  422. // Updates a definition only if that definition is already in the map.
  423. // This method should be called when assigning to an existing variable.
  424. Context updateDefinition(const NamedDecl *D, Expr *Exp, Context Ctx) {
  425. if (Ctx.contains(D)) {
  426. unsigned newID = VarDefinitions.size();
  427. Context NewCtx = ContextFactory.remove(Ctx, D);
  428. NewCtx = ContextFactory.add(NewCtx, D, newID);
  429. VarDefinitions.push_back(VarDefinition(D, Exp, Ctx));
  430. return NewCtx;
  431. }
  432. return Ctx;
  433. }
  434. // Removes a definition from the context, but keeps the variable name
  435. // as a valid variable. The index 0 is a placeholder for cleared definitions.
  436. Context clearDefinition(const NamedDecl *D, Context Ctx) {
  437. Context NewCtx = Ctx;
  438. if (NewCtx.contains(D)) {
  439. NewCtx = ContextFactory.remove(NewCtx, D);
  440. NewCtx = ContextFactory.add(NewCtx, D, 0);
  441. }
  442. return NewCtx;
  443. }
  444. // Remove a definition entirely frmo the context.
  445. Context removeDefinition(const NamedDecl *D, Context Ctx) {
  446. Context NewCtx = Ctx;
  447. if (NewCtx.contains(D)) {
  448. NewCtx = ContextFactory.remove(NewCtx, D);
  449. }
  450. return NewCtx;
  451. }
  452. Context intersectContexts(Context C1, Context C2);
  453. Context createReferenceContext(Context C);
  454. void intersectBackEdge(Context C1, Context C2);
  455. friend class VarMapBuilder;
  456. };
  457. // This has to be defined after LocalVariableMap.
  458. CFGBlockInfo CFGBlockInfo::getEmptyBlockInfo(LocalVariableMap &M) {
  459. return CFGBlockInfo(M.getEmptyContext());
  460. }
  461. /// Visitor which builds a LocalVariableMap
  462. class VarMapBuilder : public StmtVisitor<VarMapBuilder> {
  463. public:
  464. LocalVariableMap* VMap;
  465. LocalVariableMap::Context Ctx;
  466. VarMapBuilder(LocalVariableMap *VM, LocalVariableMap::Context C)
  467. : VMap(VM), Ctx(C) {}
  468. void VisitDeclStmt(DeclStmt *S);
  469. void VisitBinaryOperator(BinaryOperator *BO);
  470. };
  471. // Add new local variables to the variable map
  472. void VarMapBuilder::VisitDeclStmt(DeclStmt *S) {
  473. bool modifiedCtx = false;
  474. DeclGroupRef DGrp = S->getDeclGroup();
  475. for (const auto *D : DGrp) {
  476. if (const auto *VD = dyn_cast_or_null<VarDecl>(D)) {
  477. const Expr *E = VD->getInit();
  478. // Add local variables with trivial type to the variable map
  479. QualType T = VD->getType();
  480. if (T.isTrivialType(VD->getASTContext())) {
  481. Ctx = VMap->addDefinition(VD, E, Ctx);
  482. modifiedCtx = true;
  483. }
  484. }
  485. }
  486. if (modifiedCtx)
  487. VMap->saveContext(S, Ctx);
  488. }
  489. // Update local variable definitions in variable map
  490. void VarMapBuilder::VisitBinaryOperator(BinaryOperator *BO) {
  491. if (!BO->isAssignmentOp())
  492. return;
  493. Expr *LHSExp = BO->getLHS()->IgnoreParenCasts();
  494. // Update the variable map and current context.
  495. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LHSExp)) {
  496. ValueDecl *VDec = DRE->getDecl();
  497. if (Ctx.lookup(VDec)) {
  498. if (BO->getOpcode() == BO_Assign)
  499. Ctx = VMap->updateDefinition(VDec, BO->getRHS(), Ctx);
  500. else
  501. // FIXME -- handle compound assignment operators
  502. Ctx = VMap->clearDefinition(VDec, Ctx);
  503. VMap->saveContext(BO, Ctx);
  504. }
  505. }
  506. }
  507. // Computes the intersection of two contexts. The intersection is the
  508. // set of variables which have the same definition in both contexts;
  509. // variables with different definitions are discarded.
  510. LocalVariableMap::Context
  511. LocalVariableMap::intersectContexts(Context C1, Context C2) {
  512. Context Result = C1;
  513. for (const auto &P : C1) {
  514. const NamedDecl *Dec = P.first;
  515. const unsigned *i2 = C2.lookup(Dec);
  516. if (!i2) // variable doesn't exist on second path
  517. Result = removeDefinition(Dec, Result);
  518. else if (*i2 != P.second) // variable exists, but has different definition
  519. Result = clearDefinition(Dec, Result);
  520. }
  521. return Result;
  522. }
  523. // For every variable in C, create a new variable that refers to the
  524. // definition in C. Return a new context that contains these new variables.
  525. // (We use this for a naive implementation of SSA on loop back-edges.)
  526. LocalVariableMap::Context LocalVariableMap::createReferenceContext(Context C) {
  527. Context Result = getEmptyContext();
  528. for (const auto &P : C)
  529. Result = addReference(P.first, P.second, Result);
  530. return Result;
  531. }
  532. // This routine also takes the intersection of C1 and C2, but it does so by
  533. // altering the VarDefinitions. C1 must be the result of an earlier call to
  534. // createReferenceContext.
  535. void LocalVariableMap::intersectBackEdge(Context C1, Context C2) {
  536. for (const auto &P : C1) {
  537. unsigned i1 = P.second;
  538. VarDefinition *VDef = &VarDefinitions[i1];
  539. assert(VDef->isReference());
  540. const unsigned *i2 = C2.lookup(P.first);
  541. if (!i2 || (*i2 != i1))
  542. VDef->Ref = 0; // Mark this variable as undefined
  543. }
  544. }
  545. // Traverse the CFG in topological order, so all predecessors of a block
  546. // (excluding back-edges) are visited before the block itself. At
  547. // each point in the code, we calculate a Context, which holds the set of
  548. // variable definitions which are visible at that point in execution.
  549. // Visible variables are mapped to their definitions using an array that
  550. // contains all definitions.
  551. //
  552. // At join points in the CFG, the set is computed as the intersection of
  553. // the incoming sets along each edge, E.g.
  554. //
  555. // { Context | VarDefinitions }
  556. // int x = 0; { x -> x1 | x1 = 0 }
  557. // int y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
  558. // if (b) x = 1; { x -> x2, y -> y1 | x2 = 1, y1 = 0, ... }
  559. // else x = 2; { x -> x3, y -> y1 | x3 = 2, x2 = 1, ... }
  560. // ... { y -> y1 (x is unknown) | x3 = 2, x2 = 1, ... }
  561. //
  562. // This is essentially a simpler and more naive version of the standard SSA
  563. // algorithm. Those definitions that remain in the intersection are from blocks
  564. // that strictly dominate the current block. We do not bother to insert proper
  565. // phi nodes, because they are not used in our analysis; instead, wherever
  566. // a phi node would be required, we simply remove that definition from the
  567. // context (E.g. x above).
  568. //
  569. // The initial traversal does not capture back-edges, so those need to be
  570. // handled on a separate pass. Whenever the first pass encounters an
  571. // incoming back edge, it duplicates the context, creating new definitions
  572. // that refer back to the originals. (These correspond to places where SSA
  573. // might have to insert a phi node.) On the second pass, these definitions are
  574. // set to NULL if the variable has changed on the back-edge (i.e. a phi
  575. // node was actually required.) E.g.
  576. //
  577. // { Context | VarDefinitions }
  578. // int x = 0, y = 0; { x -> x1, y -> y1 | y1 = 0, x1 = 0 }
  579. // while (b) { x -> x2, y -> y1 | [1st:] x2=x1; [2nd:] x2=NULL; }
  580. // x = x+1; { x -> x3, y -> y1 | x3 = x2 + 1, ... }
  581. // ... { y -> y1 | x3 = 2, x2 = 1, ... }
  582. //
  583. void LocalVariableMap::traverseCFG(CFG *CFGraph,
  584. const PostOrderCFGView *SortedGraph,
  585. std::vector<CFGBlockInfo> &BlockInfo) {
  586. PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
  587. CtxIndices.resize(CFGraph->getNumBlockIDs());
  588. for (const auto *CurrBlock : *SortedGraph) {
  589. int CurrBlockID = CurrBlock->getBlockID();
  590. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
  591. VisitedBlocks.insert(CurrBlock);
  592. // Calculate the entry context for the current block
  593. bool HasBackEdges = false;
  594. bool CtxInit = true;
  595. for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  596. PE = CurrBlock->pred_end(); PI != PE; ++PI) {
  597. // if *PI -> CurrBlock is a back edge, so skip it
  598. if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI)) {
  599. HasBackEdges = true;
  600. continue;
  601. }
  602. int PrevBlockID = (*PI)->getBlockID();
  603. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  604. if (CtxInit) {
  605. CurrBlockInfo->EntryContext = PrevBlockInfo->ExitContext;
  606. CtxInit = false;
  607. }
  608. else {
  609. CurrBlockInfo->EntryContext =
  610. intersectContexts(CurrBlockInfo->EntryContext,
  611. PrevBlockInfo->ExitContext);
  612. }
  613. }
  614. // Duplicate the context if we have back-edges, so we can call
  615. // intersectBackEdges later.
  616. if (HasBackEdges)
  617. CurrBlockInfo->EntryContext =
  618. createReferenceContext(CurrBlockInfo->EntryContext);
  619. // Create a starting context index for the current block
  620. saveContext(nullptr, CurrBlockInfo->EntryContext);
  621. CurrBlockInfo->EntryIndex = getContextIndex();
  622. // Visit all the statements in the basic block.
  623. VarMapBuilder VMapBuilder(this, CurrBlockInfo->EntryContext);
  624. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  625. BE = CurrBlock->end(); BI != BE; ++BI) {
  626. switch (BI->getKind()) {
  627. case CFGElement::Statement: {
  628. CFGStmt CS = BI->castAs<CFGStmt>();
  629. VMapBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
  630. break;
  631. }
  632. default:
  633. break;
  634. }
  635. }
  636. CurrBlockInfo->ExitContext = VMapBuilder.Ctx;
  637. // Mark variables on back edges as "unknown" if they've been changed.
  638. for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
  639. SE = CurrBlock->succ_end(); SI != SE; ++SI) {
  640. // if CurrBlock -> *SI is *not* a back edge
  641. if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
  642. continue;
  643. CFGBlock *FirstLoopBlock = *SI;
  644. Context LoopBegin = BlockInfo[FirstLoopBlock->getBlockID()].EntryContext;
  645. Context LoopEnd = CurrBlockInfo->ExitContext;
  646. intersectBackEdge(LoopBegin, LoopEnd);
  647. }
  648. }
  649. // Put an extra entry at the end of the indexed context array
  650. unsigned exitID = CFGraph->getExit().getBlockID();
  651. saveContext(nullptr, BlockInfo[exitID].ExitContext);
  652. }
  653. /// Find the appropriate source locations to use when producing diagnostics for
  654. /// each block in the CFG.
  655. static void findBlockLocations(CFG *CFGraph,
  656. const PostOrderCFGView *SortedGraph,
  657. std::vector<CFGBlockInfo> &BlockInfo) {
  658. for (const auto *CurrBlock : *SortedGraph) {
  659. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlock->getBlockID()];
  660. // Find the source location of the last statement in the block, if the
  661. // block is not empty.
  662. if (const Stmt *S = CurrBlock->getTerminator()) {
  663. CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc = S->getLocStart();
  664. } else {
  665. for (CFGBlock::const_reverse_iterator BI = CurrBlock->rbegin(),
  666. BE = CurrBlock->rend(); BI != BE; ++BI) {
  667. // FIXME: Handle other CFGElement kinds.
  668. if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
  669. CurrBlockInfo->ExitLoc = CS->getStmt()->getLocStart();
  670. break;
  671. }
  672. }
  673. }
  674. if (CurrBlockInfo->ExitLoc.isValid()) {
  675. // This block contains at least one statement. Find the source location
  676. // of the first statement in the block.
  677. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  678. BE = CurrBlock->end(); BI != BE; ++BI) {
  679. // FIXME: Handle other CFGElement kinds.
  680. if (Optional<CFGStmt> CS = BI->getAs<CFGStmt>()) {
  681. CurrBlockInfo->EntryLoc = CS->getStmt()->getLocStart();
  682. break;
  683. }
  684. }
  685. } else if (CurrBlock->pred_size() == 1 && *CurrBlock->pred_begin() &&
  686. CurrBlock != &CFGraph->getExit()) {
  687. // The block is empty, and has a single predecessor. Use its exit
  688. // location.
  689. CurrBlockInfo->EntryLoc = CurrBlockInfo->ExitLoc =
  690. BlockInfo[(*CurrBlock->pred_begin())->getBlockID()].ExitLoc;
  691. }
  692. }
  693. }
  694. class LockableFactEntry : public FactEntry {
  695. private:
  696. bool Managed; ///< managed by ScopedLockable object
  697. public:
  698. LockableFactEntry(const CapabilityExpr &CE, LockKind LK, SourceLocation Loc,
  699. bool Mng = false, bool Asrt = false)
  700. : FactEntry(CE, LK, Loc, Asrt), Managed(Mng) {}
  701. void
  702. handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
  703. SourceLocation JoinLoc, LockErrorKind LEK,
  704. ThreadSafetyHandler &Handler) const override {
  705. if (!Managed && !asserted() && !negative() && !isUniversal()) {
  706. Handler.handleMutexHeldEndOfScope("mutex", toString(), loc(), JoinLoc,
  707. LEK);
  708. }
  709. }
  710. void handleUnlock(FactSet &FSet, FactManager &FactMan,
  711. const CapabilityExpr &Cp, SourceLocation UnlockLoc,
  712. bool FullyRemove, ThreadSafetyHandler &Handler,
  713. StringRef DiagKind) const override {
  714. FSet.removeLock(FactMan, Cp);
  715. if (!Cp.negative()) {
  716. FSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
  717. !Cp, LK_Exclusive, UnlockLoc));
  718. }
  719. }
  720. };
  721. class ScopedLockableFactEntry : public FactEntry {
  722. private:
  723. SmallVector<const til::SExpr *, 4> UnderlyingMutexes;
  724. public:
  725. ScopedLockableFactEntry(const CapabilityExpr &CE, SourceLocation Loc,
  726. const CapExprSet &Excl, const CapExprSet &Shrd)
  727. : FactEntry(CE, LK_Exclusive, Loc, false) {
  728. for (const auto &M : Excl)
  729. UnderlyingMutexes.push_back(M.sexpr());
  730. for (const auto &M : Shrd)
  731. UnderlyingMutexes.push_back(M.sexpr());
  732. }
  733. void
  734. handleRemovalFromIntersection(const FactSet &FSet, FactManager &FactMan,
  735. SourceLocation JoinLoc, LockErrorKind LEK,
  736. ThreadSafetyHandler &Handler) const override {
  737. for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
  738. if (FSet.findLock(FactMan, CapabilityExpr(UnderlyingMutex, false))) {
  739. // If this scoped lock manages another mutex, and if the underlying
  740. // mutex is still held, then warn about the underlying mutex.
  741. Handler.handleMutexHeldEndOfScope(
  742. "mutex", sx::toString(UnderlyingMutex), loc(), JoinLoc, LEK);
  743. }
  744. }
  745. }
  746. void handleUnlock(FactSet &FSet, FactManager &FactMan,
  747. const CapabilityExpr &Cp, SourceLocation UnlockLoc,
  748. bool FullyRemove, ThreadSafetyHandler &Handler,
  749. StringRef DiagKind) const override {
  750. assert(!Cp.negative() && "Managing object cannot be negative.");
  751. for (const til::SExpr *UnderlyingMutex : UnderlyingMutexes) {
  752. CapabilityExpr UnderCp(UnderlyingMutex, false);
  753. auto UnderEntry = llvm::make_unique<LockableFactEntry>(
  754. !UnderCp, LK_Exclusive, UnlockLoc);
  755. if (FullyRemove) {
  756. // We're destroying the managing object.
  757. // Remove the underlying mutex if it exists; but don't warn.
  758. if (FSet.findLock(FactMan, UnderCp)) {
  759. FSet.removeLock(FactMan, UnderCp);
  760. FSet.addLock(FactMan, std::move(UnderEntry));
  761. }
  762. } else {
  763. // We're releasing the underlying mutex, but not destroying the
  764. // managing object. Warn on dual release.
  765. if (!FSet.findLock(FactMan, UnderCp)) {
  766. Handler.handleUnmatchedUnlock(DiagKind, UnderCp.toString(),
  767. UnlockLoc);
  768. }
  769. FSet.removeLock(FactMan, UnderCp);
  770. FSet.addLock(FactMan, std::move(UnderEntry));
  771. }
  772. }
  773. if (FullyRemove)
  774. FSet.removeLock(FactMan, Cp);
  775. }
  776. };
  777. /// \brief Class which implements the core thread safety analysis routines.
  778. class ThreadSafetyAnalyzer {
  779. friend class BuildLockset;
  780. friend class threadSafety::BeforeSet;
  781. llvm::BumpPtrAllocator Bpa;
  782. threadSafety::til::MemRegionRef Arena;
  783. threadSafety::SExprBuilder SxBuilder;
  784. ThreadSafetyHandler &Handler;
  785. const CXXMethodDecl *CurrentMethod;
  786. LocalVariableMap LocalVarMap;
  787. FactManager FactMan;
  788. std::vector<CFGBlockInfo> BlockInfo;
  789. BeforeSet* GlobalBeforeSet;
  790. public:
  791. ThreadSafetyAnalyzer(ThreadSafetyHandler &H, BeforeSet* Bset)
  792. : Arena(&Bpa), SxBuilder(Arena), Handler(H), GlobalBeforeSet(Bset) {}
  793. bool inCurrentScope(const CapabilityExpr &CapE);
  794. void addLock(FactSet &FSet, std::unique_ptr<FactEntry> Entry,
  795. StringRef DiagKind, bool ReqAttr = false);
  796. void removeLock(FactSet &FSet, const CapabilityExpr &CapE,
  797. SourceLocation UnlockLoc, bool FullyRemove, LockKind Kind,
  798. StringRef DiagKind);
  799. template <typename AttrType>
  800. void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
  801. const NamedDecl *D, VarDecl *SelfDecl = nullptr);
  802. template <class AttrType>
  803. void getMutexIDs(CapExprSet &Mtxs, AttrType *Attr, Expr *Exp,
  804. const NamedDecl *D,
  805. const CFGBlock *PredBlock, const CFGBlock *CurrBlock,
  806. Expr *BrE, bool Neg);
  807. const CallExpr* getTrylockCallExpr(const Stmt *Cond, LocalVarContext C,
  808. bool &Negate);
  809. void getEdgeLockset(FactSet &Result, const FactSet &ExitSet,
  810. const CFGBlock* PredBlock,
  811. const CFGBlock *CurrBlock);
  812. void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
  813. SourceLocation JoinLoc,
  814. LockErrorKind LEK1, LockErrorKind LEK2,
  815. bool Modify=true);
  816. void intersectAndWarn(FactSet &FSet1, const FactSet &FSet2,
  817. SourceLocation JoinLoc, LockErrorKind LEK1,
  818. bool Modify=true) {
  819. intersectAndWarn(FSet1, FSet2, JoinLoc, LEK1, LEK1, Modify);
  820. }
  821. void runAnalysis(AnalysisDeclContext &AC);
  822. };
  823. } // namespace
  824. /// Process acquired_before and acquired_after attributes on Vd.
  825. BeforeSet::BeforeInfo* BeforeSet::insertAttrExprs(const ValueDecl* Vd,
  826. ThreadSafetyAnalyzer& Analyzer) {
  827. // Create a new entry for Vd.
  828. BeforeInfo *Info = nullptr;
  829. {
  830. // Keep InfoPtr in its own scope in case BMap is modified later and the
  831. // reference becomes invalid.
  832. std::unique_ptr<BeforeInfo> &InfoPtr = BMap[Vd];
  833. if (!InfoPtr)
  834. InfoPtr.reset(new BeforeInfo());
  835. Info = InfoPtr.get();
  836. }
  837. for (Attr* At : Vd->attrs()) {
  838. switch (At->getKind()) {
  839. case attr::AcquiredBefore: {
  840. auto *A = cast<AcquiredBeforeAttr>(At);
  841. // Read exprs from the attribute, and add them to BeforeVect.
  842. for (const auto *Arg : A->args()) {
  843. CapabilityExpr Cp =
  844. Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
  845. if (const ValueDecl *Cpvd = Cp.valueDecl()) {
  846. Info->Vect.push_back(Cpvd);
  847. auto It = BMap.find(Cpvd);
  848. if (It == BMap.end())
  849. insertAttrExprs(Cpvd, Analyzer);
  850. }
  851. }
  852. break;
  853. }
  854. case attr::AcquiredAfter: {
  855. auto *A = cast<AcquiredAfterAttr>(At);
  856. // Read exprs from the attribute, and add them to BeforeVect.
  857. for (const auto *Arg : A->args()) {
  858. CapabilityExpr Cp =
  859. Analyzer.SxBuilder.translateAttrExpr(Arg, nullptr);
  860. if (const ValueDecl *ArgVd = Cp.valueDecl()) {
  861. // Get entry for mutex listed in attribute
  862. BeforeInfo *ArgInfo = getBeforeInfoForDecl(ArgVd, Analyzer);
  863. ArgInfo->Vect.push_back(Vd);
  864. }
  865. }
  866. break;
  867. }
  868. default:
  869. break;
  870. }
  871. }
  872. return Info;
  873. }
  874. BeforeSet::BeforeInfo *
  875. BeforeSet::getBeforeInfoForDecl(const ValueDecl *Vd,
  876. ThreadSafetyAnalyzer &Analyzer) {
  877. auto It = BMap.find(Vd);
  878. BeforeInfo *Info = nullptr;
  879. if (It == BMap.end())
  880. Info = insertAttrExprs(Vd, Analyzer);
  881. else
  882. Info = It->second.get();
  883. assert(Info && "BMap contained nullptr?");
  884. return Info;
  885. }
  886. /// Return true if any mutexes in FSet are in the acquired_before set of Vd.
  887. void BeforeSet::checkBeforeAfter(const ValueDecl* StartVd,
  888. const FactSet& FSet,
  889. ThreadSafetyAnalyzer& Analyzer,
  890. SourceLocation Loc, StringRef CapKind) {
  891. SmallVector<BeforeInfo*, 8> InfoVect;
  892. // Do a depth-first traversal of Vd.
  893. // Return true if there are cycles.
  894. std::function<bool (const ValueDecl*)> traverse = [&](const ValueDecl* Vd) {
  895. if (!Vd)
  896. return false;
  897. BeforeSet::BeforeInfo *Info = getBeforeInfoForDecl(Vd, Analyzer);
  898. if (Info->Visited == 1)
  899. return true;
  900. if (Info->Visited == 2)
  901. return false;
  902. if (Info->Vect.empty())
  903. return false;
  904. InfoVect.push_back(Info);
  905. Info->Visited = 1;
  906. for (auto *Vdb : Info->Vect) {
  907. // Exclude mutexes in our immediate before set.
  908. if (FSet.containsMutexDecl(Analyzer.FactMan, Vdb)) {
  909. StringRef L1 = StartVd->getName();
  910. StringRef L2 = Vdb->getName();
  911. Analyzer.Handler.handleLockAcquiredBefore(CapKind, L1, L2, Loc);
  912. }
  913. // Transitively search other before sets, and warn on cycles.
  914. if (traverse(Vdb)) {
  915. if (CycMap.find(Vd) == CycMap.end()) {
  916. CycMap.insert(std::make_pair(Vd, true));
  917. StringRef L1 = Vd->getName();
  918. Analyzer.Handler.handleBeforeAfterCycle(L1, Vd->getLocation());
  919. }
  920. }
  921. }
  922. Info->Visited = 2;
  923. return false;
  924. };
  925. traverse(StartVd);
  926. for (auto* Info : InfoVect)
  927. Info->Visited = 0;
  928. }
  929. /// \brief Gets the value decl pointer from DeclRefExprs or MemberExprs.
  930. static const ValueDecl *getValueDecl(const Expr *Exp) {
  931. if (const auto *CE = dyn_cast<ImplicitCastExpr>(Exp))
  932. return getValueDecl(CE->getSubExpr());
  933. if (const auto *DR = dyn_cast<DeclRefExpr>(Exp))
  934. return DR->getDecl();
  935. if (const auto *ME = dyn_cast<MemberExpr>(Exp))
  936. return ME->getMemberDecl();
  937. return nullptr;
  938. }
  939. namespace {
  940. template <typename Ty>
  941. class has_arg_iterator_range {
  942. typedef char yes[1];
  943. typedef char no[2];
  944. template <typename Inner>
  945. static yes& test(Inner *I, decltype(I->args()) * = nullptr);
  946. template <typename>
  947. static no& test(...);
  948. public:
  949. static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
  950. };
  951. } // namespace
  952. static StringRef ClassifyDiagnostic(const CapabilityAttr *A) {
  953. return A->getName();
  954. }
  955. static StringRef ClassifyDiagnostic(QualType VDT) {
  956. // We need to look at the declaration of the type of the value to determine
  957. // which it is. The type should either be a record or a typedef, or a pointer
  958. // or reference thereof.
  959. if (const auto *RT = VDT->getAs<RecordType>()) {
  960. if (const auto *RD = RT->getDecl())
  961. if (const auto *CA = RD->getAttr<CapabilityAttr>())
  962. return ClassifyDiagnostic(CA);
  963. } else if (const auto *TT = VDT->getAs<TypedefType>()) {
  964. if (const auto *TD = TT->getDecl())
  965. if (const auto *CA = TD->getAttr<CapabilityAttr>())
  966. return ClassifyDiagnostic(CA);
  967. } else if (VDT->isPointerType() || VDT->isReferenceType())
  968. return ClassifyDiagnostic(VDT->getPointeeType());
  969. return "mutex";
  970. }
  971. static StringRef ClassifyDiagnostic(const ValueDecl *VD) {
  972. assert(VD && "No ValueDecl passed");
  973. // The ValueDecl is the declaration of a mutex or role (hopefully).
  974. return ClassifyDiagnostic(VD->getType());
  975. }
  976. template <typename AttrTy>
  977. static typename std::enable_if<!has_arg_iterator_range<AttrTy>::value,
  978. StringRef>::type
  979. ClassifyDiagnostic(const AttrTy *A) {
  980. if (const ValueDecl *VD = getValueDecl(A->getArg()))
  981. return ClassifyDiagnostic(VD);
  982. return "mutex";
  983. }
  984. template <typename AttrTy>
  985. static typename std::enable_if<has_arg_iterator_range<AttrTy>::value,
  986. StringRef>::type
  987. ClassifyDiagnostic(const AttrTy *A) {
  988. for (const auto *Arg : A->args()) {
  989. if (const ValueDecl *VD = getValueDecl(Arg))
  990. return ClassifyDiagnostic(VD);
  991. }
  992. return "mutex";
  993. }
  994. inline bool ThreadSafetyAnalyzer::inCurrentScope(const CapabilityExpr &CapE) {
  995. if (!CurrentMethod)
  996. return false;
  997. if (auto *P = dyn_cast_or_null<til::Project>(CapE.sexpr())) {
  998. auto *VD = P->clangDecl();
  999. if (VD)
  1000. return VD->getDeclContext() == CurrentMethod->getDeclContext();
  1001. }
  1002. return false;
  1003. }
  1004. /// \brief Add a new lock to the lockset, warning if the lock is already there.
  1005. /// \param ReqAttr -- true if this is part of an initial Requires attribute.
  1006. void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
  1007. std::unique_ptr<FactEntry> Entry,
  1008. StringRef DiagKind, bool ReqAttr) {
  1009. if (Entry->shouldIgnore())
  1010. return;
  1011. if (!ReqAttr && !Entry->negative()) {
  1012. // look for the negative capability, and remove it from the fact set.
  1013. CapabilityExpr NegC = !*Entry;
  1014. FactEntry *Nen = FSet.findLock(FactMan, NegC);
  1015. if (Nen) {
  1016. FSet.removeLock(FactMan, NegC);
  1017. }
  1018. else {
  1019. if (inCurrentScope(*Entry) && !Entry->asserted())
  1020. Handler.handleNegativeNotHeld(DiagKind, Entry->toString(),
  1021. NegC.toString(), Entry->loc());
  1022. }
  1023. }
  1024. // Check before/after constraints
  1025. if (Handler.issueBetaWarnings() &&
  1026. !Entry->asserted() && !Entry->declared()) {
  1027. GlobalBeforeSet->checkBeforeAfter(Entry->valueDecl(), FSet, *this,
  1028. Entry->loc(), DiagKind);
  1029. }
  1030. // FIXME: Don't always warn when we have support for reentrant locks.
  1031. if (FSet.findLock(FactMan, *Entry)) {
  1032. if (!Entry->asserted())
  1033. Handler.handleDoubleLock(DiagKind, Entry->toString(), Entry->loc());
  1034. } else {
  1035. FSet.addLock(FactMan, std::move(Entry));
  1036. }
  1037. }
  1038. /// \brief Remove a lock from the lockset, warning if the lock is not there.
  1039. /// \param UnlockLoc The source location of the unlock (only used in error msg)
  1040. void ThreadSafetyAnalyzer::removeLock(FactSet &FSet, const CapabilityExpr &Cp,
  1041. SourceLocation UnlockLoc,
  1042. bool FullyRemove, LockKind ReceivedKind,
  1043. StringRef DiagKind) {
  1044. if (Cp.shouldIgnore())
  1045. return;
  1046. const FactEntry *LDat = FSet.findLock(FactMan, Cp);
  1047. if (!LDat) {
  1048. Handler.handleUnmatchedUnlock(DiagKind, Cp.toString(), UnlockLoc);
  1049. return;
  1050. }
  1051. // Generic lock removal doesn't care about lock kind mismatches, but
  1052. // otherwise diagnose when the lock kinds are mismatched.
  1053. if (ReceivedKind != LK_Generic && LDat->kind() != ReceivedKind) {
  1054. Handler.handleIncorrectUnlockKind(DiagKind, Cp.toString(),
  1055. LDat->kind(), ReceivedKind, UnlockLoc);
  1056. }
  1057. LDat->handleUnlock(FSet, FactMan, Cp, UnlockLoc, FullyRemove, Handler,
  1058. DiagKind);
  1059. }
  1060. /// \brief Extract the list of mutexIDs from the attribute on an expression,
  1061. /// and push them onto Mtxs, discarding any duplicates.
  1062. template <typename AttrType>
  1063. void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
  1064. Expr *Exp, const NamedDecl *D,
  1065. VarDecl *SelfDecl) {
  1066. if (Attr->args_size() == 0) {
  1067. // The mutex held is the "this" object.
  1068. CapabilityExpr Cp = SxBuilder.translateAttrExpr(nullptr, D, Exp, SelfDecl);
  1069. if (Cp.isInvalid()) {
  1070. warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
  1071. return;
  1072. }
  1073. //else
  1074. if (!Cp.shouldIgnore())
  1075. Mtxs.push_back_nodup(Cp);
  1076. return;
  1077. }
  1078. for (const auto *Arg : Attr->args()) {
  1079. CapabilityExpr Cp = SxBuilder.translateAttrExpr(Arg, D, Exp, SelfDecl);
  1080. if (Cp.isInvalid()) {
  1081. warnInvalidLock(Handler, nullptr, D, Exp, ClassifyDiagnostic(Attr));
  1082. continue;
  1083. }
  1084. //else
  1085. if (!Cp.shouldIgnore())
  1086. Mtxs.push_back_nodup(Cp);
  1087. }
  1088. }
  1089. /// \brief Extract the list of mutexIDs from a trylock attribute. If the
  1090. /// trylock applies to the given edge, then push them onto Mtxs, discarding
  1091. /// any duplicates.
  1092. template <class AttrType>
  1093. void ThreadSafetyAnalyzer::getMutexIDs(CapExprSet &Mtxs, AttrType *Attr,
  1094. Expr *Exp, const NamedDecl *D,
  1095. const CFGBlock *PredBlock,
  1096. const CFGBlock *CurrBlock,
  1097. Expr *BrE, bool Neg) {
  1098. // Find out which branch has the lock
  1099. bool branch = false;
  1100. if (CXXBoolLiteralExpr *BLE = dyn_cast_or_null<CXXBoolLiteralExpr>(BrE))
  1101. branch = BLE->getValue();
  1102. else if (IntegerLiteral *ILE = dyn_cast_or_null<IntegerLiteral>(BrE))
  1103. branch = ILE->getValue().getBoolValue();
  1104. int branchnum = branch ? 0 : 1;
  1105. if (Neg)
  1106. branchnum = !branchnum;
  1107. // If we've taken the trylock branch, then add the lock
  1108. int i = 0;
  1109. for (CFGBlock::const_succ_iterator SI = PredBlock->succ_begin(),
  1110. SE = PredBlock->succ_end(); SI != SE && i < 2; ++SI, ++i) {
  1111. if (*SI == CurrBlock && i == branchnum)
  1112. getMutexIDs(Mtxs, Attr, Exp, D);
  1113. }
  1114. }
  1115. static bool getStaticBooleanValue(Expr *E, bool &TCond) {
  1116. if (isa<CXXNullPtrLiteralExpr>(E) || isa<GNUNullExpr>(E)) {
  1117. TCond = false;
  1118. return true;
  1119. } else if (CXXBoolLiteralExpr *BLE = dyn_cast<CXXBoolLiteralExpr>(E)) {
  1120. TCond = BLE->getValue();
  1121. return true;
  1122. } else if (IntegerLiteral *ILE = dyn_cast<IntegerLiteral>(E)) {
  1123. TCond = ILE->getValue().getBoolValue();
  1124. return true;
  1125. } else if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
  1126. return getStaticBooleanValue(CE->getSubExpr(), TCond);
  1127. }
  1128. return false;
  1129. }
  1130. // If Cond can be traced back to a function call, return the call expression.
  1131. // The negate variable should be called with false, and will be set to true
  1132. // if the function call is negated, e.g. if (!mu.tryLock(...))
  1133. const CallExpr* ThreadSafetyAnalyzer::getTrylockCallExpr(const Stmt *Cond,
  1134. LocalVarContext C,
  1135. bool &Negate) {
  1136. if (!Cond)
  1137. return nullptr;
  1138. if (const CallExpr *CallExp = dyn_cast<CallExpr>(Cond)) {
  1139. return CallExp;
  1140. }
  1141. else if (const ParenExpr *PE = dyn_cast<ParenExpr>(Cond)) {
  1142. return getTrylockCallExpr(PE->getSubExpr(), C, Negate);
  1143. }
  1144. else if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(Cond)) {
  1145. return getTrylockCallExpr(CE->getSubExpr(), C, Negate);
  1146. }
  1147. else if (const ExprWithCleanups* EWC = dyn_cast<ExprWithCleanups>(Cond)) {
  1148. return getTrylockCallExpr(EWC->getSubExpr(), C, Negate);
  1149. }
  1150. else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Cond)) {
  1151. const Expr *E = LocalVarMap.lookupExpr(DRE->getDecl(), C);
  1152. return getTrylockCallExpr(E, C, Negate);
  1153. }
  1154. else if (const UnaryOperator *UOP = dyn_cast<UnaryOperator>(Cond)) {
  1155. if (UOP->getOpcode() == UO_LNot) {
  1156. Negate = !Negate;
  1157. return getTrylockCallExpr(UOP->getSubExpr(), C, Negate);
  1158. }
  1159. return nullptr;
  1160. }
  1161. else if (const BinaryOperator *BOP = dyn_cast<BinaryOperator>(Cond)) {
  1162. if (BOP->getOpcode() == BO_EQ || BOP->getOpcode() == BO_NE) {
  1163. if (BOP->getOpcode() == BO_NE)
  1164. Negate = !Negate;
  1165. bool TCond = false;
  1166. if (getStaticBooleanValue(BOP->getRHS(), TCond)) {
  1167. if (!TCond) Negate = !Negate;
  1168. return getTrylockCallExpr(BOP->getLHS(), C, Negate);
  1169. }
  1170. TCond = false;
  1171. if (getStaticBooleanValue(BOP->getLHS(), TCond)) {
  1172. if (!TCond) Negate = !Negate;
  1173. return getTrylockCallExpr(BOP->getRHS(), C, Negate);
  1174. }
  1175. return nullptr;
  1176. }
  1177. if (BOP->getOpcode() == BO_LAnd) {
  1178. // LHS must have been evaluated in a different block.
  1179. return getTrylockCallExpr(BOP->getRHS(), C, Negate);
  1180. }
  1181. if (BOP->getOpcode() == BO_LOr) {
  1182. return getTrylockCallExpr(BOP->getRHS(), C, Negate);
  1183. }
  1184. return nullptr;
  1185. }
  1186. return nullptr;
  1187. }
  1188. /// \brief Find the lockset that holds on the edge between PredBlock
  1189. /// and CurrBlock. The edge set is the exit set of PredBlock (passed
  1190. /// as the ExitSet parameter) plus any trylocks, which are conditionally held.
  1191. void ThreadSafetyAnalyzer::getEdgeLockset(FactSet& Result,
  1192. const FactSet &ExitSet,
  1193. const CFGBlock *PredBlock,
  1194. const CFGBlock *CurrBlock) {
  1195. Result = ExitSet;
  1196. const Stmt *Cond = PredBlock->getTerminatorCondition();
  1197. if (!Cond)
  1198. return;
  1199. bool Negate = false;
  1200. const CFGBlockInfo *PredBlockInfo = &BlockInfo[PredBlock->getBlockID()];
  1201. const LocalVarContext &LVarCtx = PredBlockInfo->ExitContext;
  1202. StringRef CapDiagKind = "mutex";
  1203. CallExpr *Exp =
  1204. const_cast<CallExpr*>(getTrylockCallExpr(Cond, LVarCtx, Negate));
  1205. if (!Exp)
  1206. return;
  1207. NamedDecl *FunDecl = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
  1208. if(!FunDecl || !FunDecl->hasAttrs())
  1209. return;
  1210. CapExprSet ExclusiveLocksToAdd;
  1211. CapExprSet SharedLocksToAdd;
  1212. // If the condition is a call to a Trylock function, then grab the attributes
  1213. for (auto *Attr : FunDecl->attrs()) {
  1214. switch (Attr->getKind()) {
  1215. case attr::ExclusiveTrylockFunction: {
  1216. ExclusiveTrylockFunctionAttr *A =
  1217. cast<ExclusiveTrylockFunctionAttr>(Attr);
  1218. getMutexIDs(ExclusiveLocksToAdd, A, Exp, FunDecl,
  1219. PredBlock, CurrBlock, A->getSuccessValue(), Negate);
  1220. CapDiagKind = ClassifyDiagnostic(A);
  1221. break;
  1222. }
  1223. case attr::SharedTrylockFunction: {
  1224. SharedTrylockFunctionAttr *A =
  1225. cast<SharedTrylockFunctionAttr>(Attr);
  1226. getMutexIDs(SharedLocksToAdd, A, Exp, FunDecl,
  1227. PredBlock, CurrBlock, A->getSuccessValue(), Negate);
  1228. CapDiagKind = ClassifyDiagnostic(A);
  1229. break;
  1230. }
  1231. default:
  1232. break;
  1233. }
  1234. }
  1235. // Add and remove locks.
  1236. SourceLocation Loc = Exp->getExprLoc();
  1237. for (const auto &ExclusiveLockToAdd : ExclusiveLocksToAdd)
  1238. addLock(Result, llvm::make_unique<LockableFactEntry>(ExclusiveLockToAdd,
  1239. LK_Exclusive, Loc),
  1240. CapDiagKind);
  1241. for (const auto &SharedLockToAdd : SharedLocksToAdd)
  1242. addLock(Result, llvm::make_unique<LockableFactEntry>(SharedLockToAdd,
  1243. LK_Shared, Loc),
  1244. CapDiagKind);
  1245. }
  1246. namespace {
  1247. /// \brief We use this class to visit different types of expressions in
  1248. /// CFGBlocks, and build up the lockset.
  1249. /// An expression may cause us to add or remove locks from the lockset, or else
  1250. /// output error messages related to missing locks.
  1251. /// FIXME: In future, we may be able to not inherit from a visitor.
  1252. class BuildLockset : public StmtVisitor<BuildLockset> {
  1253. friend class ThreadSafetyAnalyzer;
  1254. ThreadSafetyAnalyzer *Analyzer;
  1255. FactSet FSet;
  1256. LocalVariableMap::Context LVarCtx;
  1257. unsigned CtxIndex;
  1258. // helper functions
  1259. void warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp, AccessKind AK,
  1260. Expr *MutexExp, ProtectedOperationKind POK,
  1261. StringRef DiagKind, SourceLocation Loc);
  1262. void warnIfMutexHeld(const NamedDecl *D, const Expr *Exp, Expr *MutexExp,
  1263. StringRef DiagKind);
  1264. void checkAccess(const Expr *Exp, AccessKind AK,
  1265. ProtectedOperationKind POK = POK_VarAccess);
  1266. void checkPtAccess(const Expr *Exp, AccessKind AK,
  1267. ProtectedOperationKind POK = POK_VarAccess);
  1268. void handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD = nullptr);
  1269. public:
  1270. BuildLockset(ThreadSafetyAnalyzer *Anlzr, CFGBlockInfo &Info)
  1271. : StmtVisitor<BuildLockset>(),
  1272. Analyzer(Anlzr),
  1273. FSet(Info.EntrySet),
  1274. LVarCtx(Info.EntryContext),
  1275. CtxIndex(Info.EntryIndex)
  1276. {}
  1277. void VisitUnaryOperator(UnaryOperator *UO);
  1278. void VisitBinaryOperator(BinaryOperator *BO);
  1279. void VisitCastExpr(CastExpr *CE);
  1280. void VisitCallExpr(CallExpr *Exp);
  1281. void VisitCXXConstructExpr(CXXConstructExpr *Exp);
  1282. void VisitDeclStmt(DeclStmt *S);
  1283. };
  1284. } // namespace
  1285. /// \brief Warn if the LSet does not contain a lock sufficient to protect access
  1286. /// of at least the passed in AccessKind.
  1287. void BuildLockset::warnIfMutexNotHeld(const NamedDecl *D, const Expr *Exp,
  1288. AccessKind AK, Expr *MutexExp,
  1289. ProtectedOperationKind POK,
  1290. StringRef DiagKind, SourceLocation Loc) {
  1291. LockKind LK = getLockKindFromAccessKind(AK);
  1292. CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
  1293. if (Cp.isInvalid()) {
  1294. warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
  1295. return;
  1296. } else if (Cp.shouldIgnore()) {
  1297. return;
  1298. }
  1299. if (Cp.negative()) {
  1300. // Negative capabilities act like locks excluded
  1301. FactEntry *LDat = FSet.findLock(Analyzer->FactMan, !Cp);
  1302. if (LDat) {
  1303. Analyzer->Handler.handleFunExcludesLock(
  1304. DiagKind, D->getNameAsString(), (!Cp).toString(), Loc);
  1305. return;
  1306. }
  1307. // If this does not refer to a negative capability in the same class,
  1308. // then stop here.
  1309. if (!Analyzer->inCurrentScope(Cp))
  1310. return;
  1311. // Otherwise the negative requirement must be propagated to the caller.
  1312. LDat = FSet.findLock(Analyzer->FactMan, Cp);
  1313. if (!LDat) {
  1314. Analyzer->Handler.handleMutexNotHeld("", D, POK, Cp.toString(),
  1315. LK_Shared, Loc);
  1316. }
  1317. return;
  1318. }
  1319. FactEntry* LDat = FSet.findLockUniv(Analyzer->FactMan, Cp);
  1320. bool NoError = true;
  1321. if (!LDat) {
  1322. // No exact match found. Look for a partial match.
  1323. LDat = FSet.findPartialMatch(Analyzer->FactMan, Cp);
  1324. if (LDat) {
  1325. // Warn that there's no precise match.
  1326. std::string PartMatchStr = LDat->toString();
  1327. StringRef PartMatchName(PartMatchStr);
  1328. Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
  1329. LK, Loc, &PartMatchName);
  1330. } else {
  1331. // Warn that there's no match at all.
  1332. Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
  1333. LK, Loc);
  1334. }
  1335. NoError = false;
  1336. }
  1337. // Make sure the mutex we found is the right kind.
  1338. if (NoError && LDat && !LDat->isAtLeast(LK)) {
  1339. Analyzer->Handler.handleMutexNotHeld(DiagKind, D, POK, Cp.toString(),
  1340. LK, Loc);
  1341. }
  1342. }
  1343. /// \brief Warn if the LSet contains the given lock.
  1344. void BuildLockset::warnIfMutexHeld(const NamedDecl *D, const Expr *Exp,
  1345. Expr *MutexExp, StringRef DiagKind) {
  1346. CapabilityExpr Cp = Analyzer->SxBuilder.translateAttrExpr(MutexExp, D, Exp);
  1347. if (Cp.isInvalid()) {
  1348. warnInvalidLock(Analyzer->Handler, MutexExp, D, Exp, DiagKind);
  1349. return;
  1350. } else if (Cp.shouldIgnore()) {
  1351. return;
  1352. }
  1353. FactEntry* LDat = FSet.findLock(Analyzer->FactMan, Cp);
  1354. if (LDat) {
  1355. Analyzer->Handler.handleFunExcludesLock(
  1356. DiagKind, D->getNameAsString(), Cp.toString(), Exp->getExprLoc());
  1357. }
  1358. }
  1359. /// \brief Checks guarded_by and pt_guarded_by attributes.
  1360. /// Whenever we identify an access (read or write) to a DeclRefExpr that is
  1361. /// marked with guarded_by, we must ensure the appropriate mutexes are held.
  1362. /// Similarly, we check if the access is to an expression that dereferences
  1363. /// a pointer marked with pt_guarded_by.
  1364. void BuildLockset::checkAccess(const Expr *Exp, AccessKind AK,
  1365. ProtectedOperationKind POK) {
  1366. Exp = Exp->IgnoreParenCasts();
  1367. SourceLocation Loc = Exp->getExprLoc();
  1368. // Local variables of reference type cannot be re-assigned;
  1369. // map them to their initializer.
  1370. while (const auto *DRE = dyn_cast<DeclRefExpr>(Exp)) {
  1371. const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()->getCanonicalDecl());
  1372. if (VD && VD->isLocalVarDecl() && VD->getType()->isReferenceType()) {
  1373. if (const auto *E = VD->getInit()) {
  1374. Exp = E;
  1375. continue;
  1376. }
  1377. }
  1378. break;
  1379. }
  1380. if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Exp)) {
  1381. // For dereferences
  1382. if (UO->getOpcode() == clang::UO_Deref)
  1383. checkPtAccess(UO->getSubExpr(), AK, POK);
  1384. return;
  1385. }
  1386. if (const ArraySubscriptExpr *AE = dyn_cast<ArraySubscriptExpr>(Exp)) {
  1387. checkPtAccess(AE->getLHS(), AK, POK);
  1388. return;
  1389. }
  1390. if (const MemberExpr *ME = dyn_cast<MemberExpr>(Exp)) {
  1391. if (ME->isArrow())
  1392. checkPtAccess(ME->getBase(), AK, POK);
  1393. else
  1394. checkAccess(ME->getBase(), AK, POK);
  1395. }
  1396. const ValueDecl *D = getValueDecl(Exp);
  1397. if (!D || !D->hasAttrs())
  1398. return;
  1399. if (D->hasAttr<GuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan)) {
  1400. Analyzer->Handler.handleNoMutexHeld("mutex", D, POK, AK, Loc);
  1401. }
  1402. for (const auto *I : D->specific_attrs<GuardedByAttr>())
  1403. warnIfMutexNotHeld(D, Exp, AK, I->getArg(), POK,
  1404. ClassifyDiagnostic(I), Loc);
  1405. }
  1406. /// \brief Checks pt_guarded_by and pt_guarded_var attributes.
  1407. /// POK is the same operationKind that was passed to checkAccess.
  1408. void BuildLockset::checkPtAccess(const Expr *Exp, AccessKind AK,
  1409. ProtectedOperationKind POK) {
  1410. while (true) {
  1411. if (const ParenExpr *PE = dyn_cast<ParenExpr>(Exp)) {
  1412. Exp = PE->getSubExpr();
  1413. continue;
  1414. }
  1415. if (const CastExpr *CE = dyn_cast<CastExpr>(Exp)) {
  1416. if (CE->getCastKind() == CK_ArrayToPointerDecay) {
  1417. // If it's an actual array, and not a pointer, then it's elements
  1418. // are protected by GUARDED_BY, not PT_GUARDED_BY;
  1419. checkAccess(CE->getSubExpr(), AK, POK);
  1420. return;
  1421. }
  1422. Exp = CE->getSubExpr();
  1423. continue;
  1424. }
  1425. break;
  1426. }
  1427. // Pass by reference warnings are under a different flag.
  1428. ProtectedOperationKind PtPOK = POK_VarDereference;
  1429. if (POK == POK_PassByRef) PtPOK = POK_PtPassByRef;
  1430. const ValueDecl *D = getValueDecl(Exp);
  1431. if (!D || !D->hasAttrs())
  1432. return;
  1433. if (D->hasAttr<PtGuardedVarAttr>() && FSet.isEmpty(Analyzer->FactMan))
  1434. Analyzer->Handler.handleNoMutexHeld("mutex", D, PtPOK, AK,
  1435. Exp->getExprLoc());
  1436. for (auto const *I : D->specific_attrs<PtGuardedByAttr>())
  1437. warnIfMutexNotHeld(D, Exp, AK, I->getArg(), PtPOK,
  1438. ClassifyDiagnostic(I), Exp->getExprLoc());
  1439. }
  1440. /// \brief Process a function call, method call, constructor call,
  1441. /// or destructor call. This involves looking at the attributes on the
  1442. /// corresponding function/method/constructor/destructor, issuing warnings,
  1443. /// and updating the locksets accordingly.
  1444. ///
  1445. /// FIXME: For classes annotated with one of the guarded annotations, we need
  1446. /// to treat const method calls as reads and non-const method calls as writes,
  1447. /// and check that the appropriate locks are held. Non-const method calls with
  1448. /// the same signature as const method calls can be also treated as reads.
  1449. ///
  1450. void BuildLockset::handleCall(Expr *Exp, const NamedDecl *D, VarDecl *VD) {
  1451. SourceLocation Loc = Exp->getExprLoc();
  1452. CapExprSet ExclusiveLocksToAdd, SharedLocksToAdd;
  1453. CapExprSet ExclusiveLocksToRemove, SharedLocksToRemove, GenericLocksToRemove;
  1454. CapExprSet ScopedExclusiveReqs, ScopedSharedReqs;
  1455. StringRef CapDiagKind = "mutex";
  1456. // Figure out if we're calling the constructor of scoped lockable class
  1457. bool isScopedVar = false;
  1458. if (VD) {
  1459. if (const CXXConstructorDecl *CD = dyn_cast<const CXXConstructorDecl>(D)) {
  1460. const CXXRecordDecl* PD = CD->getParent();
  1461. if (PD && PD->hasAttr<ScopedLockableAttr>())
  1462. isScopedVar = true;
  1463. }
  1464. }
  1465. for(Attr *Atconst : D->attrs()) {
  1466. Attr* At = const_cast<Attr*>(Atconst);
  1467. switch (At->getKind()) {
  1468. // When we encounter a lock function, we need to add the lock to our
  1469. // lockset.
  1470. case attr::AcquireCapability: {
  1471. auto *A = cast<AcquireCapabilityAttr>(At);
  1472. Analyzer->getMutexIDs(A->isShared() ? SharedLocksToAdd
  1473. : ExclusiveLocksToAdd,
  1474. A, Exp, D, VD);
  1475. CapDiagKind = ClassifyDiagnostic(A);
  1476. break;
  1477. }
  1478. // An assert will add a lock to the lockset, but will not generate
  1479. // a warning if it is already there, and will not generate a warning
  1480. // if it is not removed.
  1481. case attr::AssertExclusiveLock: {
  1482. AssertExclusiveLockAttr *A = cast<AssertExclusiveLockAttr>(At);
  1483. CapExprSet AssertLocks;
  1484. Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
  1485. for (const auto &AssertLock : AssertLocks)
  1486. Analyzer->addLock(FSet,
  1487. llvm::make_unique<LockableFactEntry>(
  1488. AssertLock, LK_Exclusive, Loc, false, true),
  1489. ClassifyDiagnostic(A));
  1490. break;
  1491. }
  1492. case attr::AssertSharedLock: {
  1493. AssertSharedLockAttr *A = cast<AssertSharedLockAttr>(At);
  1494. CapExprSet AssertLocks;
  1495. Analyzer->getMutexIDs(AssertLocks, A, Exp, D, VD);
  1496. for (const auto &AssertLock : AssertLocks)
  1497. Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
  1498. AssertLock, LK_Shared, Loc, false, true),
  1499. ClassifyDiagnostic(A));
  1500. break;
  1501. }
  1502. // When we encounter an unlock function, we need to remove unlocked
  1503. // mutexes from the lockset, and flag a warning if they are not there.
  1504. case attr::ReleaseCapability: {
  1505. auto *A = cast<ReleaseCapabilityAttr>(At);
  1506. if (A->isGeneric())
  1507. Analyzer->getMutexIDs(GenericLocksToRemove, A, Exp, D, VD);
  1508. else if (A->isShared())
  1509. Analyzer->getMutexIDs(SharedLocksToRemove, A, Exp, D, VD);
  1510. else
  1511. Analyzer->getMutexIDs(ExclusiveLocksToRemove, A, Exp, D, VD);
  1512. CapDiagKind = ClassifyDiagnostic(A);
  1513. break;
  1514. }
  1515. case attr::RequiresCapability: {
  1516. RequiresCapabilityAttr *A = cast<RequiresCapabilityAttr>(At);
  1517. for (auto *Arg : A->args()) {
  1518. warnIfMutexNotHeld(D, Exp, A->isShared() ? AK_Read : AK_Written, Arg,
  1519. POK_FunctionCall, ClassifyDiagnostic(A),
  1520. Exp->getExprLoc());
  1521. // use for adopting a lock
  1522. if (isScopedVar) {
  1523. Analyzer->getMutexIDs(A->isShared() ? ScopedSharedReqs
  1524. : ScopedExclusiveReqs,
  1525. A, Exp, D, VD);
  1526. }
  1527. }
  1528. break;
  1529. }
  1530. case attr::LocksExcluded: {
  1531. LocksExcludedAttr *A = cast<LocksExcludedAttr>(At);
  1532. for (auto *Arg : A->args())
  1533. warnIfMutexHeld(D, Exp, Arg, ClassifyDiagnostic(A));
  1534. break;
  1535. }
  1536. // Ignore attributes unrelated to thread-safety
  1537. default:
  1538. break;
  1539. }
  1540. }
  1541. // Add locks.
  1542. for (const auto &M : ExclusiveLocksToAdd)
  1543. Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
  1544. M, LK_Exclusive, Loc, isScopedVar),
  1545. CapDiagKind);
  1546. for (const auto &M : SharedLocksToAdd)
  1547. Analyzer->addLock(FSet, llvm::make_unique<LockableFactEntry>(
  1548. M, LK_Shared, Loc, isScopedVar),
  1549. CapDiagKind);
  1550. if (isScopedVar) {
  1551. // Add the managing object as a dummy mutex, mapped to the underlying mutex.
  1552. SourceLocation MLoc = VD->getLocation();
  1553. DeclRefExpr DRE(VD, false, VD->getType(), VK_LValue, VD->getLocation());
  1554. // FIXME: does this store a pointer to DRE?
  1555. CapabilityExpr Scp = Analyzer->SxBuilder.translateAttrExpr(&DRE, nullptr);
  1556. std::copy(ScopedExclusiveReqs.begin(), ScopedExclusiveReqs.end(),
  1557. std::back_inserter(ExclusiveLocksToAdd));
  1558. std::copy(ScopedSharedReqs.begin(), ScopedSharedReqs.end(),
  1559. std::back_inserter(SharedLocksToAdd));
  1560. Analyzer->addLock(FSet,
  1561. llvm::make_unique<ScopedLockableFactEntry>(
  1562. Scp, MLoc, ExclusiveLocksToAdd, SharedLocksToAdd),
  1563. CapDiagKind);
  1564. }
  1565. // Remove locks.
  1566. // FIXME -- should only fully remove if the attribute refers to 'this'.
  1567. bool Dtor = isa<CXXDestructorDecl>(D);
  1568. for (const auto &M : ExclusiveLocksToRemove)
  1569. Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Exclusive, CapDiagKind);
  1570. for (const auto &M : SharedLocksToRemove)
  1571. Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Shared, CapDiagKind);
  1572. for (const auto &M : GenericLocksToRemove)
  1573. Analyzer->removeLock(FSet, M, Loc, Dtor, LK_Generic, CapDiagKind);
  1574. }
  1575. /// \brief For unary operations which read and write a variable, we need to
  1576. /// check whether we hold any required mutexes. Reads are checked in
  1577. /// VisitCastExpr.
  1578. void BuildLockset::VisitUnaryOperator(UnaryOperator *UO) {
  1579. switch (UO->getOpcode()) {
  1580. case clang::UO_PostDec:
  1581. case clang::UO_PostInc:
  1582. case clang::UO_PreDec:
  1583. case clang::UO_PreInc: {
  1584. checkAccess(UO->getSubExpr(), AK_Written);
  1585. break;
  1586. }
  1587. default:
  1588. break;
  1589. }
  1590. }
  1591. /// For binary operations which assign to a variable (writes), we need to check
  1592. /// whether we hold any required mutexes.
  1593. /// FIXME: Deal with non-primitive types.
  1594. void BuildLockset::VisitBinaryOperator(BinaryOperator *BO) {
  1595. if (!BO->isAssignmentOp())
  1596. return;
  1597. // adjust the context
  1598. LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, BO, LVarCtx);
  1599. checkAccess(BO->getLHS(), AK_Written);
  1600. }
  1601. /// Whenever we do an LValue to Rvalue cast, we are reading a variable and
  1602. /// need to ensure we hold any required mutexes.
  1603. /// FIXME: Deal with non-primitive types.
  1604. void BuildLockset::VisitCastExpr(CastExpr *CE) {
  1605. if (CE->getCastKind() != CK_LValueToRValue)
  1606. return;
  1607. checkAccess(CE->getSubExpr(), AK_Read);
  1608. }
  1609. void BuildLockset::VisitCallExpr(CallExpr *Exp) {
  1610. bool ExamineArgs = true;
  1611. bool OperatorFun = false;
  1612. if (CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Exp)) {
  1613. MemberExpr *ME = dyn_cast<MemberExpr>(CE->getCallee());
  1614. // ME can be null when calling a method pointer
  1615. CXXMethodDecl *MD = CE->getMethodDecl();
  1616. if (ME && MD) {
  1617. if (ME->isArrow()) {
  1618. if (MD->isConst()) {
  1619. checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
  1620. } else { // FIXME -- should be AK_Written
  1621. checkPtAccess(CE->getImplicitObjectArgument(), AK_Read);
  1622. }
  1623. } else {
  1624. if (MD->isConst())
  1625. checkAccess(CE->getImplicitObjectArgument(), AK_Read);
  1626. else // FIXME -- should be AK_Written
  1627. checkAccess(CE->getImplicitObjectArgument(), AK_Read);
  1628. }
  1629. }
  1630. } else if (CXXOperatorCallExpr *OE = dyn_cast<CXXOperatorCallExpr>(Exp)) {
  1631. OperatorFun = true;
  1632. auto OEop = OE->getOperator();
  1633. switch (OEop) {
  1634. case OO_Equal: {
  1635. ExamineArgs = false;
  1636. const Expr *Target = OE->getArg(0);
  1637. const Expr *Source = OE->getArg(1);
  1638. checkAccess(Target, AK_Written);
  1639. checkAccess(Source, AK_Read);
  1640. break;
  1641. }
  1642. case OO_Star:
  1643. case OO_Arrow:
  1644. case OO_Subscript: {
  1645. const Expr *Obj = OE->getArg(0);
  1646. checkAccess(Obj, AK_Read);
  1647. if (!(OEop == OO_Star && OE->getNumArgs() > 1)) {
  1648. // Grrr. operator* can be multiplication...
  1649. checkPtAccess(Obj, AK_Read);
  1650. }
  1651. break;
  1652. }
  1653. default: {
  1654. // TODO: get rid of this, and rely on pass-by-ref instead.
  1655. const Expr *Obj = OE->getArg(0);
  1656. checkAccess(Obj, AK_Read);
  1657. break;
  1658. }
  1659. }
  1660. }
  1661. if (ExamineArgs) {
  1662. if (FunctionDecl *FD = Exp->getDirectCallee()) {
  1663. // NO_THREAD_SAFETY_ANALYSIS does double duty here. Normally it
  1664. // only turns off checking within the body of a function, but we also
  1665. // use it to turn off checking in arguments to the function. This
  1666. // could result in some false negatives, but the alternative is to
  1667. // create yet another attribute.
  1668. //
  1669. if (!FD->hasAttr<NoThreadSafetyAnalysisAttr>()) {
  1670. unsigned Fn = FD->getNumParams();
  1671. unsigned Cn = Exp->getNumArgs();
  1672. unsigned Skip = 0;
  1673. unsigned i = 0;
  1674. if (OperatorFun) {
  1675. if (isa<CXXMethodDecl>(FD)) {
  1676. // First arg in operator call is implicit self argument,
  1677. // and doesn't appear in the FunctionDecl.
  1678. Skip = 1;
  1679. Cn--;
  1680. } else {
  1681. // Ignore the first argument of operators; it's been checked above.
  1682. i = 1;
  1683. }
  1684. }
  1685. // Ignore default arguments
  1686. unsigned n = (Fn < Cn) ? Fn : Cn;
  1687. for (; i < n; ++i) {
  1688. ParmVarDecl* Pvd = FD->getParamDecl(i);
  1689. Expr* Arg = Exp->getArg(i+Skip);
  1690. QualType Qt = Pvd->getType();
  1691. if (Qt->isReferenceType())
  1692. checkAccess(Arg, AK_Read, POK_PassByRef);
  1693. }
  1694. }
  1695. }
  1696. }
  1697. NamedDecl *D = dyn_cast_or_null<NamedDecl>(Exp->getCalleeDecl());
  1698. if(!D || !D->hasAttrs())
  1699. return;
  1700. handleCall(Exp, D);
  1701. }
  1702. void BuildLockset::VisitCXXConstructExpr(CXXConstructExpr *Exp) {
  1703. const CXXConstructorDecl *D = Exp->getConstructor();
  1704. if (D && D->isCopyConstructor()) {
  1705. const Expr* Source = Exp->getArg(0);
  1706. checkAccess(Source, AK_Read);
  1707. }
  1708. // FIXME -- only handles constructors in DeclStmt below.
  1709. }
  1710. void BuildLockset::VisitDeclStmt(DeclStmt *S) {
  1711. // adjust the context
  1712. LVarCtx = Analyzer->LocalVarMap.getNextContext(CtxIndex, S, LVarCtx);
  1713. for (auto *D : S->getDeclGroup()) {
  1714. if (VarDecl *VD = dyn_cast_or_null<VarDecl>(D)) {
  1715. Expr *E = VD->getInit();
  1716. // handle constructors that involve temporaries
  1717. if (ExprWithCleanups *EWC = dyn_cast_or_null<ExprWithCleanups>(E))
  1718. E = EWC->getSubExpr();
  1719. if (CXXConstructExpr *CE = dyn_cast_or_null<CXXConstructExpr>(E)) {
  1720. NamedDecl *CtorD = dyn_cast_or_null<NamedDecl>(CE->getConstructor());
  1721. if (!CtorD || !CtorD->hasAttrs())
  1722. return;
  1723. handleCall(CE, CtorD, VD);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. /// \brief Compute the intersection of two locksets and issue warnings for any
  1729. /// locks in the symmetric difference.
  1730. ///
  1731. /// This function is used at a merge point in the CFG when comparing the lockset
  1732. /// of each branch being merged. For example, given the following sequence:
  1733. /// A; if () then B; else C; D; we need to check that the lockset after B and C
  1734. /// are the same. In the event of a difference, we use the intersection of these
  1735. /// two locksets at the start of D.
  1736. ///
  1737. /// \param FSet1 The first lockset.
  1738. /// \param FSet2 The second lockset.
  1739. /// \param JoinLoc The location of the join point for error reporting
  1740. /// \param LEK1 The error message to report if a mutex is missing from LSet1
  1741. /// \param LEK2 The error message to report if a mutex is missing from Lset2
  1742. void ThreadSafetyAnalyzer::intersectAndWarn(FactSet &FSet1,
  1743. const FactSet &FSet2,
  1744. SourceLocation JoinLoc,
  1745. LockErrorKind LEK1,
  1746. LockErrorKind LEK2,
  1747. bool Modify) {
  1748. FactSet FSet1Orig = FSet1;
  1749. // Find locks in FSet2 that conflict or are not in FSet1, and warn.
  1750. for (const auto &Fact : FSet2) {
  1751. const FactEntry *LDat1 = nullptr;
  1752. const FactEntry *LDat2 = &FactMan[Fact];
  1753. FactSet::iterator Iter1 = FSet1.findLockIter(FactMan, *LDat2);
  1754. if (Iter1 != FSet1.end()) LDat1 = &FactMan[*Iter1];
  1755. if (LDat1) {
  1756. if (LDat1->kind() != LDat2->kind()) {
  1757. Handler.handleExclusiveAndShared("mutex", LDat2->toString(),
  1758. LDat2->loc(), LDat1->loc());
  1759. if (Modify && LDat1->kind() != LK_Exclusive) {
  1760. // Take the exclusive lock, which is the one in FSet2.
  1761. *Iter1 = Fact;
  1762. }
  1763. }
  1764. else if (Modify && LDat1->asserted() && !LDat2->asserted()) {
  1765. // The non-asserted lock in FSet2 is the one we want to track.
  1766. *Iter1 = Fact;
  1767. }
  1768. } else {
  1769. LDat2->handleRemovalFromIntersection(FSet2, FactMan, JoinLoc, LEK1,
  1770. Handler);
  1771. }
  1772. }
  1773. // Find locks in FSet1 that are not in FSet2, and remove them.
  1774. for (const auto &Fact : FSet1Orig) {
  1775. const FactEntry *LDat1 = &FactMan[Fact];
  1776. const FactEntry *LDat2 = FSet2.findLock(FactMan, *LDat1);
  1777. if (!LDat2) {
  1778. LDat1->handleRemovalFromIntersection(FSet1Orig, FactMan, JoinLoc, LEK2,
  1779. Handler);
  1780. if (Modify)
  1781. FSet1.removeLock(FactMan, *LDat1);
  1782. }
  1783. }
  1784. }
  1785. // Return true if block B never continues to its successors.
  1786. static bool neverReturns(const CFGBlock *B) {
  1787. if (B->hasNoReturnElement())
  1788. return true;
  1789. if (B->empty())
  1790. return false;
  1791. CFGElement Last = B->back();
  1792. if (Optional<CFGStmt> S = Last.getAs<CFGStmt>()) {
  1793. if (isa<CXXThrowExpr>(S->getStmt()))
  1794. return true;
  1795. }
  1796. return false;
  1797. }
  1798. /// \brief Check a function's CFG for thread-safety violations.
  1799. ///
  1800. /// We traverse the blocks in the CFG, compute the set of mutexes that are held
  1801. /// at the end of each block, and issue warnings for thread safety violations.
  1802. /// Each block in the CFG is traversed exactly once.
  1803. void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
  1804. // TODO: this whole function needs be rewritten as a visitor for CFGWalker.
  1805. // For now, we just use the walker to set things up.
  1806. threadSafety::CFGWalker walker;
  1807. if (!walker.init(AC))
  1808. return;
  1809. // AC.dumpCFG(true);
  1810. // threadSafety::printSCFG(walker);
  1811. CFG *CFGraph = walker.getGraph();
  1812. const NamedDecl *D = walker.getDecl();
  1813. const FunctionDecl *CurrentFunction = dyn_cast<FunctionDecl>(D);
  1814. CurrentMethod = dyn_cast<CXXMethodDecl>(D);
  1815. if (D->hasAttr<NoThreadSafetyAnalysisAttr>())
  1816. return;
  1817. // FIXME: Do something a bit more intelligent inside constructor and
  1818. // destructor code. Constructors and destructors must assume unique access
  1819. // to 'this', so checks on member variable access is disabled, but we should
  1820. // still enable checks on other objects.
  1821. if (isa<CXXConstructorDecl>(D))
  1822. return; // Don't check inside constructors.
  1823. if (isa<CXXDestructorDecl>(D))
  1824. return; // Don't check inside destructors.
  1825. Handler.enterFunction(CurrentFunction);
  1826. BlockInfo.resize(CFGraph->getNumBlockIDs(),
  1827. CFGBlockInfo::getEmptyBlockInfo(LocalVarMap));
  1828. // We need to explore the CFG via a "topological" ordering.
  1829. // That way, we will be guaranteed to have information about required
  1830. // predecessor locksets when exploring a new block.
  1831. const PostOrderCFGView *SortedGraph = walker.getSortedGraph();
  1832. PostOrderCFGView::CFGBlockSet VisitedBlocks(CFGraph);
  1833. // Mark entry block as reachable
  1834. BlockInfo[CFGraph->getEntry().getBlockID()].Reachable = true;
  1835. // Compute SSA names for local variables
  1836. LocalVarMap.traverseCFG(CFGraph, SortedGraph, BlockInfo);
  1837. // Fill in source locations for all CFGBlocks.
  1838. findBlockLocations(CFGraph, SortedGraph, BlockInfo);
  1839. CapExprSet ExclusiveLocksAcquired;
  1840. CapExprSet SharedLocksAcquired;
  1841. CapExprSet LocksReleased;
  1842. // Add locks from exclusive_locks_required and shared_locks_required
  1843. // to initial lockset. Also turn off checking for lock and unlock functions.
  1844. // FIXME: is there a more intelligent way to check lock/unlock functions?
  1845. if (!SortedGraph->empty() && D->hasAttrs()) {
  1846. const CFGBlock *FirstBlock = *SortedGraph->begin();
  1847. FactSet &InitialLockset = BlockInfo[FirstBlock->getBlockID()].EntrySet;
  1848. CapExprSet ExclusiveLocksToAdd;
  1849. CapExprSet SharedLocksToAdd;
  1850. StringRef CapDiagKind = "mutex";
  1851. SourceLocation Loc = D->getLocation();
  1852. for (const auto *Attr : D->attrs()) {
  1853. Loc = Attr->getLocation();
  1854. if (const auto *A = dyn_cast<RequiresCapabilityAttr>(Attr)) {
  1855. getMutexIDs(A->isShared() ? SharedLocksToAdd : ExclusiveLocksToAdd, A,
  1856. nullptr, D);
  1857. CapDiagKind = ClassifyDiagnostic(A);
  1858. } else if (const auto *A = dyn_cast<ReleaseCapabilityAttr>(Attr)) {
  1859. // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
  1860. // We must ignore such methods.
  1861. if (A->args_size() == 0)
  1862. return;
  1863. // FIXME -- deal with exclusive vs. shared unlock functions?
  1864. getMutexIDs(ExclusiveLocksToAdd, A, nullptr, D);
  1865. getMutexIDs(LocksReleased, A, nullptr, D);
  1866. CapDiagKind = ClassifyDiagnostic(A);
  1867. } else if (const auto *A = dyn_cast<AcquireCapabilityAttr>(Attr)) {
  1868. if (A->args_size() == 0)
  1869. return;
  1870. getMutexIDs(A->isShared() ? SharedLocksAcquired
  1871. : ExclusiveLocksAcquired,
  1872. A, nullptr, D);
  1873. CapDiagKind = ClassifyDiagnostic(A);
  1874. } else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
  1875. // Don't try to check trylock functions for now
  1876. return;
  1877. } else if (isa<SharedTrylockFunctionAttr>(Attr)) {
  1878. // Don't try to check trylock functions for now
  1879. return;
  1880. }
  1881. }
  1882. // FIXME -- Loc can be wrong here.
  1883. for (const auto &Mu : ExclusiveLocksToAdd) {
  1884. auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Exclusive, Loc);
  1885. Entry->setDeclared(true);
  1886. addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
  1887. }
  1888. for (const auto &Mu : SharedLocksToAdd) {
  1889. auto Entry = llvm::make_unique<LockableFactEntry>(Mu, LK_Shared, Loc);
  1890. Entry->setDeclared(true);
  1891. addLock(InitialLockset, std::move(Entry), CapDiagKind, true);
  1892. }
  1893. }
  1894. for (const auto *CurrBlock : *SortedGraph) {
  1895. int CurrBlockID = CurrBlock->getBlockID();
  1896. CFGBlockInfo *CurrBlockInfo = &BlockInfo[CurrBlockID];
  1897. // Use the default initial lockset in case there are no predecessors.
  1898. VisitedBlocks.insert(CurrBlock);
  1899. // Iterate through the predecessor blocks and warn if the lockset for all
  1900. // predecessors is not the same. We take the entry lockset of the current
  1901. // block to be the intersection of all previous locksets.
  1902. // FIXME: By keeping the intersection, we may output more errors in future
  1903. // for a lock which is not in the intersection, but was in the union. We
  1904. // may want to also keep the union in future. As an example, let's say
  1905. // the intersection contains Mutex L, and the union contains L and M.
  1906. // Later we unlock M. At this point, we would output an error because we
  1907. // never locked M; although the real error is probably that we forgot to
  1908. // lock M on all code paths. Conversely, let's say that later we lock M.
  1909. // In this case, we should compare against the intersection instead of the
  1910. // union because the real error is probably that we forgot to unlock M on
  1911. // all code paths.
  1912. bool LocksetInitialized = false;
  1913. SmallVector<CFGBlock *, 8> SpecialBlocks;
  1914. for (CFGBlock::const_pred_iterator PI = CurrBlock->pred_begin(),
  1915. PE = CurrBlock->pred_end(); PI != PE; ++PI) {
  1916. // if *PI -> CurrBlock is a back edge
  1917. if (*PI == nullptr || !VisitedBlocks.alreadySet(*PI))
  1918. continue;
  1919. int PrevBlockID = (*PI)->getBlockID();
  1920. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  1921. // Ignore edges from blocks that can't return.
  1922. if (neverReturns(*PI) || !PrevBlockInfo->Reachable)
  1923. continue;
  1924. // Okay, we can reach this block from the entry.
  1925. CurrBlockInfo->Reachable = true;
  1926. // If the previous block ended in a 'continue' or 'break' statement, then
  1927. // a difference in locksets is probably due to a bug in that block, rather
  1928. // than in some other predecessor. In that case, keep the other
  1929. // predecessor's lockset.
  1930. if (const Stmt *Terminator = (*PI)->getTerminator()) {
  1931. if (isa<ContinueStmt>(Terminator) || isa<BreakStmt>(Terminator)) {
  1932. SpecialBlocks.push_back(*PI);
  1933. continue;
  1934. }
  1935. }
  1936. FactSet PrevLockset;
  1937. getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet, *PI, CurrBlock);
  1938. if (!LocksetInitialized) {
  1939. CurrBlockInfo->EntrySet = PrevLockset;
  1940. LocksetInitialized = true;
  1941. } else {
  1942. intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
  1943. CurrBlockInfo->EntryLoc,
  1944. LEK_LockedSomePredecessors);
  1945. }
  1946. }
  1947. // Skip rest of block if it's not reachable.
  1948. if (!CurrBlockInfo->Reachable)
  1949. continue;
  1950. // Process continue and break blocks. Assume that the lockset for the
  1951. // resulting block is unaffected by any discrepancies in them.
  1952. for (const auto *PrevBlock : SpecialBlocks) {
  1953. int PrevBlockID = PrevBlock->getBlockID();
  1954. CFGBlockInfo *PrevBlockInfo = &BlockInfo[PrevBlockID];
  1955. if (!LocksetInitialized) {
  1956. CurrBlockInfo->EntrySet = PrevBlockInfo->ExitSet;
  1957. LocksetInitialized = true;
  1958. } else {
  1959. // Determine whether this edge is a loop terminator for diagnostic
  1960. // purposes. FIXME: A 'break' statement might be a loop terminator, but
  1961. // it might also be part of a switch. Also, a subsequent destructor
  1962. // might add to the lockset, in which case the real issue might be a
  1963. // double lock on the other path.
  1964. const Stmt *Terminator = PrevBlock->getTerminator();
  1965. bool IsLoop = Terminator && isa<ContinueStmt>(Terminator);
  1966. FactSet PrevLockset;
  1967. getEdgeLockset(PrevLockset, PrevBlockInfo->ExitSet,
  1968. PrevBlock, CurrBlock);
  1969. // Do not update EntrySet.
  1970. intersectAndWarn(CurrBlockInfo->EntrySet, PrevLockset,
  1971. PrevBlockInfo->ExitLoc,
  1972. IsLoop ? LEK_LockedSomeLoopIterations
  1973. : LEK_LockedSomePredecessors,
  1974. false);
  1975. }
  1976. }
  1977. BuildLockset LocksetBuilder(this, *CurrBlockInfo);
  1978. // Visit all the statements in the basic block.
  1979. for (CFGBlock::const_iterator BI = CurrBlock->begin(),
  1980. BE = CurrBlock->end(); BI != BE; ++BI) {
  1981. switch (BI->getKind()) {
  1982. case CFGElement::Statement: {
  1983. CFGStmt CS = BI->castAs<CFGStmt>();
  1984. LocksetBuilder.Visit(const_cast<Stmt*>(CS.getStmt()));
  1985. break;
  1986. }
  1987. // Ignore BaseDtor, MemberDtor, and TemporaryDtor for now.
  1988. case CFGElement::AutomaticObjectDtor: {
  1989. CFGAutomaticObjDtor AD = BI->castAs<CFGAutomaticObjDtor>();
  1990. CXXDestructorDecl *DD = const_cast<CXXDestructorDecl *>(
  1991. AD.getDestructorDecl(AC.getASTContext()));
  1992. if (!DD->hasAttrs())
  1993. break;
  1994. // Create a dummy expression,
  1995. VarDecl *VD = const_cast<VarDecl*>(AD.getVarDecl());
  1996. DeclRefExpr DRE(VD, false, VD->getType().getNonReferenceType(),
  1997. VK_LValue, AD.getTriggerStmt()->getLocEnd());
  1998. LocksetBuilder.handleCall(&DRE, DD);
  1999. break;
  2000. }
  2001. default:
  2002. break;
  2003. }
  2004. }
  2005. CurrBlockInfo->ExitSet = LocksetBuilder.FSet;
  2006. // For every back edge from CurrBlock (the end of the loop) to another block
  2007. // (FirstLoopBlock) we need to check that the Lockset of Block is equal to
  2008. // the one held at the beginning of FirstLoopBlock. We can look up the
  2009. // Lockset held at the beginning of FirstLoopBlock in the EntryLockSets map.
  2010. for (CFGBlock::const_succ_iterator SI = CurrBlock->succ_begin(),
  2011. SE = CurrBlock->succ_end(); SI != SE; ++SI) {
  2012. // if CurrBlock -> *SI is *not* a back edge
  2013. if (*SI == nullptr || !VisitedBlocks.alreadySet(*SI))
  2014. continue;
  2015. CFGBlock *FirstLoopBlock = *SI;
  2016. CFGBlockInfo *PreLoop = &BlockInfo[FirstLoopBlock->getBlockID()];
  2017. CFGBlockInfo *LoopEnd = &BlockInfo[CurrBlockID];
  2018. intersectAndWarn(LoopEnd->ExitSet, PreLoop->EntrySet,
  2019. PreLoop->EntryLoc,
  2020. LEK_LockedSomeLoopIterations,
  2021. false);
  2022. }
  2023. }
  2024. CFGBlockInfo *Initial = &BlockInfo[CFGraph->getEntry().getBlockID()];
  2025. CFGBlockInfo *Final = &BlockInfo[CFGraph->getExit().getBlockID()];
  2026. // Skip the final check if the exit block is unreachable.
  2027. if (!Final->Reachable)
  2028. return;
  2029. // By default, we expect all locks held on entry to be held on exit.
  2030. FactSet ExpectedExitSet = Initial->EntrySet;
  2031. // Adjust the expected exit set by adding or removing locks, as declared
  2032. // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
  2033. // issue the appropriate warning.
  2034. // FIXME: the location here is not quite right.
  2035. for (const auto &Lock : ExclusiveLocksAcquired)
  2036. ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
  2037. Lock, LK_Exclusive, D->getLocation()));
  2038. for (const auto &Lock : SharedLocksAcquired)
  2039. ExpectedExitSet.addLock(FactMan, llvm::make_unique<LockableFactEntry>(
  2040. Lock, LK_Shared, D->getLocation()));
  2041. for (const auto &Lock : LocksReleased)
  2042. ExpectedExitSet.removeLock(FactMan, Lock);
  2043. // FIXME: Should we call this function for all blocks which exit the function?
  2044. intersectAndWarn(ExpectedExitSet, Final->ExitSet,
  2045. Final->ExitLoc,
  2046. LEK_LockedAtEndOfFunction,
  2047. LEK_NotLockedAtEndOfFunction,
  2048. false);
  2049. Handler.leaveFunction(CurrentFunction);
  2050. }
  2051. /// \brief Check a function's CFG for thread-safety violations.
  2052. ///
  2053. /// We traverse the blocks in the CFG, compute the set of mutexes that are held
  2054. /// at the end of each block, and issue warnings for thread safety violations.
  2055. /// Each block in the CFG is traversed exactly once.
  2056. void threadSafety::runThreadSafetyAnalysis(AnalysisDeclContext &AC,
  2057. ThreadSafetyHandler &Handler,
  2058. BeforeSet **BSet) {
  2059. if (!*BSet)
  2060. *BSet = new BeforeSet;
  2061. ThreadSafetyAnalyzer Analyzer(Handler, *BSet);
  2062. Analyzer.runAnalysis(AC);
  2063. }
  2064. void threadSafety::threadSafetyCleanup(BeforeSet *Cache) { delete Cache; }
  2065. /// \brief Helper function that returns a LockKind required for the given level
  2066. /// of access.
  2067. LockKind threadSafety::getLockKindFromAccessKind(AccessKind AK) {
  2068. switch (AK) {
  2069. case AK_Read :
  2070. return LK_Shared;
  2071. case AK_Written :
  2072. return LK_Exclusive;
  2073. }
  2074. llvm_unreachable("Unknown AccessKind");
  2075. }