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