ThreadSafety.cpp 91 KB

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