ThreadSafetyCommon.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. //===- ThreadSafetyCommon.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. // Implementation of the interfaces declared in ThreadSafetyCommon.h
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Analysis/Analyses/ThreadSafetyCommon.h"
  13. #include "clang/AST/Attr.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclGroup.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/OperationKinds.h"
  21. #include "clang/AST/Stmt.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
  24. #include "clang/Analysis/CFG.h"
  25. #include "clang/Basic/LLVM.h"
  26. #include "clang/Basic/OperatorKinds.h"
  27. #include "clang/Basic/Specifiers.h"
  28. #include "llvm/ADT/StringExtras.h"
  29. #include "llvm/ADT/StringRef.h"
  30. #include "llvm/Support/Casting.h"
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <string>
  34. #include <utility>
  35. using namespace clang;
  36. using namespace threadSafety;
  37. // From ThreadSafetyUtil.h
  38. std::string threadSafety::getSourceLiteralString(const Expr *CE) {
  39. switch (CE->getStmtClass()) {
  40. case Stmt::IntegerLiteralClass:
  41. return toString(cast<IntegerLiteral>(CE)->getValue(), 10, true);
  42. case Stmt::StringLiteralClass: {
  43. std::string ret("\"");
  44. ret += cast<StringLiteral>(CE)->getString();
  45. ret += "\"";
  46. return ret;
  47. }
  48. case Stmt::CharacterLiteralClass:
  49. case Stmt::CXXNullPtrLiteralExprClass:
  50. case Stmt::GNUNullExprClass:
  51. case Stmt::CXXBoolLiteralExprClass:
  52. case Stmt::FloatingLiteralClass:
  53. case Stmt::ImaginaryLiteralClass:
  54. case Stmt::ObjCStringLiteralClass:
  55. default:
  56. return "#lit";
  57. }
  58. }
  59. // Return true if E is a variable that points to an incomplete Phi node.
  60. static bool isIncompletePhi(const til::SExpr *E) {
  61. if (const auto *Ph = dyn_cast<til::Phi>(E))
  62. return Ph->status() == til::Phi::PH_Incomplete;
  63. return false;
  64. }
  65. using CallingContext = SExprBuilder::CallingContext;
  66. til::SExpr *SExprBuilder::lookupStmt(const Stmt *S) {
  67. auto It = SMap.find(S);
  68. if (It != SMap.end())
  69. return It->second;
  70. return nullptr;
  71. }
  72. til::SCFG *SExprBuilder::buildCFG(CFGWalker &Walker) {
  73. Walker.walk(*this);
  74. return Scfg;
  75. }
  76. static bool isCalleeArrow(const Expr *E) {
  77. const auto *ME = dyn_cast<MemberExpr>(E->IgnoreParenCasts());
  78. return ME ? ME->isArrow() : false;
  79. }
  80. /// Translate a clang expression in an attribute to a til::SExpr.
  81. /// Constructs the context from D, DeclExp, and SelfDecl.
  82. ///
  83. /// \param AttrExp The expression to translate.
  84. /// \param D The declaration to which the attribute is attached.
  85. /// \param DeclExp An expression involving the Decl to which the attribute
  86. /// is attached. E.g. the call to a function.
  87. CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
  88. const NamedDecl *D,
  89. const Expr *DeclExp,
  90. VarDecl *SelfDecl) {
  91. // If we are processing a raw attribute expression, with no substitutions.
  92. if (!DeclExp)
  93. return translateAttrExpr(AttrExp, nullptr);
  94. CallingContext Ctx(nullptr, D);
  95. // Examine DeclExp to find SelfArg and FunArgs, which are used to substitute
  96. // for formal parameters when we call buildMutexID later.
  97. if (const auto *ME = dyn_cast<MemberExpr>(DeclExp)) {
  98. Ctx.SelfArg = ME->getBase();
  99. Ctx.SelfArrow = ME->isArrow();
  100. } else if (const auto *CE = dyn_cast<CXXMemberCallExpr>(DeclExp)) {
  101. Ctx.SelfArg = CE->getImplicitObjectArgument();
  102. Ctx.SelfArrow = isCalleeArrow(CE->getCallee());
  103. Ctx.NumArgs = CE->getNumArgs();
  104. Ctx.FunArgs = CE->getArgs();
  105. } else if (const auto *CE = dyn_cast<CallExpr>(DeclExp)) {
  106. Ctx.NumArgs = CE->getNumArgs();
  107. Ctx.FunArgs = CE->getArgs();
  108. } else if (const auto *CE = dyn_cast<CXXConstructExpr>(DeclExp)) {
  109. Ctx.SelfArg = nullptr; // Will be set below
  110. Ctx.NumArgs = CE->getNumArgs();
  111. Ctx.FunArgs = CE->getArgs();
  112. } else if (D && isa<CXXDestructorDecl>(D)) {
  113. // There's no such thing as a "destructor call" in the AST.
  114. Ctx.SelfArg = DeclExp;
  115. }
  116. // Hack to handle constructors, where self cannot be recovered from
  117. // the expression.
  118. if (SelfDecl && !Ctx.SelfArg) {
  119. DeclRefExpr SelfDRE(SelfDecl->getASTContext(), SelfDecl, false,
  120. SelfDecl->getType(), VK_LValue,
  121. SelfDecl->getLocation());
  122. Ctx.SelfArg = &SelfDRE;
  123. // If the attribute has no arguments, then assume the argument is "this".
  124. if (!AttrExp)
  125. return translateAttrExpr(Ctx.SelfArg, nullptr);
  126. else // For most attributes.
  127. return translateAttrExpr(AttrExp, &Ctx);
  128. }
  129. // If the attribute has no arguments, then assume the argument is "this".
  130. if (!AttrExp)
  131. return translateAttrExpr(Ctx.SelfArg, nullptr);
  132. else // For most attributes.
  133. return translateAttrExpr(AttrExp, &Ctx);
  134. }
  135. /// Translate a clang expression in an attribute to a til::SExpr.
  136. // This assumes a CallingContext has already been created.
  137. CapabilityExpr SExprBuilder::translateAttrExpr(const Expr *AttrExp,
  138. CallingContext *Ctx) {
  139. if (!AttrExp)
  140. return CapabilityExpr(nullptr, false);
  141. if (const auto* SLit = dyn_cast<StringLiteral>(AttrExp)) {
  142. if (SLit->getString() == StringRef("*"))
  143. // The "*" expr is a universal lock, which essentially turns off
  144. // checks until it is removed from the lockset.
  145. return CapabilityExpr(new (Arena) til::Wildcard(), false);
  146. else
  147. // Ignore other string literals for now.
  148. return CapabilityExpr(nullptr, false);
  149. }
  150. bool Neg = false;
  151. if (const auto *OE = dyn_cast<CXXOperatorCallExpr>(AttrExp)) {
  152. if (OE->getOperator() == OO_Exclaim) {
  153. Neg = true;
  154. AttrExp = OE->getArg(0);
  155. }
  156. }
  157. else if (const auto *UO = dyn_cast<UnaryOperator>(AttrExp)) {
  158. if (UO->getOpcode() == UO_LNot) {
  159. Neg = true;
  160. AttrExp = UO->getSubExpr();
  161. }
  162. }
  163. til::SExpr *E = translate(AttrExp, Ctx);
  164. // Trap mutex expressions like nullptr, or 0.
  165. // Any literal value is nonsense.
  166. if (!E || isa<til::Literal>(E))
  167. return CapabilityExpr(nullptr, false);
  168. // Hack to deal with smart pointers -- strip off top-level pointer casts.
  169. if (const auto *CE = dyn_cast<til::Cast>(E)) {
  170. if (CE->castOpcode() == til::CAST_objToPtr)
  171. return CapabilityExpr(CE->expr(), Neg);
  172. }
  173. return CapabilityExpr(E, Neg);
  174. }
  175. // Translate a clang statement or expression to a TIL expression.
  176. // Also performs substitution of variables; Ctx provides the context.
  177. // Dispatches on the type of S.
  178. til::SExpr *SExprBuilder::translate(const Stmt *S, CallingContext *Ctx) {
  179. if (!S)
  180. return nullptr;
  181. // Check if S has already been translated and cached.
  182. // This handles the lookup of SSA names for DeclRefExprs here.
  183. if (til::SExpr *E = lookupStmt(S))
  184. return E;
  185. switch (S->getStmtClass()) {
  186. case Stmt::DeclRefExprClass:
  187. return translateDeclRefExpr(cast<DeclRefExpr>(S), Ctx);
  188. case Stmt::CXXThisExprClass:
  189. return translateCXXThisExpr(cast<CXXThisExpr>(S), Ctx);
  190. case Stmt::MemberExprClass:
  191. return translateMemberExpr(cast<MemberExpr>(S), Ctx);
  192. case Stmt::ObjCIvarRefExprClass:
  193. return translateObjCIVarRefExpr(cast<ObjCIvarRefExpr>(S), Ctx);
  194. case Stmt::CallExprClass:
  195. return translateCallExpr(cast<CallExpr>(S), Ctx);
  196. case Stmt::CXXMemberCallExprClass:
  197. return translateCXXMemberCallExpr(cast<CXXMemberCallExpr>(S), Ctx);
  198. case Stmt::CXXOperatorCallExprClass:
  199. return translateCXXOperatorCallExpr(cast<CXXOperatorCallExpr>(S), Ctx);
  200. case Stmt::UnaryOperatorClass:
  201. return translateUnaryOperator(cast<UnaryOperator>(S), Ctx);
  202. case Stmt::BinaryOperatorClass:
  203. case Stmt::CompoundAssignOperatorClass:
  204. return translateBinaryOperator(cast<BinaryOperator>(S), Ctx);
  205. case Stmt::ArraySubscriptExprClass:
  206. return translateArraySubscriptExpr(cast<ArraySubscriptExpr>(S), Ctx);
  207. case Stmt::ConditionalOperatorClass:
  208. return translateAbstractConditionalOperator(
  209. cast<ConditionalOperator>(S), Ctx);
  210. case Stmt::BinaryConditionalOperatorClass:
  211. return translateAbstractConditionalOperator(
  212. cast<BinaryConditionalOperator>(S), Ctx);
  213. // We treat these as no-ops
  214. case Stmt::ConstantExprClass:
  215. return translate(cast<ConstantExpr>(S)->getSubExpr(), Ctx);
  216. case Stmt::ParenExprClass:
  217. return translate(cast<ParenExpr>(S)->getSubExpr(), Ctx);
  218. case Stmt::ExprWithCleanupsClass:
  219. return translate(cast<ExprWithCleanups>(S)->getSubExpr(), Ctx);
  220. case Stmt::CXXBindTemporaryExprClass:
  221. return translate(cast<CXXBindTemporaryExpr>(S)->getSubExpr(), Ctx);
  222. case Stmt::MaterializeTemporaryExprClass:
  223. return translate(cast<MaterializeTemporaryExpr>(S)->getSubExpr(), Ctx);
  224. // Collect all literals
  225. case Stmt::CharacterLiteralClass:
  226. case Stmt::CXXNullPtrLiteralExprClass:
  227. case Stmt::GNUNullExprClass:
  228. case Stmt::CXXBoolLiteralExprClass:
  229. case Stmt::FloatingLiteralClass:
  230. case Stmt::ImaginaryLiteralClass:
  231. case Stmt::IntegerLiteralClass:
  232. case Stmt::StringLiteralClass:
  233. case Stmt::ObjCStringLiteralClass:
  234. return new (Arena) til::Literal(cast<Expr>(S));
  235. case Stmt::DeclStmtClass:
  236. return translateDeclStmt(cast<DeclStmt>(S), Ctx);
  237. default:
  238. break;
  239. }
  240. if (const auto *CE = dyn_cast<CastExpr>(S))
  241. return translateCastExpr(CE, Ctx);
  242. return new (Arena) til::Undefined(S);
  243. }
  244. til::SExpr *SExprBuilder::translateDeclRefExpr(const DeclRefExpr *DRE,
  245. CallingContext *Ctx) {
  246. const auto *VD = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
  247. // Function parameters require substitution and/or renaming.
  248. if (const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
  249. unsigned I = PV->getFunctionScopeIndex();
  250. const DeclContext *D = PV->getDeclContext();
  251. if (Ctx && Ctx->FunArgs) {
  252. const Decl *Canonical = Ctx->AttrDecl->getCanonicalDecl();
  253. if (isa<FunctionDecl>(D)
  254. ? (cast<FunctionDecl>(D)->getCanonicalDecl() == Canonical)
  255. : (cast<ObjCMethodDecl>(D)->getCanonicalDecl() == Canonical)) {
  256. // Substitute call arguments for references to function parameters
  257. assert(I < Ctx->NumArgs);
  258. return translate(Ctx->FunArgs[I], Ctx->Prev);
  259. }
  260. }
  261. // Map the param back to the param of the original function declaration
  262. // for consistent comparisons.
  263. VD = isa<FunctionDecl>(D)
  264. ? cast<FunctionDecl>(D)->getCanonicalDecl()->getParamDecl(I)
  265. : cast<ObjCMethodDecl>(D)->getCanonicalDecl()->getParamDecl(I);
  266. }
  267. // For non-local variables, treat it as a reference to a named object.
  268. return new (Arena) til::LiteralPtr(VD);
  269. }
  270. til::SExpr *SExprBuilder::translateCXXThisExpr(const CXXThisExpr *TE,
  271. CallingContext *Ctx) {
  272. // Substitute for 'this'
  273. if (Ctx && Ctx->SelfArg)
  274. return translate(Ctx->SelfArg, Ctx->Prev);
  275. assert(SelfVar && "We have no variable for 'this'!");
  276. return SelfVar;
  277. }
  278. static const ValueDecl *getValueDeclFromSExpr(const til::SExpr *E) {
  279. if (const auto *V = dyn_cast<til::Variable>(E))
  280. return V->clangDecl();
  281. if (const auto *Ph = dyn_cast<til::Phi>(E))
  282. return Ph->clangDecl();
  283. if (const auto *P = dyn_cast<til::Project>(E))
  284. return P->clangDecl();
  285. if (const auto *L = dyn_cast<til::LiteralPtr>(E))
  286. return L->clangDecl();
  287. return nullptr;
  288. }
  289. static bool hasAnyPointerType(const til::SExpr *E) {
  290. auto *VD = getValueDeclFromSExpr(E);
  291. if (VD && VD->getType()->isAnyPointerType())
  292. return true;
  293. if (const auto *C = dyn_cast<til::Cast>(E))
  294. return C->castOpcode() == til::CAST_objToPtr;
  295. return false;
  296. }
  297. // Grab the very first declaration of virtual method D
  298. static const CXXMethodDecl *getFirstVirtualDecl(const CXXMethodDecl *D) {
  299. while (true) {
  300. D = D->getCanonicalDecl();
  301. auto OverriddenMethods = D->overridden_methods();
  302. if (OverriddenMethods.begin() == OverriddenMethods.end())
  303. return D; // Method does not override anything
  304. // FIXME: this does not work with multiple inheritance.
  305. D = *OverriddenMethods.begin();
  306. }
  307. return nullptr;
  308. }
  309. til::SExpr *SExprBuilder::translateMemberExpr(const MemberExpr *ME,
  310. CallingContext *Ctx) {
  311. til::SExpr *BE = translate(ME->getBase(), Ctx);
  312. til::SExpr *E = new (Arena) til::SApply(BE);
  313. const auto *D = cast<ValueDecl>(ME->getMemberDecl()->getCanonicalDecl());
  314. if (const auto *VD = dyn_cast<CXXMethodDecl>(D))
  315. D = getFirstVirtualDecl(VD);
  316. til::Project *P = new (Arena) til::Project(E, D);
  317. if (hasAnyPointerType(BE))
  318. P->setArrow(true);
  319. return P;
  320. }
  321. til::SExpr *SExprBuilder::translateObjCIVarRefExpr(const ObjCIvarRefExpr *IVRE,
  322. CallingContext *Ctx) {
  323. til::SExpr *BE = translate(IVRE->getBase(), Ctx);
  324. til::SExpr *E = new (Arena) til::SApply(BE);
  325. const auto *D = cast<ObjCIvarDecl>(IVRE->getDecl()->getCanonicalDecl());
  326. til::Project *P = new (Arena) til::Project(E, D);
  327. if (hasAnyPointerType(BE))
  328. P->setArrow(true);
  329. return P;
  330. }
  331. til::SExpr *SExprBuilder::translateCallExpr(const CallExpr *CE,
  332. CallingContext *Ctx,
  333. const Expr *SelfE) {
  334. if (CapabilityExprMode) {
  335. // Handle LOCK_RETURNED
  336. if (const FunctionDecl *FD = CE->getDirectCallee()) {
  337. FD = FD->getMostRecentDecl();
  338. if (LockReturnedAttr *At = FD->getAttr<LockReturnedAttr>()) {
  339. CallingContext LRCallCtx(Ctx);
  340. LRCallCtx.AttrDecl = CE->getDirectCallee();
  341. LRCallCtx.SelfArg = SelfE;
  342. LRCallCtx.NumArgs = CE->getNumArgs();
  343. LRCallCtx.FunArgs = CE->getArgs();
  344. return const_cast<til::SExpr *>(
  345. translateAttrExpr(At->getArg(), &LRCallCtx).sexpr());
  346. }
  347. }
  348. }
  349. til::SExpr *E = translate(CE->getCallee(), Ctx);
  350. for (const auto *Arg : CE->arguments()) {
  351. til::SExpr *A = translate(Arg, Ctx);
  352. E = new (Arena) til::Apply(E, A);
  353. }
  354. return new (Arena) til::Call(E, CE);
  355. }
  356. til::SExpr *SExprBuilder::translateCXXMemberCallExpr(
  357. const CXXMemberCallExpr *ME, CallingContext *Ctx) {
  358. if (CapabilityExprMode) {
  359. // Ignore calls to get() on smart pointers.
  360. if (ME->getMethodDecl()->getNameAsString() == "get" &&
  361. ME->getNumArgs() == 0) {
  362. auto *E = translate(ME->getImplicitObjectArgument(), Ctx);
  363. return new (Arena) til::Cast(til::CAST_objToPtr, E);
  364. // return E;
  365. }
  366. }
  367. return translateCallExpr(cast<CallExpr>(ME), Ctx,
  368. ME->getImplicitObjectArgument());
  369. }
  370. til::SExpr *SExprBuilder::translateCXXOperatorCallExpr(
  371. const CXXOperatorCallExpr *OCE, CallingContext *Ctx) {
  372. if (CapabilityExprMode) {
  373. // Ignore operator * and operator -> on smart pointers.
  374. OverloadedOperatorKind k = OCE->getOperator();
  375. if (k == OO_Star || k == OO_Arrow) {
  376. auto *E = translate(OCE->getArg(0), Ctx);
  377. return new (Arena) til::Cast(til::CAST_objToPtr, E);
  378. // return E;
  379. }
  380. }
  381. return translateCallExpr(cast<CallExpr>(OCE), Ctx);
  382. }
  383. til::SExpr *SExprBuilder::translateUnaryOperator(const UnaryOperator *UO,
  384. CallingContext *Ctx) {
  385. switch (UO->getOpcode()) {
  386. case UO_PostInc:
  387. case UO_PostDec:
  388. case UO_PreInc:
  389. case UO_PreDec:
  390. return new (Arena) til::Undefined(UO);
  391. case UO_AddrOf:
  392. if (CapabilityExprMode) {
  393. // interpret &Graph::mu_ as an existential.
  394. if (const auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr())) {
  395. if (DRE->getDecl()->isCXXInstanceMember()) {
  396. // This is a pointer-to-member expression, e.g. &MyClass::mu_.
  397. // We interpret this syntax specially, as a wildcard.
  398. auto *W = new (Arena) til::Wildcard();
  399. return new (Arena) til::Project(W, DRE->getDecl());
  400. }
  401. }
  402. }
  403. // otherwise, & is a no-op
  404. return translate(UO->getSubExpr(), Ctx);
  405. // We treat these as no-ops
  406. case UO_Deref:
  407. case UO_Plus:
  408. return translate(UO->getSubExpr(), Ctx);
  409. case UO_Minus:
  410. return new (Arena)
  411. til::UnaryOp(til::UOP_Minus, translate(UO->getSubExpr(), Ctx));
  412. case UO_Not:
  413. return new (Arena)
  414. til::UnaryOp(til::UOP_BitNot, translate(UO->getSubExpr(), Ctx));
  415. case UO_LNot:
  416. return new (Arena)
  417. til::UnaryOp(til::UOP_LogicNot, translate(UO->getSubExpr(), Ctx));
  418. // Currently unsupported
  419. case UO_Real:
  420. case UO_Imag:
  421. case UO_Extension:
  422. case UO_Coawait:
  423. return new (Arena) til::Undefined(UO);
  424. }
  425. return new (Arena) til::Undefined(UO);
  426. }
  427. til::SExpr *SExprBuilder::translateBinOp(til::TIL_BinaryOpcode Op,
  428. const BinaryOperator *BO,
  429. CallingContext *Ctx, bool Reverse) {
  430. til::SExpr *E0 = translate(BO->getLHS(), Ctx);
  431. til::SExpr *E1 = translate(BO->getRHS(), Ctx);
  432. if (Reverse)
  433. return new (Arena) til::BinaryOp(Op, E1, E0);
  434. else
  435. return new (Arena) til::BinaryOp(Op, E0, E1);
  436. }
  437. til::SExpr *SExprBuilder::translateBinAssign(til::TIL_BinaryOpcode Op,
  438. const BinaryOperator *BO,
  439. CallingContext *Ctx,
  440. bool Assign) {
  441. const Expr *LHS = BO->getLHS();
  442. const Expr *RHS = BO->getRHS();
  443. til::SExpr *E0 = translate(LHS, Ctx);
  444. til::SExpr *E1 = translate(RHS, Ctx);
  445. const ValueDecl *VD = nullptr;
  446. til::SExpr *CV = nullptr;
  447. if (const auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
  448. VD = DRE->getDecl();
  449. CV = lookupVarDecl(VD);
  450. }
  451. if (!Assign) {
  452. til::SExpr *Arg = CV ? CV : new (Arena) til::Load(E0);
  453. E1 = new (Arena) til::BinaryOp(Op, Arg, E1);
  454. E1 = addStatement(E1, nullptr, VD);
  455. }
  456. if (VD && CV)
  457. return updateVarDecl(VD, E1);
  458. return new (Arena) til::Store(E0, E1);
  459. }
  460. til::SExpr *SExprBuilder::translateBinaryOperator(const BinaryOperator *BO,
  461. CallingContext *Ctx) {
  462. switch (BO->getOpcode()) {
  463. case BO_PtrMemD:
  464. case BO_PtrMemI:
  465. return new (Arena) til::Undefined(BO);
  466. case BO_Mul: return translateBinOp(til::BOP_Mul, BO, Ctx);
  467. case BO_Div: return translateBinOp(til::BOP_Div, BO, Ctx);
  468. case BO_Rem: return translateBinOp(til::BOP_Rem, BO, Ctx);
  469. case BO_Add: return translateBinOp(til::BOP_Add, BO, Ctx);
  470. case BO_Sub: return translateBinOp(til::BOP_Sub, BO, Ctx);
  471. case BO_Shl: return translateBinOp(til::BOP_Shl, BO, Ctx);
  472. case BO_Shr: return translateBinOp(til::BOP_Shr, BO, Ctx);
  473. case BO_LT: return translateBinOp(til::BOP_Lt, BO, Ctx);
  474. case BO_GT: return translateBinOp(til::BOP_Lt, BO, Ctx, true);
  475. case BO_LE: return translateBinOp(til::BOP_Leq, BO, Ctx);
  476. case BO_GE: return translateBinOp(til::BOP_Leq, BO, Ctx, true);
  477. case BO_EQ: return translateBinOp(til::BOP_Eq, BO, Ctx);
  478. case BO_NE: return translateBinOp(til::BOP_Neq, BO, Ctx);
  479. case BO_Cmp: return translateBinOp(til::BOP_Cmp, BO, Ctx);
  480. case BO_And: return translateBinOp(til::BOP_BitAnd, BO, Ctx);
  481. case BO_Xor: return translateBinOp(til::BOP_BitXor, BO, Ctx);
  482. case BO_Or: return translateBinOp(til::BOP_BitOr, BO, Ctx);
  483. case BO_LAnd: return translateBinOp(til::BOP_LogicAnd, BO, Ctx);
  484. case BO_LOr: return translateBinOp(til::BOP_LogicOr, BO, Ctx);
  485. case BO_Assign: return translateBinAssign(til::BOP_Eq, BO, Ctx, true);
  486. case BO_MulAssign: return translateBinAssign(til::BOP_Mul, BO, Ctx);
  487. case BO_DivAssign: return translateBinAssign(til::BOP_Div, BO, Ctx);
  488. case BO_RemAssign: return translateBinAssign(til::BOP_Rem, BO, Ctx);
  489. case BO_AddAssign: return translateBinAssign(til::BOP_Add, BO, Ctx);
  490. case BO_SubAssign: return translateBinAssign(til::BOP_Sub, BO, Ctx);
  491. case BO_ShlAssign: return translateBinAssign(til::BOP_Shl, BO, Ctx);
  492. case BO_ShrAssign: return translateBinAssign(til::BOP_Shr, BO, Ctx);
  493. case BO_AndAssign: return translateBinAssign(til::BOP_BitAnd, BO, Ctx);
  494. case BO_XorAssign: return translateBinAssign(til::BOP_BitXor, BO, Ctx);
  495. case BO_OrAssign: return translateBinAssign(til::BOP_BitOr, BO, Ctx);
  496. case BO_Comma:
  497. // The clang CFG should have already processed both sides.
  498. return translate(BO->getRHS(), Ctx);
  499. }
  500. return new (Arena) til::Undefined(BO);
  501. }
  502. til::SExpr *SExprBuilder::translateCastExpr(const CastExpr *CE,
  503. CallingContext *Ctx) {
  504. CastKind K = CE->getCastKind();
  505. switch (K) {
  506. case CK_LValueToRValue: {
  507. if (const auto *DRE = dyn_cast<DeclRefExpr>(CE->getSubExpr())) {
  508. til::SExpr *E0 = lookupVarDecl(DRE->getDecl());
  509. if (E0)
  510. return E0;
  511. }
  512. til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
  513. return E0;
  514. // FIXME!! -- get Load working properly
  515. // return new (Arena) til::Load(E0);
  516. }
  517. case CK_NoOp:
  518. case CK_DerivedToBase:
  519. case CK_UncheckedDerivedToBase:
  520. case CK_ArrayToPointerDecay:
  521. case CK_FunctionToPointerDecay: {
  522. til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
  523. return E0;
  524. }
  525. default: {
  526. // FIXME: handle different kinds of casts.
  527. til::SExpr *E0 = translate(CE->getSubExpr(), Ctx);
  528. if (CapabilityExprMode)
  529. return E0;
  530. return new (Arena) til::Cast(til::CAST_none, E0);
  531. }
  532. }
  533. }
  534. til::SExpr *
  535. SExprBuilder::translateArraySubscriptExpr(const ArraySubscriptExpr *E,
  536. CallingContext *Ctx) {
  537. til::SExpr *E0 = translate(E->getBase(), Ctx);
  538. til::SExpr *E1 = translate(E->getIdx(), Ctx);
  539. return new (Arena) til::ArrayIndex(E0, E1);
  540. }
  541. til::SExpr *
  542. SExprBuilder::translateAbstractConditionalOperator(
  543. const AbstractConditionalOperator *CO, CallingContext *Ctx) {
  544. auto *C = translate(CO->getCond(), Ctx);
  545. auto *T = translate(CO->getTrueExpr(), Ctx);
  546. auto *E = translate(CO->getFalseExpr(), Ctx);
  547. return new (Arena) til::IfThenElse(C, T, E);
  548. }
  549. til::SExpr *
  550. SExprBuilder::translateDeclStmt(const DeclStmt *S, CallingContext *Ctx) {
  551. DeclGroupRef DGrp = S->getDeclGroup();
  552. for (auto I : DGrp) {
  553. if (auto *VD = dyn_cast_or_null<VarDecl>(I)) {
  554. Expr *E = VD->getInit();
  555. til::SExpr* SE = translate(E, Ctx);
  556. // Add local variables with trivial type to the variable map
  557. QualType T = VD->getType();
  558. if (T.isTrivialType(VD->getASTContext()))
  559. return addVarDecl(VD, SE);
  560. else {
  561. // TODO: add alloca
  562. }
  563. }
  564. }
  565. return nullptr;
  566. }
  567. // If (E) is non-trivial, then add it to the current basic block, and
  568. // update the statement map so that S refers to E. Returns a new variable
  569. // that refers to E.
  570. // If E is trivial returns E.
  571. til::SExpr *SExprBuilder::addStatement(til::SExpr* E, const Stmt *S,
  572. const ValueDecl *VD) {
  573. if (!E || !CurrentBB || E->block() || til::ThreadSafetyTIL::isTrivial(E))
  574. return E;
  575. if (VD)
  576. E = new (Arena) til::Variable(E, VD);
  577. CurrentInstructions.push_back(E);
  578. if (S)
  579. insertStmt(S, E);
  580. return E;
  581. }
  582. // Returns the current value of VD, if known, and nullptr otherwise.
  583. til::SExpr *SExprBuilder::lookupVarDecl(const ValueDecl *VD) {
  584. auto It = LVarIdxMap.find(VD);
  585. if (It != LVarIdxMap.end()) {
  586. assert(CurrentLVarMap[It->second].first == VD);
  587. return CurrentLVarMap[It->second].second;
  588. }
  589. return nullptr;
  590. }
  591. // if E is a til::Variable, update its clangDecl.
  592. static void maybeUpdateVD(til::SExpr *E, const ValueDecl *VD) {
  593. if (!E)
  594. return;
  595. if (auto *V = dyn_cast<til::Variable>(E)) {
  596. if (!V->clangDecl())
  597. V->setClangDecl(VD);
  598. }
  599. }
  600. // Adds a new variable declaration.
  601. til::SExpr *SExprBuilder::addVarDecl(const ValueDecl *VD, til::SExpr *E) {
  602. maybeUpdateVD(E, VD);
  603. LVarIdxMap.insert(std::make_pair(VD, CurrentLVarMap.size()));
  604. CurrentLVarMap.makeWritable();
  605. CurrentLVarMap.push_back(std::make_pair(VD, E));
  606. return E;
  607. }
  608. // Updates a current variable declaration. (E.g. by assignment)
  609. til::SExpr *SExprBuilder::updateVarDecl(const ValueDecl *VD, til::SExpr *E) {
  610. maybeUpdateVD(E, VD);
  611. auto It = LVarIdxMap.find(VD);
  612. if (It == LVarIdxMap.end()) {
  613. til::SExpr *Ptr = new (Arena) til::LiteralPtr(VD);
  614. til::SExpr *St = new (Arena) til::Store(Ptr, E);
  615. return St;
  616. }
  617. CurrentLVarMap.makeWritable();
  618. CurrentLVarMap.elem(It->second).second = E;
  619. return E;
  620. }
  621. // Make a Phi node in the current block for the i^th variable in CurrentVarMap.
  622. // If E != null, sets Phi[CurrentBlockInfo->ArgIndex] = E.
  623. // If E == null, this is a backedge and will be set later.
  624. void SExprBuilder::makePhiNodeVar(unsigned i, unsigned NPreds, til::SExpr *E) {
  625. unsigned ArgIndex = CurrentBlockInfo->ProcessedPredecessors;
  626. assert(ArgIndex > 0 && ArgIndex < NPreds);
  627. til::SExpr *CurrE = CurrentLVarMap[i].second;
  628. if (CurrE->block() == CurrentBB) {
  629. // We already have a Phi node in the current block,
  630. // so just add the new variable to the Phi node.
  631. auto *Ph = dyn_cast<til::Phi>(CurrE);
  632. assert(Ph && "Expecting Phi node.");
  633. if (E)
  634. Ph->values()[ArgIndex] = E;
  635. return;
  636. }
  637. // Make a new phi node: phi(..., E)
  638. // All phi args up to the current index are set to the current value.
  639. til::Phi *Ph = new (Arena) til::Phi(Arena, NPreds);
  640. Ph->values().setValues(NPreds, nullptr);
  641. for (unsigned PIdx = 0; PIdx < ArgIndex; ++PIdx)
  642. Ph->values()[PIdx] = CurrE;
  643. if (E)
  644. Ph->values()[ArgIndex] = E;
  645. Ph->setClangDecl(CurrentLVarMap[i].first);
  646. // If E is from a back-edge, or either E or CurrE are incomplete, then
  647. // mark this node as incomplete; we may need to remove it later.
  648. if (!E || isIncompletePhi(E) || isIncompletePhi(CurrE))
  649. Ph->setStatus(til::Phi::PH_Incomplete);
  650. // Add Phi node to current block, and update CurrentLVarMap[i]
  651. CurrentArguments.push_back(Ph);
  652. if (Ph->status() == til::Phi::PH_Incomplete)
  653. IncompleteArgs.push_back(Ph);
  654. CurrentLVarMap.makeWritable();
  655. CurrentLVarMap.elem(i).second = Ph;
  656. }
  657. // Merge values from Map into the current variable map.
  658. // This will construct Phi nodes in the current basic block as necessary.
  659. void SExprBuilder::mergeEntryMap(LVarDefinitionMap Map) {
  660. assert(CurrentBlockInfo && "Not processing a block!");
  661. if (!CurrentLVarMap.valid()) {
  662. // Steal Map, using copy-on-write.
  663. CurrentLVarMap = std::move(Map);
  664. return;
  665. }
  666. if (CurrentLVarMap.sameAs(Map))
  667. return; // Easy merge: maps from different predecessors are unchanged.
  668. unsigned NPreds = CurrentBB->numPredecessors();
  669. unsigned ESz = CurrentLVarMap.size();
  670. unsigned MSz = Map.size();
  671. unsigned Sz = std::min(ESz, MSz);
  672. for (unsigned i = 0; i < Sz; ++i) {
  673. if (CurrentLVarMap[i].first != Map[i].first) {
  674. // We've reached the end of variables in common.
  675. CurrentLVarMap.makeWritable();
  676. CurrentLVarMap.downsize(i);
  677. break;
  678. }
  679. if (CurrentLVarMap[i].second != Map[i].second)
  680. makePhiNodeVar(i, NPreds, Map[i].second);
  681. }
  682. if (ESz > MSz) {
  683. CurrentLVarMap.makeWritable();
  684. CurrentLVarMap.downsize(Map.size());
  685. }
  686. }
  687. // Merge a back edge into the current variable map.
  688. // This will create phi nodes for all variables in the variable map.
  689. void SExprBuilder::mergeEntryMapBackEdge() {
  690. // We don't have definitions for variables on the backedge, because we
  691. // haven't gotten that far in the CFG. Thus, when encountering a back edge,
  692. // we conservatively create Phi nodes for all variables. Unnecessary Phi
  693. // nodes will be marked as incomplete, and stripped out at the end.
  694. //
  695. // An Phi node is unnecessary if it only refers to itself and one other
  696. // variable, e.g. x = Phi(y, y, x) can be reduced to x = y.
  697. assert(CurrentBlockInfo && "Not processing a block!");
  698. if (CurrentBlockInfo->HasBackEdges)
  699. return;
  700. CurrentBlockInfo->HasBackEdges = true;
  701. CurrentLVarMap.makeWritable();
  702. unsigned Sz = CurrentLVarMap.size();
  703. unsigned NPreds = CurrentBB->numPredecessors();
  704. for (unsigned i = 0; i < Sz; ++i)
  705. makePhiNodeVar(i, NPreds, nullptr);
  706. }
  707. // Update the phi nodes that were initially created for a back edge
  708. // once the variable definitions have been computed.
  709. // I.e., merge the current variable map into the phi nodes for Blk.
  710. void SExprBuilder::mergePhiNodesBackEdge(const CFGBlock *Blk) {
  711. til::BasicBlock *BB = lookupBlock(Blk);
  712. unsigned ArgIndex = BBInfo[Blk->getBlockID()].ProcessedPredecessors;
  713. assert(ArgIndex > 0 && ArgIndex < BB->numPredecessors());
  714. for (til::SExpr *PE : BB->arguments()) {
  715. auto *Ph = dyn_cast_or_null<til::Phi>(PE);
  716. assert(Ph && "Expecting Phi Node.");
  717. assert(Ph->values()[ArgIndex] == nullptr && "Wrong index for back edge.");
  718. til::SExpr *E = lookupVarDecl(Ph->clangDecl());
  719. assert(E && "Couldn't find local variable for Phi node.");
  720. Ph->values()[ArgIndex] = E;
  721. }
  722. }
  723. void SExprBuilder::enterCFG(CFG *Cfg, const NamedDecl *D,
  724. const CFGBlock *First) {
  725. // Perform initial setup operations.
  726. unsigned NBlocks = Cfg->getNumBlockIDs();
  727. Scfg = new (Arena) til::SCFG(Arena, NBlocks);
  728. // allocate all basic blocks immediately, to handle forward references.
  729. BBInfo.resize(NBlocks);
  730. BlockMap.resize(NBlocks, nullptr);
  731. // create map from clang blockID to til::BasicBlocks
  732. for (auto *B : *Cfg) {
  733. auto *BB = new (Arena) til::BasicBlock(Arena);
  734. BB->reserveInstructions(B->size());
  735. BlockMap[B->getBlockID()] = BB;
  736. }
  737. CurrentBB = lookupBlock(&Cfg->getEntry());
  738. auto Parms = isa<ObjCMethodDecl>(D) ? cast<ObjCMethodDecl>(D)->parameters()
  739. : cast<FunctionDecl>(D)->parameters();
  740. for (auto *Pm : Parms) {
  741. QualType T = Pm->getType();
  742. if (!T.isTrivialType(Pm->getASTContext()))
  743. continue;
  744. // Add parameters to local variable map.
  745. // FIXME: right now we emulate params with loads; that should be fixed.
  746. til::SExpr *Lp = new (Arena) til::LiteralPtr(Pm);
  747. til::SExpr *Ld = new (Arena) til::Load(Lp);
  748. til::SExpr *V = addStatement(Ld, nullptr, Pm);
  749. addVarDecl(Pm, V);
  750. }
  751. }
  752. void SExprBuilder::enterCFGBlock(const CFGBlock *B) {
  753. // Initialize TIL basic block and add it to the CFG.
  754. CurrentBB = lookupBlock(B);
  755. CurrentBB->reservePredecessors(B->pred_size());
  756. Scfg->add(CurrentBB);
  757. CurrentBlockInfo = &BBInfo[B->getBlockID()];
  758. // CurrentLVarMap is moved to ExitMap on block exit.
  759. // FIXME: the entry block will hold function parameters.
  760. // assert(!CurrentLVarMap.valid() && "CurrentLVarMap already initialized.");
  761. }
  762. void SExprBuilder::handlePredecessor(const CFGBlock *Pred) {
  763. // Compute CurrentLVarMap on entry from ExitMaps of predecessors
  764. CurrentBB->addPredecessor(BlockMap[Pred->getBlockID()]);
  765. BlockInfo *PredInfo = &BBInfo[Pred->getBlockID()];
  766. assert(PredInfo->UnprocessedSuccessors > 0);
  767. if (--PredInfo->UnprocessedSuccessors == 0)
  768. mergeEntryMap(std::move(PredInfo->ExitMap));
  769. else
  770. mergeEntryMap(PredInfo->ExitMap.clone());
  771. ++CurrentBlockInfo->ProcessedPredecessors;
  772. }
  773. void SExprBuilder::handlePredecessorBackEdge(const CFGBlock *Pred) {
  774. mergeEntryMapBackEdge();
  775. }
  776. void SExprBuilder::enterCFGBlockBody(const CFGBlock *B) {
  777. // The merge*() methods have created arguments.
  778. // Push those arguments onto the basic block.
  779. CurrentBB->arguments().reserve(
  780. static_cast<unsigned>(CurrentArguments.size()), Arena);
  781. for (auto *A : CurrentArguments)
  782. CurrentBB->addArgument(A);
  783. }
  784. void SExprBuilder::handleStatement(const Stmt *S) {
  785. til::SExpr *E = translate(S, nullptr);
  786. addStatement(E, S);
  787. }
  788. void SExprBuilder::handleDestructorCall(const VarDecl *VD,
  789. const CXXDestructorDecl *DD) {
  790. til::SExpr *Sf = new (Arena) til::LiteralPtr(VD);
  791. til::SExpr *Dr = new (Arena) til::LiteralPtr(DD);
  792. til::SExpr *Ap = new (Arena) til::Apply(Dr, Sf);
  793. til::SExpr *E = new (Arena) til::Call(Ap);
  794. addStatement(E, nullptr);
  795. }
  796. void SExprBuilder::exitCFGBlockBody(const CFGBlock *B) {
  797. CurrentBB->instructions().reserve(
  798. static_cast<unsigned>(CurrentInstructions.size()), Arena);
  799. for (auto *V : CurrentInstructions)
  800. CurrentBB->addInstruction(V);
  801. // Create an appropriate terminator
  802. unsigned N = B->succ_size();
  803. auto It = B->succ_begin();
  804. if (N == 1) {
  805. til::BasicBlock *BB = *It ? lookupBlock(*It) : nullptr;
  806. // TODO: set index
  807. unsigned Idx = BB ? BB->findPredecessorIndex(CurrentBB) : 0;
  808. auto *Tm = new (Arena) til::Goto(BB, Idx);
  809. CurrentBB->setTerminator(Tm);
  810. }
  811. else if (N == 2) {
  812. til::SExpr *C = translate(B->getTerminatorCondition(true), nullptr);
  813. til::BasicBlock *BB1 = *It ? lookupBlock(*It) : nullptr;
  814. ++It;
  815. til::BasicBlock *BB2 = *It ? lookupBlock(*It) : nullptr;
  816. // FIXME: make sure these aren't critical edges.
  817. auto *Tm = new (Arena) til::Branch(C, BB1, BB2);
  818. CurrentBB->setTerminator(Tm);
  819. }
  820. }
  821. void SExprBuilder::handleSuccessor(const CFGBlock *Succ) {
  822. ++CurrentBlockInfo->UnprocessedSuccessors;
  823. }
  824. void SExprBuilder::handleSuccessorBackEdge(const CFGBlock *Succ) {
  825. mergePhiNodesBackEdge(Succ);
  826. ++BBInfo[Succ->getBlockID()].ProcessedPredecessors;
  827. }
  828. void SExprBuilder::exitCFGBlock(const CFGBlock *B) {
  829. CurrentArguments.clear();
  830. CurrentInstructions.clear();
  831. CurrentBlockInfo->ExitMap = std::move(CurrentLVarMap);
  832. CurrentBB = nullptr;
  833. CurrentBlockInfo = nullptr;
  834. }
  835. void SExprBuilder::exitCFG(const CFGBlock *Last) {
  836. for (auto *Ph : IncompleteArgs) {
  837. if (Ph->status() == til::Phi::PH_Incomplete)
  838. simplifyIncompleteArg(Ph);
  839. }
  840. CurrentArguments.clear();
  841. CurrentInstructions.clear();
  842. IncompleteArgs.clear();
  843. }
  844. /*
  845. namespace {
  846. class TILPrinter :
  847. public til::PrettyPrinter<TILPrinter, llvm::raw_ostream> {};
  848. } // namespace
  849. namespace clang {
  850. namespace threadSafety {
  851. void printSCFG(CFGWalker &Walker) {
  852. llvm::BumpPtrAllocator Bpa;
  853. til::MemRegionRef Arena(&Bpa);
  854. SExprBuilder SxBuilder(Arena);
  855. til::SCFG *Scfg = SxBuilder.buildCFG(Walker);
  856. TILPrinter::print(Scfg, llvm::errs());
  857. }
  858. } // namespace threadSafety
  859. } // namespace clang
  860. */