AnalysisDeclContext.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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 *, std::unique_ptr<ManagedAnalysis>>;
  51. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *ADCMgr,
  52. const Decl *D,
  53. const CFG::BuildOptions &Options)
  54. : ADCMgr(ADCMgr), D(D), cfgBuildOptions(Options) {
  55. cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
  56. }
  57. AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *ADCMgr,
  58. const Decl *D)
  59. : ADCMgr(ADCMgr), 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 (ADCMgr && ADCMgr->synthesizeBodies()) {
  92. Stmt *SynthesizedBody = ADCMgr->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 (ADCMgr && ADCMgr->synthesizeBodies()) {
  103. Stmt *SynthesizedBody = ADCMgr->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(const LocationContext *ParentLC,
  271. const Stmt *S, const CFGBlock *Blk,
  272. unsigned BlockCount, unsigned Index) {
  273. return getLocationContextManager().getStackFrame(this, ParentLC, S, Blk,
  274. BlockCount, Index);
  275. }
  276. const BlockInvocationContext *AnalysisDeclContext::getBlockInvocationContext(
  277. const LocationContext *ParentLC, const BlockDecl *BD, const void *Data) {
  278. return getLocationContextManager().getBlockInvocationContext(this, ParentLC,
  279. BD, Data);
  280. }
  281. bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
  282. const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
  283. const auto *ND = dyn_cast<NamespaceDecl>(DC);
  284. if (!ND)
  285. return false;
  286. while (const DeclContext *Parent = ND->getParent()) {
  287. if (!isa<NamespaceDecl>(Parent))
  288. break;
  289. ND = cast<NamespaceDecl>(Parent);
  290. }
  291. return ND->isStdNamespace();
  292. }
  293. std::string AnalysisDeclContext::getFunctionName(const Decl *D) {
  294. std::string Str;
  295. llvm::raw_string_ostream OS(Str);
  296. const ASTContext &Ctx = D->getASTContext();
  297. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  298. OS << FD->getQualifiedNameAsString();
  299. // In C++, there are overloads.
  300. if (Ctx.getLangOpts().CPlusPlus) {
  301. OS << '(';
  302. for (const auto &P : FD->parameters()) {
  303. if (P != *FD->param_begin())
  304. OS << ", ";
  305. OS << P->getType().getAsString();
  306. }
  307. OS << ')';
  308. }
  309. } else if (isa<BlockDecl>(D)) {
  310. PresumedLoc Loc = Ctx.getSourceManager().getPresumedLoc(D->getLocation());
  311. if (Loc.isValid()) {
  312. OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
  313. << ')';
  314. }
  315. } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
  316. // FIXME: copy-pasted from CGDebugInfo.cpp.
  317. OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
  318. const DeclContext *DC = OMD->getDeclContext();
  319. if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
  320. OS << OID->getName();
  321. } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
  322. OS << OID->getName();
  323. } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
  324. if (OC->IsClassExtension()) {
  325. OS << OC->getClassInterface()->getName();
  326. } else {
  327. OS << OC->getIdentifier()->getNameStart() << '('
  328. << OC->getIdentifier()->getNameStart() << ')';
  329. }
  330. } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
  331. OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
  332. }
  333. OS << ' ' << OMD->getSelector().getAsString() << ']';
  334. }
  335. return Str;
  336. }
  337. LocationContextManager &AnalysisDeclContext::getLocationContextManager() {
  338. assert(
  339. ADCMgr &&
  340. "Cannot create LocationContexts without an AnalysisDeclContextManager!");
  341. return ADCMgr->getLocationContextManager();
  342. }
  343. //===----------------------------------------------------------------------===//
  344. // FoldingSet profiling.
  345. //===----------------------------------------------------------------------===//
  346. void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
  347. ContextKind ck,
  348. AnalysisDeclContext *ctx,
  349. const LocationContext *parent,
  350. const void *data) {
  351. ID.AddInteger(ck);
  352. ID.AddPointer(ctx);
  353. ID.AddPointer(parent);
  354. ID.AddPointer(data);
  355. }
  356. void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
  357. Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block,
  358. BlockCount, Index);
  359. }
  360. void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
  361. Profile(ID, getAnalysisDeclContext(), getParent(), BD, Data);
  362. }
  363. //===----------------------------------------------------------------------===//
  364. // LocationContext creation.
  365. //===----------------------------------------------------------------------===//
  366. const StackFrameContext *LocationContextManager::getStackFrame(
  367. AnalysisDeclContext *ctx, const LocationContext *parent, const Stmt *s,
  368. const CFGBlock *blk, unsigned blockCount, unsigned idx) {
  369. llvm::FoldingSetNodeID ID;
  370. StackFrameContext::Profile(ID, ctx, parent, s, blk, blockCount, idx);
  371. void *InsertPos;
  372. auto *L =
  373. cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
  374. if (!L) {
  375. L = new StackFrameContext(ctx, parent, s, blk, blockCount, idx, ++NewID);
  376. Contexts.InsertNode(L, InsertPos);
  377. }
  378. return L;
  379. }
  380. const BlockInvocationContext *LocationContextManager::getBlockInvocationContext(
  381. AnalysisDeclContext *ADC, const LocationContext *ParentLC,
  382. const BlockDecl *BD, const void *Data) {
  383. llvm::FoldingSetNodeID ID;
  384. BlockInvocationContext::Profile(ID, ADC, ParentLC, BD, Data);
  385. void *InsertPos;
  386. auto *L =
  387. cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
  388. InsertPos));
  389. if (!L) {
  390. L = new BlockInvocationContext(ADC, ParentLC, BD, Data, ++NewID);
  391. Contexts.InsertNode(L, InsertPos);
  392. }
  393. return L;
  394. }
  395. //===----------------------------------------------------------------------===//
  396. // LocationContext methods.
  397. //===----------------------------------------------------------------------===//
  398. const StackFrameContext *LocationContext::getStackFrame() const {
  399. const LocationContext *LC = this;
  400. while (LC) {
  401. if (const auto *SFC = dyn_cast<StackFrameContext>(LC))
  402. return SFC;
  403. LC = LC->getParent();
  404. }
  405. return nullptr;
  406. }
  407. bool LocationContext::inTopFrame() const {
  408. return getStackFrame()->inTopFrame();
  409. }
  410. bool LocationContext::isParentOf(const LocationContext *LC) const {
  411. do {
  412. const LocationContext *Parent = LC->getParent();
  413. if (Parent == this)
  414. return true;
  415. else
  416. LC = Parent;
  417. } while (LC);
  418. return false;
  419. }
  420. static void printLocation(raw_ostream &Out, const SourceManager &SM,
  421. SourceLocation Loc) {
  422. if (Loc.isFileID() && SM.isInMainFile(Loc))
  423. Out << SM.getExpansionLineNumber(Loc);
  424. else
  425. Loc.print(Out, SM);
  426. }
  427. void LocationContext::dumpStack(raw_ostream &Out) const {
  428. ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
  429. PrintingPolicy PP(Ctx.getLangOpts());
  430. PP.TerseOutput = 1;
  431. const SourceManager &SM =
  432. getAnalysisDeclContext()->getASTContext().getSourceManager();
  433. unsigned Frame = 0;
  434. for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
  435. switch (LCtx->getKind()) {
  436. case StackFrame:
  437. Out << "\t#" << Frame << ' ';
  438. ++Frame;
  439. if (const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl()))
  440. Out << "Calling " << AnalysisDeclContext::getFunctionName(D);
  441. else
  442. Out << "Calling anonymous code";
  443. if (const Stmt *S = cast<StackFrameContext>(LCtx)->getCallSite()) {
  444. Out << " at line ";
  445. printLocation(Out, SM, S->getBeginLoc());
  446. }
  447. break;
  448. case Block:
  449. Out << "Invoking block";
  450. if (const Decl *D = cast<BlockInvocationContext>(LCtx)->getDecl()) {
  451. Out << " defined at line ";
  452. printLocation(Out, SM, D->getBeginLoc());
  453. }
  454. break;
  455. }
  456. Out << '\n';
  457. }
  458. }
  459. void LocationContext::printJson(raw_ostream &Out, const char *NL,
  460. unsigned int Space, bool IsDot,
  461. std::function<void(const LocationContext *)>
  462. printMoreInfoPerContext) const {
  463. ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
  464. PrintingPolicy PP(Ctx.getLangOpts());
  465. PP.TerseOutput = 1;
  466. const SourceManager &SM =
  467. getAnalysisDeclContext()->getASTContext().getSourceManager();
  468. unsigned Frame = 0;
  469. for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
  470. Indent(Out, Space, IsDot)
  471. << "{ \"lctx_id\": " << LCtx->getID() << ", \"location_context\": \"";
  472. switch (LCtx->getKind()) {
  473. case StackFrame:
  474. Out << '#' << Frame << " Call\", \"calling\": \"";
  475. ++Frame;
  476. if (const auto *D = dyn_cast<NamedDecl>(LCtx->getDecl()))
  477. Out << D->getQualifiedNameAsString();
  478. else
  479. Out << "anonymous code";
  480. Out << "\", \"location\": ";
  481. if (const Stmt *S = cast<StackFrameContext>(LCtx)->getCallSite()) {
  482. printSourceLocationAsJson(Out, S->getBeginLoc(), SM);
  483. } else {
  484. Out << "null";
  485. }
  486. Out << ", \"items\": ";
  487. break;
  488. case Block:
  489. Out << "Invoking block\" ";
  490. if (const Decl *D = cast<BlockInvocationContext>(LCtx)->getDecl()) {
  491. Out << ", \"location\": ";
  492. printSourceLocationAsJson(Out, D->getBeginLoc(), SM);
  493. Out << ' ';
  494. }
  495. break;
  496. }
  497. printMoreInfoPerContext(LCtx);
  498. Out << '}';
  499. if (LCtx->getParent())
  500. Out << ',';
  501. Out << NL;
  502. }
  503. }
  504. LLVM_DUMP_METHOD void LocationContext::dump() const { printJson(llvm::errs()); }
  505. //===----------------------------------------------------------------------===//
  506. // Lazily generated map to query the external variables referenced by a Block.
  507. //===----------------------------------------------------------------------===//
  508. namespace {
  509. class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
  510. BumpVector<const VarDecl *> &BEVals;
  511. BumpVectorContext &BC;
  512. llvm::SmallPtrSet<const VarDecl *, 4> Visited;
  513. llvm::SmallPtrSet<const DeclContext *, 4> IgnoredContexts;
  514. public:
  515. FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
  516. BumpVectorContext &bc)
  517. : BEVals(bevals), BC(bc) {}
  518. void VisitStmt(Stmt *S) {
  519. for (auto *Child : S->children())
  520. if (Child)
  521. Visit(Child);
  522. }
  523. void VisitDeclRefExpr(DeclRefExpr *DR) {
  524. // Non-local variables are also directly modified.
  525. if (const auto *VD = dyn_cast<VarDecl>(DR->getDecl())) {
  526. if (!VD->hasLocalStorage()) {
  527. if (Visited.insert(VD).second)
  528. BEVals.push_back(VD, BC);
  529. }
  530. }
  531. }
  532. void VisitBlockExpr(BlockExpr *BR) {
  533. // Blocks containing blocks can transitively capture more variables.
  534. IgnoredContexts.insert(BR->getBlockDecl());
  535. Visit(BR->getBlockDecl()->getBody());
  536. }
  537. void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
  538. for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
  539. et = PE->semantics_end(); it != et; ++it) {
  540. Expr *Semantic = *it;
  541. if (auto *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
  542. Semantic = OVE->getSourceExpr();
  543. Visit(Semantic);
  544. }
  545. }
  546. };
  547. } // namespace
  548. using DeclVec = BumpVector<const VarDecl *>;
  549. static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
  550. void *&Vec,
  551. llvm::BumpPtrAllocator &A) {
  552. if (Vec)
  553. return (DeclVec*) Vec;
  554. BumpVectorContext BC(A);
  555. DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
  556. new (BV) DeclVec(BC, 10);
  557. // Go through the capture list.
  558. for (const auto &CI : BD->captures()) {
  559. BV->push_back(CI.getVariable(), BC);
  560. }
  561. // Find the referenced global/static variables.
  562. FindBlockDeclRefExprsVals F(*BV, BC);
  563. F.Visit(BD->getBody());
  564. Vec = BV;
  565. return BV;
  566. }
  567. llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
  568. AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
  569. if (!ReferencedBlockVars)
  570. ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
  571. const DeclVec *V =
  572. LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
  573. return llvm::make_range(V->begin(), V->end());
  574. }
  575. std::unique_ptr<ManagedAnalysis> &AnalysisDeclContext::getAnalysisImpl(const void *tag) {
  576. if (!ManagedAnalyses)
  577. ManagedAnalyses = new ManagedAnalysisMap();
  578. ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
  579. return (*M)[tag];
  580. }
  581. //===----------------------------------------------------------------------===//
  582. // Cleanup.
  583. //===----------------------------------------------------------------------===//
  584. ManagedAnalysis::~ManagedAnalysis() = default;
  585. AnalysisDeclContext::~AnalysisDeclContext() {
  586. delete forcedBlkExprs;
  587. delete ReferencedBlockVars;
  588. delete (ManagedAnalysisMap*) ManagedAnalyses;
  589. }
  590. LocationContext::~LocationContext() = default;
  591. LocationContextManager::~LocationContextManager() {
  592. clear();
  593. }
  594. void LocationContextManager::clear() {
  595. for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
  596. E = Contexts.end(); I != E; ) {
  597. LocationContext *LC = &*I;
  598. ++I;
  599. delete LC;
  600. }
  601. Contexts.clear();
  602. }