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,
70 bool synthesizeBodies,
71 bool addStaticInitBranch,
72 bool addCXXNewAllocator,
73 CodeInjector *injector)
74 : Injector(injector), SynthesizeBodies(synthesizeBodies)
76 cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
77 cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
78 cfgBuildOptions.AddInitializers = addInitializers;
79 cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
80 cfgBuildOptions.AddStaticInitBranches = addStaticInitBranch;
81 cfgBuildOptions.AddCXXNewAllocator = addCXXNewAllocator;
84 void AnalysisDeclContextManager::clear() { Contexts.clear(); }
86 static BodyFarm &getBodyFarm(ASTContext &C, CodeInjector *injector = nullptr) {
87 static BodyFarm *BF = new BodyFarm(C, injector);
91 Stmt *AnalysisDeclContext::getBody(bool &IsAutosynthesized) const {
92 IsAutosynthesized = false;
93 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
94 Stmt *Body = FD->getBody();
95 if (auto *CoroBody = dyn_cast_or_null<CoroutineBodyStmt>(Body))
96 Body = CoroBody->getBody();
97 if (Manager && Manager->synthesizeBodies()) {
98 Stmt *SynthesizedBody =
99 getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(FD);
100 if (SynthesizedBody) {
101 Body = SynthesizedBody;
102 IsAutosynthesized = true;
107 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
108 Stmt *Body = MD->getBody();
109 if (Manager && Manager->synthesizeBodies()) {
110 Stmt *SynthesizedBody =
111 getBodyFarm(getASTContext(), Manager->Injector.get()).getBody(MD);
112 if (SynthesizedBody) {
113 Body = SynthesizedBody;
114 IsAutosynthesized = true;
118 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
119 return BD->getBody();
120 else if (const FunctionTemplateDecl *FunTmpl
121 = dyn_cast_or_null<FunctionTemplateDecl>(D))
122 return FunTmpl->getTemplatedDecl()->getBody();
124 llvm_unreachable("unknown code decl");
127 Stmt *AnalysisDeclContext::getBody() const {
132 bool AnalysisDeclContext::isBodyAutosynthesized() const {
138 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const {
140 Stmt *Body = getBody(Tmp);
141 return Tmp && Body->getLocStart().isValid();
144 /// Returns true if \param VD is an Objective-C implicit 'self' parameter.
145 static bool isSelfDecl(const VarDecl *VD) {
146 return isa<ImplicitParamDecl>(VD) && VD->getName() == "self";
149 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
150 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
151 return MD->getSelfDecl();
152 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
153 // See if 'self' was captured by the block.
154 for (const auto &I : BD->captures()) {
155 const VarDecl *VD = I.getVariable();
157 return dyn_cast<ImplicitParamDecl>(VD);
161 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D);
165 const CXXRecordDecl *parent = CXXMethod->getParent();
166 if (!parent->isLambda())
169 for (const LambdaCapture &LC : parent->captures()) {
170 if (!LC.capturesVariable())
173 VarDecl *VD = LC.getCapturedVar();
175 return dyn_cast<ImplicitParamDecl>(VD);
181 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
183 forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
184 // Default construct an entry for 'stmt'.
185 if (const Expr *e = dyn_cast<Expr>(stmt))
186 stmt = e->IgnoreParens();
187 (void) (*forcedBlkExprs)[stmt];
191 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
192 assert(forcedBlkExprs);
193 if (const Expr *e = dyn_cast<Expr>(stmt))
194 stmt = e->IgnoreParens();
195 CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
196 forcedBlkExprs->find(stmt);
197 assert(itr != forcedBlkExprs->end());
201 /// Add each synthetic statement in the CFG to the parent map, using the
202 /// source statement's parent.
203 static void addParentsForSyntheticStmts(const CFG *TheCFG, ParentMap &PM) {
207 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(),
208 E = TheCFG->synthetic_stmt_end();
210 PM.setParent(I->first, PM.getParent(I->second));
214 CFG *AnalysisDeclContext::getCFG() {
215 if (!cfgBuildOptions.PruneTriviallyFalseEdges)
216 return getUnoptimizedCFG();
219 cfg = CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
220 // Even when the cfg is not successfully built, we don't
221 // want to try building it again.
225 addParentsForSyntheticStmts(cfg.get(), *PM);
227 // The Observer should only observe one build of the CFG.
228 getCFGBuildOptions().Observer = nullptr;
233 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
234 if (!builtCompleteCFG) {
235 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
238 CFG::buildCFG(D, getBody(), &D->getASTContext(), cfgBuildOptions);
239 // Even when the cfg is not successfully built, we don't
240 // want to try building it again.
241 builtCompleteCFG = true;
244 addParentsForSyntheticStmts(completeCFG.get(), *PM);
246 // The Observer should only observe one build of the CFG.
247 getCFGBuildOptions().Observer = nullptr;
249 return completeCFG.get();
252 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
254 return cfgStmtMap.get();
256 if (CFG *c = getCFG()) {
257 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
258 return cfgStmtMap.get();
264 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
268 if (CFG *c = getCFG()) {
269 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
276 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
277 getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
280 ParentMap &AnalysisDeclContext::getParentMap() {
282 PM.reset(new ParentMap(getBody()));
283 if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
284 for (const auto *I : C->inits()) {
285 PM->addStmt(I->getInit());
289 addParentsForSyntheticStmts(getCFG(), *PM);
290 if (builtCompleteCFG)
291 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM);
296 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
298 PCA.reset(new PseudoConstantAnalysis(getBody()));
302 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
303 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
304 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
305 // that has the body.
310 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D];
312 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions);
316 const StackFrameContext *
317 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
318 const CFGBlock *Blk, unsigned Idx) {
319 return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
322 const BlockInvocationContext *
323 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
324 const clang::BlockDecl *BD,
325 const void *ContextData) {
326 return getLocationContextManager().getBlockInvocationContext(this, parent,
330 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) {
331 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext();
332 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
336 while (const DeclContext *Parent = ND->getParent()) {
337 if (!isa<NamespaceDecl>(Parent))
339 ND = cast<NamespaceDecl>(Parent);
342 return ND->isStdNamespace();
345 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
347 "Cannot create LocationContexts without an AnalysisDeclContextManager!");
348 return Manager->getLocationContextManager();
351 //===----------------------------------------------------------------------===//
352 // FoldingSet profiling.
353 //===----------------------------------------------------------------------===//
355 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
357 AnalysisDeclContext *ctx,
358 const LocationContext *parent,
362 ID.AddPointer(parent);
366 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
367 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
370 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
371 Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
374 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
375 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
378 //===----------------------------------------------------------------------===//
379 // LocationContext creation.
380 //===----------------------------------------------------------------------===//
382 template <typename LOC, typename DATA>
384 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
385 const LocationContext *parent,
387 llvm::FoldingSetNodeID ID;
388 LOC::Profile(ID, ctx, parent, d);
391 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
394 L = new LOC(ctx, parent, d);
395 Contexts.InsertNode(L, InsertPos);
400 const StackFrameContext*
401 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
402 const LocationContext *parent,
404 const CFGBlock *blk, unsigned idx) {
405 llvm::FoldingSetNodeID ID;
406 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
408 StackFrameContext *L =
409 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
411 L = new StackFrameContext(ctx, parent, s, blk, idx);
412 Contexts.InsertNode(L, InsertPos);
418 LocationContextManager::getScope(AnalysisDeclContext *ctx,
419 const LocationContext *parent,
421 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
424 const BlockInvocationContext *
425 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
426 const LocationContext *parent,
428 const void *ContextData) {
429 llvm::FoldingSetNodeID ID;
430 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
432 BlockInvocationContext *L =
433 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
436 L = new BlockInvocationContext(ctx, parent, BD, ContextData);
437 Contexts.InsertNode(L, InsertPos);
442 //===----------------------------------------------------------------------===//
443 // LocationContext methods.
444 //===----------------------------------------------------------------------===//
446 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
447 const LocationContext *LC = this;
449 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
451 LC = LC->getParent();
456 bool LocationContext::inTopFrame() const {
457 return getCurrentStackFrame()->inTopFrame();
460 bool LocationContext::isParentOf(const LocationContext *LC) const {
462 const LocationContext *Parent = LC->getParent();
472 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const {
473 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext();
474 PrintingPolicy PP(Ctx.getLangOpts());
478 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) {
479 switch (LCtx->getKind()) {
481 OS << Indent << '#' << Frame++ << ' ';
482 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP);
486 OS << Indent << " (scope)\n";
489 OS << Indent << " (block context: "
490 << cast<BlockInvocationContext>(LCtx)->getContextData()
497 LLVM_DUMP_METHOD void LocationContext::dumpStack() const {
498 dumpStack(llvm::errs());
501 //===----------------------------------------------------------------------===//
502 // Lazily generated map to query the external variables referenced by a Block.
503 //===----------------------------------------------------------------------===//
506 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
507 BumpVector<const VarDecl*> &BEVals;
508 BumpVectorContext &BC;
509 llvm::SmallPtrSet<const VarDecl*, 4> Visited;
510 llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
512 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
513 BumpVectorContext &bc)
514 : BEVals(bevals), BC(bc) {}
516 void VisitStmt(Stmt *S) {
517 for (Stmt *Child : S->children())
522 void VisitDeclRefExpr(DeclRefExpr *DR) {
523 // Non-local variables are also directly modified.
524 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
525 if (!VD->hasLocalStorage()) {
526 if (Visited.insert(VD).second)
527 BEVals.push_back(VD, BC);
532 void VisitBlockExpr(BlockExpr *BR) {
533 // Blocks containing blocks can transitively capture more variables.
534 IgnoredContexts.insert(BR->getBlockDecl());
535 Visit(BR->getBlockDecl()->getBody());
538 void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
539 for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
540 et = PE->semantics_end(); it != et; ++it) {
541 Expr *Semantic = *it;
542 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
543 Semantic = OVE->getSourceExpr();
548 } // end anonymous namespace
550 typedef BumpVector<const VarDecl*> DeclVec;
552 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
554 llvm::BumpPtrAllocator &A) {
556 return (DeclVec*) Vec;
558 BumpVectorContext BC(A);
559 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
560 new (BV) DeclVec(BC, 10);
562 // Go through the capture list.
563 for (const auto &CI : BD->captures()) {
564 BV->push_back(CI.getVariable(), BC);
567 // Find the referenced global/static variables.
568 FindBlockDeclRefExprsVals F(*BV, BC);
569 F.Visit(BD->getBody());
575 llvm::iterator_range<AnalysisDeclContext::referenced_decls_iterator>
576 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
577 if (!ReferencedBlockVars)
578 ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
581 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
582 return llvm::make_range(V->begin(), V->end());
585 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
586 if (!ManagedAnalyses)
587 ManagedAnalyses = new ManagedAnalysisMap();
588 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
592 //===----------------------------------------------------------------------===//
594 //===----------------------------------------------------------------------===//
596 ManagedAnalysis::~ManagedAnalysis() {}
598 AnalysisDeclContext::~AnalysisDeclContext() {
599 delete forcedBlkExprs;
600 delete ReferencedBlockVars;
601 // Release the managed analyses.
602 if (ManagedAnalyses) {
603 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
604 llvm::DeleteContainerSeconds(*M);
609 AnalysisDeclContextManager::~AnalysisDeclContextManager() {}
611 LocationContext::~LocationContext() {}
613 LocationContextManager::~LocationContextManager() {
617 void LocationContextManager::clear() {
618 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
619 E = Contexts.end(); I != E; ) {
620 LocationContext *LC = &*I;