1 //== AnalysisDeclContext.cpp - Analysis context for Path Sens analysis -*- C++ -*-//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines AnalysisDeclContext, a class that manages the analysis context
11 // data for path sensitive analysis.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Analysis/AnalysisContext.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/ParentMap.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
24 #include "clang/Analysis/Analyses/LiveVariables.h"
25 #include "clang/Analysis/Analyses/PseudoConstantAnalysis.h"
26 #include "clang/Analysis/CFG.h"
27 #include "clang/Analysis/CFGStmtMap.h"
28 #include "clang/Analysis/Support/BumpVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/SaveAndRestore.h"
32 #include "llvm/Support/raw_ostream.h"
34 using namespace clang;
36 typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap;
38 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
40 const CFG::BuildOptions &buildOptions)
43 cfgBuildOptions(buildOptions),
44 forcedBlkExprs(nullptr),
46 builtCompleteCFG(false),
47 ReferencedBlockVars(nullptr),
48 ManagedAnalyses(nullptr)
50 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
53 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
57 forcedBlkExprs(nullptr),
59 builtCompleteCFG(false),
60 ReferencedBlockVars(nullptr),
61 ManagedAnalyses(nullptr)
63 cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
66 AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG,
67 bool addImplicitDtors,
69 bool addTemporaryDtors,
71 bool synthesizeBodies,
72 bool addStaticInitBranch,
73 bool addCXXNewAllocator,
74 CodeInjector *injector)
75 : Injector(injector), SynthesizeBodies(synthesizeBodies)
77 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
78 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
79 cfgBuildOptions.AddInitializers = addInitializers;
80 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
81 cfgBuildOptions.AddLifetime = addLifetime;
82 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
83 cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
86 void AnalysisDeclContextManager::clear() { Contexts.clear(); }
88 static BodyFarm &getBodyFarm(ASTContext &C, CodeInjector *injector = nullptr) {
89 static BodyFarm *BF = new BodyFarm(C, injector);
93 Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
94 IsAutosynthesized = false;
95 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
96 Stmt *Body = FD->getBody();
97 if (auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body))
98 Body = CoroBody->getBody();
99 if (Manager && Manager->synthesizeBodies()) {
100 Stmt *SynthesizedBody =
101 getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(FD);
102 if (SynthesizedBody) {
103 Body = SynthesizedBody;
104 IsAutosynthesized = true;
109 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 Stmt *Body = MD->getBody();
111 if (Manager && Manager->synthesizeBodies()) {
112 Stmt *SynthesizedBody =
113 getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(MD);
114 if (SynthesizedBody) {
115 Body = SynthesizedBody;
116 IsAutosynthesized = true;
120 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
121 return BD->getBody();
122 else if (const FunctionTemplateDecl *FunTmpl
123 = dyn_cast_or_null<FunctionTemplateDecl>(D))
124 return FunTmpl->getTemplatedDecl()->getBody();
126 llvm_unreachable("unknown code decl");
129 Stmt *AnalysisDeclContext::getBody() const {
134 bool AnalysisDeclContext::isBodyAutosynthesized() const {
140 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
142 Stmt *Body = getBody(Tmp);
143 return Tmp && Body->getLocStart().isValid();
146 /// Returns true if \param VD is an Objective-C implicit 'self' parameter.
147 static bool isSelfDecl(const VarDecl *VD) {
148 return isa<ImplicitParamDecl>(VD) && VD->getName() == "self";
151 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
152 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
153 return MD->getSelfDecl();
154 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
155 // See if 'self' was captured by the block.
156 for (const auto &I : BD->captures()) {
157 const VarDecl *VD = I.getVariable();
159 return dyn_cast<ImplicitParamDecl>(VD);
163 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D);
167 const CXXRecordDecl *parent = CXXMethod->getParent();
168 if (!parent->isLambda())
171 for (const LambdaCapture &LC : parent->captures()) {
172 if (!LC.capturesVariable())
175 VarDecl *VD = LC.getCapturedVar();
177 return dyn_cast<ImplicitParamDecl>(VD);
183 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
185 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
186 // Default construct an entry for 'stmt'.
187 if (const Expr *e = dyn_cast<Expr>(stmt))
188 stmt = e->IgnoreParens();
189 (void) (*forcedBlkExprs)[stmt];
193 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
194 assert(forcedBlkExprs);
195 if (const Expr *e = dyn_cast<Expr>(stmt))
196 stmt = e->IgnoreParens();
197 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
198 forcedBlkExprs->find(stmt);
199 assert(itr != forcedBlkExprs->end());
203 /// Add each synthetic statement in the CFG to the parent map, using the
204 /// source statement's parent.
205 static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
209 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
210 E = TheCFG->synthetic_stmt_end();
212 PM.setParent(I->first, PM.getParent(I->second));
216 CFG *AnalysisDeclContext::getCFG() {
217 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
218 return getUnoptimizedCFG();
221 cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
222 // Even when the cfg is not successfully built, we don't
223 // want to try building it again.
227 addParentsForSyntheticStmts(cfg.get(), *PM);
229 // The Observer should only observe one build of the CFG.
230 getCFGBuildOptions().Observer = nullptr;
235 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
236 if (!builtCompleteCFG) {
237 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
240 CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
241 // Even when the cfg is not successfully built, we don't
242 // want to try building it again.
243 builtCompleteCFG = true;
246 addParentsForSyntheticStmts(completeCFG.get(), *PM);
248 // The Observer should only observe one build of the CFG.
249 getCFGBuildOptions().Observer = nullptr;
251 return completeCFG.get();
254 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
256 return cfgStmtMap.get();
258 if (CFG *c = getCFG()) {
259 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
260 return cfgStmtMap.get();
266 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
270 if (CFG *c = getCFG()) {
271 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
278 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
279 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
282 ParentMap &AnalysisDeclContext::getParentMap() {
284 PM.reset(new ParentMap(getBody()));
285 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
286 for (const auto *I : C->inits()) {
287 PM->addStmt(I->getInit());
291 addParentsForSyntheticStmts(getCFG(), *PM);
292 if (builtCompleteCFG)
293 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
298 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
300 PCA.reset(new PseudoConstantAnalysis(getBody()));
304 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
305 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
306 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
307 // that has the body.
312 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
314 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions);
318 const StackFrameContext *
319 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
320 const CFGBlock *Blk, unsigned Idx) {
321 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
324 const BlockInvocationContext *
325 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
326 const clang::BlockDecl *BD,
327 const void *ContextData) {
328 return getLocationContextManager().getBlockInvocationContext(this, parent,
332 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
333 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
334 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
338 while (const DeclContext *Parent = ND->getParent()) {
339 if (!isa<NamespaceDecl>(Parent))
341 ND = cast<NamespaceDecl>(Parent);
344 return ND->isStdNamespace();
347 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
349 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
350 return Manager->getLocationContextManager();
353 //===----------------------------------------------------------------------===//
354 // FoldingSet profiling.
355 //===----------------------------------------------------------------------===//
357 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
359 AnalysisDeclContext *ctx,
360 const LocationContext *parent,
364 ID.AddPointer(parent);
368 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
369 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
372 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
373 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
376 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
377 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
380 //===----------------------------------------------------------------------===//
381 // LocationContext creation.
382 //===----------------------------------------------------------------------===//
384 template <typename LOC, typename DATA>
386 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
387 const LocationContext *parent,
389 llvm::FoldingSetNodeID ID;
390 LOC::Profile(ID, ctx, parent, d);
393 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
396 L = new LOC(ctx, parent, d);
397 Contexts.InsertNode(L, InsertPos);
402 const StackFrameContext*
403 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
404 const LocationContext *parent,
406 const CFGBlock *blk, unsigned idx) {
407 llvm::FoldingSetNodeID ID;
408 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
410 StackFrameContext *L =
411 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
413 L = new StackFrameContext(ctx, parent, s, blk, idx);
414 Contexts.InsertNode(L, InsertPos);
420 LocationContextManager::getScope(AnalysisDeclContext *ctx,
421 const LocationContext *parent,
423 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
426 const BlockInvocationContext *
427 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
428 const LocationContext *parent,
430 const void *ContextData) {
431 llvm::FoldingSetNodeID ID;
432 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
434 BlockInvocationContext *L =
435 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
438 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
439 Contexts.InsertNode(L, InsertPos);
444 //===----------------------------------------------------------------------===//
445 // LocationContext methods.
446 //===----------------------------------------------------------------------===//
448 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
449 const LocationContext *LC = this;
451 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
453 LC = LC->getParent();
458 bool LocationContext::inTopFrame() const {
459 return getCurrentStackFrame()->inTopFrame();
462 bool LocationContext::isParentOf(const LocationContext *LC) const {
464 const LocationContext *Parent = LC->getParent();
474 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const {
475 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
476 PrintingPolicy PP(Ctx.getLangOpts());
480 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
481 switch (LCtx->getKind()) {
483 OS << Indent << '#' << Frame++ << ' ';
484 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP);
488 OS << Indent << " (scope)\n";
491 OS << Indent << " (block context: "
492 << cast<BlockInvocationContext>(LCtx)->getContextData()
499 LLVM_DUMP_METHOD void LocationContext::dumpStack() const {
500 dumpStack(llvm::errs());
503 //===----------------------------------------------------------------------===//
504 // Lazily generated map to query the external variables referenced by a Block.
505 //===----------------------------------------------------------------------===//
508 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
509 BumpVector<const VarDecl*> &BEVals;
510 BumpVectorContext &BC;
511 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
512 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
514 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
515 BumpVectorContext &bc)
516 : BEVals(bevals), BC(bc) {}
518 void VisitStmt(Stmt *S) {
519 for (Stmt *Child : S->children())
524 void VisitDeclRefExpr(DeclRefExpr *DR) {
525 // Non-local variables are also directly modified.
526 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
527 if (!VD->hasLocalStorage()) {
528 if (Visited.insert(VD).second)
529 BEVals.push_back(VD, BC);
534 void VisitBlockExpr(BlockExpr *BR) {
535 // Blocks containing blocks can transitively capture more variables.
536 IgnoredContexts.insert(BR->getBlockDecl());
537 Visit(BR->getBlockDecl()->getBody());
540 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
541 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
542 et = PE->semantics_end(); it != et; ++it) {
543 Expr *Semantic = *it;
544 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
545 Semantic = OVE->getSourceExpr();
550 } // end anonymous namespace
552 typedef BumpVector<const VarDecl*> DeclVec;
554 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
556 llvm::BumpPtrAllocator &A) {
558 return (DeclVec*) Vec;
560 BumpVectorContext BC(A);
561 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
562 new (BV) DeclVec(BC, 10);
564 // Go through the capture list.
565 for (const auto &CI : BD->captures()) {
566 BV->push_back(CI.getVariable(), BC);
569 // Find the referenced global/static variables.
570 FindBlockDeclRefExprsVals F(*BV, BC);
571 F.Visit(BD->getBody());
577 llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
578 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
579 if (!ReferencedBlockVars)
580 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
583 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
584 return llvm::make_range(V->begin(), V->end());
587 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
588 if (!ManagedAnalyses)
589 ManagedAnalyses = new ManagedAnalysisMap();
590 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
594 //===----------------------------------------------------------------------===//
596 //===----------------------------------------------------------------------===//
598 ManagedAnalysis::~ManagedAnalysis() {}
600 AnalysisDeclContext::~AnalysisDeclContext() {
601 delete forcedBlkExprs;
602 delete ReferencedBlockVars;
603 // Release the managed analyses.
604 if (ManagedAnalyses) {
605 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
606 llvm::DeleteContainerSeconds(*M);
611 AnalysisDeclContextManager::~AnalysisDeclContextManager() {}
613 LocationContext::~LocationContext() {}
615 LocationContextManager::~LocationContextManager() {
619 void LocationContextManager::clear() {
620 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
621 E = Contexts.end(); I != E; ) {
622 LocationContext *LC = &*I;