AnalysisDeclContext.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. //===- AnalysisDeclContext.cpp - Analysis context for Path Sens analysis --===//
  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. // This file defines AnalysisDeclContext, a class that manages the analysis
  10. // context data for path sensitive analysis.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Analysis/AnalysisDeclContext.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Decl.h"
  16. #include "clang/AST/DeclBase.h"
  17. #include "clang/AST/DeclCXX.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DeclTemplate.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/LambdaCapture.h"
  22. #include "clang/AST/ParentMap.h"
  23. #include "clang/AST/PrettyPrinter.h"
  24. #include "clang/AST/Stmt.h"
  25. #include "clang/AST/StmtCXX.h"
  26. #include "clang/AST/StmtVisitor.h"
  27. #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
  28. #include "clang/Analysis/BodyFarm.h"
  29. #include "clang/Analysis/CFG.h"
  30. #include "clang/Analysis/CFGStmtMap.h"
  31. #include "clang/Analysis/Support/BumpVector.h"
  32. #include "clang/Basic/JsonSupport.h"
  33. #include "clang/Basic/LLVM.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "llvm/ADT/DenseMap.h"
  37. #include "llvm/ADT/FoldingSet.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/ADT/SmallPtrSet.h"
  40. #include "llvm/ADT/iterator_range.h"
  41. #include "llvm/Support/Allocator.h"
  42. #include "llvm/Support/Casting.h"
  43. #include "llvm/Support/Compiler.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/SaveAndRestore.h"
  46. #include "llvm/Support/raw_ostream.h"
  47. #include <cassert>
  48. #include <memory>
  49. using namespace clang;
  50. using ManagedAnalysisMap = llvm::DenseMap<const void *, ManagedAnalysis *>;
  51. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
  52. const Decl *d,
  53. const CFG::BuildOptions &buildOptions)
  54. : Manager(Mgr), D(d), cfgBuildOptions(buildOptions) {
  55. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  56. }
  57. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
  58. const Decl *d)
  59. : Manager(Mgr), D(d) {
  60. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  61. }
  62. AnalysisDeclContextManager::AnalysisDeclContextManager(
  63. ASTContext &ASTCtx, bool useUnoptimizedCFG, bool addImplicitDtors,
  64. bool addInitializers, bool addTemporaryDtors, bool addLifetime,
  65. bool addLoopExit, bool addScopes, bool synthesizeBodies,
  66. bool addStaticInitBranch, bool addCXXNewAllocator,
  67. bool addRichCXXConstructors, bool markElidedCXXConstructors,
  68. bool addVirtualBaseBranches, CodeInjector *injector)
  69. : Injector(injector), FunctionBodyFarm(ASTCtx, injector),
  70. SynthesizeBodies(synthesizeBodies) {
  71. cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
  72. cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
  73. cfgBuildOptions.AddInitializers = addInitializers;
  74. cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
  75. cfgBuildOptions.AddLifetime = addLifetime;
  76. cfgBuildOptions.AddLoopExit = addLoopExit;
  77. cfgBuildOptions.AddScopes = addScopes;
  78. cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
  79. cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
  80. cfgBuildOptions.AddRichCXXConstructors = addRichCXXConstructors;
  81. cfgBuildOptions.MarkElidedCXXConstructors = markElidedCXXConstructors;
  82. cfgBuildOptions.AddVirtualBaseBranches = addVirtualBaseBranches;
  83. }
  84. void AnalysisDeclContextManager::clear() { Contexts.clear(); }
  85. Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
  86. IsAutosynthesized = false;
  87. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  88. Stmt *Body = FD->getBody();
  89. if (auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body))
  90. Body = CoroBody->getBody();
  91. if (Manager && Manager->synthesizeBodies()) {
  92. Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(FD);
  93. if (SynthesizedBody) {
  94. Body = SynthesizedBody;
  95. IsAutosynthesized = true;
  96. }
  97. }
  98. return Body;
  99. }
  100. else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  101. Stmt *Body = MD->getBody();
  102. if (Manager && Manager->synthesizeBodies()) {
  103. Stmt *SynthesizedBody = Manager->getBodyFarm().getBody(MD);
  104. if (SynthesizedBody) {
  105. Body = SynthesizedBody;
  106. IsAutosynthesized = true;
  107. }
  108. }
  109. return Body;
  110. } else if (const auto *BD = dyn_cast<BlockDecl>(D))
  111. return BD->getBody();
  112. else if (const auto *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
  113. return FunTmpl->getTemplatedDecl()->getBody();
  114. llvm_unreachable("unknown code decl");
  115. }
  116. Stmt *AnalysisDeclContext::getBody() const {
  117. bool Tmp;
  118. return getBody(Tmp);
  119. }
  120. bool AnalysisDeclContext::isBodyAutosynthesized() const {
  121. bool Tmp;
  122. getBody(Tmp);
  123. return Tmp;
  124. }
  125. bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
  126. bool Tmp;
  127. Stmt *Body = getBody(Tmp);
  128. return Tmp && Body->getBeginLoc().isValid();
  129. }
  130. /// Returns true if \param VD is an Objective-C implicit 'self' parameter.
  131. static bool isSelfDecl(const VarDecl *VD) {
  132. return isa<ImplicitParamDecl>(VD) && VD->getName() == "self";
  133. }
  134. const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
  135. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  136. return MD->getSelfDecl();
  137. if (const auto *BD = dyn_cast<BlockDecl>(D)) {
  138. // See if 'self' was captured by the block.
  139. for (const auto &I : BD->captures()) {
  140. const VarDecl *VD = I.getVariable();
  141. if (isSelfDecl(VD))
  142. return dyn_cast<ImplicitParamDecl>(VD);
  143. }
  144. }
  145. auto *CXXMethod = dyn_cast<CXXMethodDecl>(D);
  146. if (!CXXMethod)
  147. return nullptr;
  148. const CXXRecordDecl *parent = CXXMethod->getParent();
  149. if (!parent->isLambda())
  150. return nullptr;
  151. for (const auto &LC : parent->captures()) {
  152. if (!LC.capturesVariable())
  153. continue;
  154. VarDecl *VD = LC.getCapturedVar();
  155. if (isSelfDecl(VD))
  156. return dyn_cast<ImplicitParamDecl>(VD);
  157. }
  158. return nullptr;
  159. }
  160. void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
  161. if (!forcedBlkExprs)
  162. forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
  163. // Default construct an entry for 'stmt'.
  164. if (const auto *e = dyn_cast<Expr>(stmt))
  165. stmt = e->IgnoreParens();
  166. (void) (*forcedBlkExprs)[stmt];
  167. }
  168. const CFGBlock *
  169. AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
  170. assert(forcedBlkExprs);
  171. if (const auto *e = dyn_cast<Expr>(stmt))
  172. stmt = e->IgnoreParens();
  173. CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
  174. forcedBlkExprs->find(stmt);
  175. assert(itr != forcedBlkExprs->end());
  176. return itr->second;
  177. }
  178. /// Add each synthetic statement in the CFG to the parent map, using the
  179. /// source statement's parent.
  180. static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
  181. if (!TheCFG)
  182. return;
  183. for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
  184. E = TheCFG->synthetic_stmt_end();
  185. I != E; ++I) {
  186. PM.setParent(I->first, PM.getParent(I->second));
  187. }
  188. }
  189. CFG *AnalysisDeclContext::getCFG() {
  190. if (!cfgBuildOptions.PruneTriviallyFalseEdges)
  191. return getUnoptimizedCFG();
  192. if (!builtCFG) {
  193. cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
  194. // Even when the cfg is not successfully built, we don't
  195. // want to try building it again.
  196. builtCFG = true;
  197. if (PM)
  198. addParentsForSyntheticStmts(cfg.get(), *PM);
  199. // The Observer should only observe one build of the CFG.
  200. getCFGBuildOptions().Observer = nullptr;
  201. }
  202. return cfg.get();
  203. }
  204. CFG *AnalysisDeclContext::getUnoptimizedCFG() {
  205. if (!builtCompleteCFG) {
  206. SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
  207. false);
  208. completeCFG =
  209. CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
  210. // Even when the cfg is not successfully built, we don't
  211. // want to try building it again.
  212. builtCompleteCFG = true;
  213. if (PM)
  214. addParentsForSyntheticStmts(completeCFG.get(), *PM);
  215. // The Observer should only observe one build of the CFG.
  216. getCFGBuildOptions().Observer = nullptr;
  217. }
  218. return completeCFG.get();
  219. }
  220. CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
  221. if (cfgStmtMap)
  222. return cfgStmtMap.get();
  223. if (CFG *c = getCFG()) {
  224. cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
  225. return cfgStmtMap.get();
  226. }
  227. return nullptr;
  228. }
  229. CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
  230. if (CFA)
  231. return CFA.get();
  232. if (CFG *c = getCFG()) {
  233. CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
  234. return CFA.get();
  235. }
  236. return nullptr;
  237. }
  238. void AnalysisDeclContext::dumpCFG(bool ShowColors) {
  239. getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
  240. }
  241. ParentMap &AnalysisDeclContext::getParentMap() {
  242. if (!PM) {
  243. PM.reset(new ParentMap(getBody()));
  244. if (const auto *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
  245. for (const auto *I : C->inits()) {
  246. PM->addStmt(I->getInit());
  247. }
  248. }
  249. if (builtCFG)
  250. addParentsForSyntheticStmts(getCFG(), *PM);
  251. if (builtCompleteCFG)
  252. addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
  253. }
  254. return *PM;
  255. }
  256. AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
  257. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  258. // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
  259. // that has the body.
  260. FD->hasBody(FD);
  261. D = FD;
  262. }
  263. std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
  264. if (!AC)
  265. AC = std::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions);
  266. return AC.get();
  267. }
  268. BodyFarm &AnalysisDeclContextManager::getBodyFarm() { return FunctionBodyFarm; }
  269. const StackFrameContext *
  270. AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
  271. const CFGBlock *Blk, unsigned BlockCount,
  272. unsigned Idx) {
  273. return getLocationContextManager().getStackFrame(this, Parent, S, Blk,
  274. BlockCount, Idx);
  275. }
  276. const BlockInvocationContext *
  277. AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
  278. const BlockDecl *BD,
  279. const void *ContextData) {
  280. return getLocationContextManager().getBlockInvocationContext(this, parent,
  281. BD, ContextData);
  282. }
  283. bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
  284. const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
  285. const auto *ND = dyn_cast<NamespaceDecl>(DC);
  286. if (!ND)
  287. return false;
  288. while (const DeclContext *Parent = ND->getParent()) {
  289. if (!isa<NamespaceDecl>(Parent))
  290. break;
  291. ND = cast<NamespaceDecl>(Parent);
  292. }
  293. return ND->isStdNamespace();
  294. }
  295. LocationContextManager &AnalysisDeclContext::getLocationContextManager() {
  296. assert(Manager &&
  297. "Cannot create LocationContexts without an AnalysisDeclContextManager!");
  298. return Manager->getLocationContextManager();
  299. }
  300. //===----------------------------------------------------------------------===//
  301. // FoldingSet profiling.
  302. //===----------------------------------------------------------------------===//
  303. void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
  304. ContextKind ck,
  305. AnalysisDeclContext *ctx,
  306. const LocationContext *parent,
  307. const void *data) {
  308. ID.AddInteger(ck);
  309. ID.AddPointer(ctx);
  310. ID.AddPointer(parent);
  311. ID.AddPointer(data);
  312. }
  313. void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
  314. Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block,
  315. BlockCount, Index);
  316. }
  317. void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
  318. Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
  319. }
  320. void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
  321. Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
  322. }
  323. //===----------------------------------------------------------------------===//
  324. // LocationContext creation.
  325. //===----------------------------------------------------------------------===//
  326. template <typename LOC, typename DATA>
  327. const LOC*
  328. LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
  329. const LocationContext *parent,
  330. const DATA *d) {
  331. llvm::FoldingSetNodeID ID;
  332. LOC::Profile(ID, ctx, parent, d);
  333. void *InsertPos;
  334. LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  335. if (!L) {
  336. L = new LOC(ctx, parent, d, ++NewID);
  337. Contexts.InsertNode(L, InsertPos);
  338. }
  339. return L;
  340. }
  341. const StackFrameContext *LocationContextManager::getStackFrame(
  342. AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s,
  343. const CFGBlock *blk, unsigned blockCount, unsigned idx) {
  344. llvm::FoldingSetNodeID ID;
  345. StackFrameContext::Profile(ID, ctx, parent, s, blk, blockCount, idx);
  346. void *InsertPos;
  347. auto *L =
  348. cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  349. if (!L) {
  350. L = new StackFrameContext(ctx, parent, s, blk, blockCount, idx, ++NewID);
  351. Contexts.InsertNode(L, InsertPos);
  352. }
  353. return L;
  354. }
  355. const ScopeContext *
  356. LocationContextManager::getScope(AnalysisDeclContext *ctx,
  357. const LocationContext *parent,
  358. const Stmt *s) {
  359. return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
  360. }
  361. const BlockInvocationContext *
  362. LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
  363. const LocationContext *parent,
  364. const BlockDecl *BD,
  365. const void *ContextData) {
  366. llvm::FoldingSetNodeID ID;
  367. BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
  368. void *InsertPos;
  369. auto *L =
  370. cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
  371. InsertPos));
  372. if (!L) {
  373. L = new BlockInvocationContext(ctx, parent, BD, ContextData, ++NewID);
  374. Contexts.InsertNode(L, InsertPos);
  375. }
  376. return L;
  377. }
  378. //===----------------------------------------------------------------------===//
  379. // LocationContext methods.
  380. //===----------------------------------------------------------------------===//
  381. const StackFrameContext *LocationContext::getStackFrame() const {
  382. const LocationContext *LC = this;
  383. while (LC) {
  384. if (const auto *SFC = dyn_cast<StackFrameContext>(LC))
  385. return SFC;
  386. LC = LC->getParent();
  387. }
  388. return nullptr;
  389. }
  390. bool LocationContext::inTopFrame() const {
  391. return getStackFrame()->inTopFrame();
  392. }
  393. bool LocationContext::isParentOf(const LocationContext *LC) const {
  394. do {
  395. const LocationContext *Parent = LC->getParent();
  396. if (Parent == this)
  397. return true;
  398. else
  399. LC = Parent;
  400. } while (LC);
  401. return false;
  402. }
  403. static void printLocation(raw_ostream &Out, const SourceManager &SM,
  404. SourceLocation Loc) {
  405. if (Loc.isFileID() && SM.isInMainFile(Loc))
  406. Out << SM.getExpansionLineNumber(Loc);
  407. else
  408. Loc.print(Out, SM);
  409. }
  410. void LocationContext::dumpStack(raw_ostream &Out, const char *NL,
  411. std::function<void(const LocationContext *)>
  412. printMoreInfoPerContext) const {
  413. ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
  414. PrintingPolicy PP(Ctx.getLangOpts());
  415. PP.TerseOutput = 1;
  416. const SourceManager &SM =
  417. getAnalysisDeclContext()->getASTContext().getSourceManager();
  418. unsigned Frame = 0;
  419. for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
  420. switch (LCtx->getKind()) {
  421. case StackFrame:
  422. Out << "\t#" << Frame << ' ';
  423. ++Frame;
  424. if (const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl()))
  425. Out << "Calling " << D->getQualifiedNameAsString();
  426. else
  427. Out << "Calling anonymous code";
  428. if (const Stmt *S = cast<StackFrameContext>(LCtx)->getCallSite()) {
  429. Out << " at line ";
  430. printLocation(Out, SM, S->getBeginLoc());
  431. }
  432. break;
  433. case Scope:
  434. Out << "Entering scope";
  435. break;
  436. case Block:
  437. Out << "Invoking block";
  438. if (const Decl *D = cast<BlockInvocationContext>(LCtx)->getDecl()) {
  439. Out << " defined at line ";
  440. printLocation(Out, SM, D->getBeginLoc());
  441. }
  442. break;
  443. }
  444. Out << NL;
  445. printMoreInfoPerContext(LCtx);
  446. }
  447. }
  448. void LocationContext::printJson(raw_ostream &Out, const char *NL,
  449. unsigned int Space, bool IsDot,
  450. std::function<void(const LocationContext *)>
  451. printMoreInfoPerContext) const {
  452. ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
  453. PrintingPolicy PP(Ctx.getLangOpts());
  454. PP.TerseOutput = 1;
  455. const SourceManager &SM =
  456. getAnalysisDeclContext()->getASTContext().getSourceManager();
  457. unsigned Frame = 0;
  458. for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
  459. Indent(Out, Space, IsDot)
  460. << "{ \"lctx_id\": " << LCtx->getID() << ", \"location_context\": \"";
  461. switch (LCtx->getKind()) {
  462. case StackFrame:
  463. Out << '#' << Frame << " Call\", \"calling\": \"";
  464. ++Frame;
  465. if (const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl()))
  466. Out << D->getQualifiedNameAsString();
  467. else
  468. Out << "anonymous code";
  469. Out << "\", \"location\": ";
  470. if (const Stmt *S = cast<StackFrameContext>(LCtx)->getCallSite()) {
  471. printSourceLocationAsJson(Out, S->getBeginLoc(), SM);
  472. } else {
  473. Out << "null";
  474. }
  475. Out << ", \"items\": ";
  476. break;
  477. case Scope:
  478. Out << "Entering scope\" ";
  479. break;
  480. case Block:
  481. Out << "Invoking block\" ";
  482. if (const Decl *D = cast<BlockInvocationContext>(LCtx)->getDecl()) {
  483. Out << ", \"location\": ";
  484. printSourceLocationAsJson(Out, D->getBeginLoc(), SM);
  485. Out << ' ';
  486. }
  487. break;
  488. }
  489. printMoreInfoPerContext(LCtx);
  490. Out << '}';
  491. if (LCtx->getParent())
  492. Out << ',';
  493. Out << NL;
  494. }
  495. }
  496. LLVM_DUMP_METHOD void LocationContext::dump() const { printJson(llvm::errs()); }
  497. //===----------------------------------------------------------------------===//
  498. // Lazily generated map to query the external variables referenced by a Block.
  499. //===----------------------------------------------------------------------===//
  500. namespace {
  501. class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
  502. BumpVector<const VarDecl *> &BEVals;
  503. BumpVectorContext &BC;
  504. llvm::SmallPtrSet<const VarDecl *, 4> Visited;
  505. llvm::SmallPtrSet<const DeclContext *, 4> IgnoredContexts;
  506. public:
  507. FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
  508. BumpVectorContext &bc)
  509. : BEVals(bevals), BC(bc) {}
  510. void VisitStmt(Stmt *S) {
  511. for (auto *Child : S->children())
  512. if (Child)
  513. Visit(Child);
  514. }
  515. void VisitDeclRefExpr(DeclRefExpr *DR) {
  516. // Non-local variables are also directly modified.
  517. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  518. if (!VD->hasLocalStorage()) {
  519. if (Visited.insert(VD).second)
  520. BEVals.push_back(VD, BC);
  521. }
  522. }
  523. }
  524. void VisitBlockExpr(BlockExpr *BR) {
  525. // Blocks containing blocks can transitively capture more variables.
  526. IgnoredContexts.insert(BR->getBlockDecl());
  527. Visit(BR->getBlockDecl()->getBody());
  528. }
  529. void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
  530. for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
  531. et = PE->semantics_end(); it != et; ++it) {
  532. Expr *Semantic = *it;
  533. if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  534. Semantic = OVE->getSourceExpr();
  535. Visit(Semantic);
  536. }
  537. }
  538. };
  539. } // namespace
  540. using DeclVec = BumpVector<const VarDecl *>;
  541. static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
  542. void *&Vec,
  543. llvm::BumpPtrAllocator &A) {
  544. if (Vec)
  545. return (DeclVec*) Vec;
  546. BumpVectorContext BC(A);
  547. DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
  548. new (BV) DeclVec(BC, 10);
  549. // Go through the capture list.
  550. for (const auto &CI : BD->captures()) {
  551. BV->push_back(CI.getVariable(), BC);
  552. }
  553. // Find the referenced global/static variables.
  554. FindBlockDeclRefExprsVals F(*BV, BC);
  555. F.Visit(BD->getBody());
  556. Vec = BV;
  557. return BV;
  558. }
  559. llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
  560. AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
  561. if (!ReferencedBlockVars)
  562. ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
  563. const DeclVec *V =
  564. LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
  565. return llvm::make_range(V->begin(), V->end());
  566. }
  567. ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
  568. if (!ManagedAnalyses)
  569. ManagedAnalyses = new ManagedAnalysisMap();
  570. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  571. return (*M)[tag];
  572. }
  573. //===----------------------------------------------------------------------===//
  574. // Cleanup.
  575. //===----------------------------------------------------------------------===//
  576. ManagedAnalysis::~ManagedAnalysis() = default;
  577. AnalysisDeclContext::~AnalysisDeclContext() {
  578. delete forcedBlkExprs;
  579. delete ReferencedBlockVars;
  580. // Release the managed analyses.
  581. if (ManagedAnalyses) {
  582. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  583. llvm::DeleteContainerSeconds(*M);
  584. delete M;
  585. }
  586. }
  587. LocationContext::~LocationContext() = default;
  588. LocationContextManager::~LocationContextManager() {
  589. clear();
  590. }
  591. void LocationContextManager::clear() {
  592. for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
  593. E = Contexts.end(); I != E; ) {
  594. LocationContext *LC = &*I;
  595. ++I;
  596. delete LC;
  597. }
  598. Contexts.clear();
  599. }