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 
33 using namespace clang;
34 
35 typedef llvm::DenseMap<const void *, ManagedAnalysis *> ManagedAnalysisMap;
36 
37 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
38                                          const Decl *d,
39                                          const CFG::BuildOptions &buildOptions)
40   : Manager(Mgr),
41     D(d),
42     cfgBuildOptions(buildOptions),
43     forcedBlkExprs(0),
44     builtCFG(false),
45     builtCompleteCFG(false),
46     ReferencedBlockVars(0),
47     ManagedAnalyses(0)
48 {
49   cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
50 }
51 
52 AnalysisDeclContext::AnalysisDeclContext(AnalysisDeclContextManager *Mgr,
53                                          const Decl *d)
54 : Manager(Mgr),
55   D(d),
56   forcedBlkExprs(0),
57   builtCFG(false),
58   builtCompleteCFG(false),
59   ReferencedBlockVars(0),
60   ManagedAnalyses(0)
61 {
62   cfgBuildOptions.forcedBlkExprs = &forcedBlkExprs;
63 }
64 
65 AnalysisDeclContextManager::AnalysisDeclContextManager(bool useUnoptimizedCFG,
66                                                        bool addImplicitDtors,
67                                                        bool addInitializers,
68                                                        bool addTemporaryDtors,
69                                                        bool synthesizeBodies)
70   : SynthesizeBodies(synthesizeBodies)
71 {
72   cfgBuildOptions.PruneTriviallyFalseEdges = !useUnoptimizedCFG;
73   cfgBuildOptions.AddImplicitDtors = addImplicitDtors;
74   cfgBuildOptions.AddInitializers = addInitializers;
75   cfgBuildOptions.AddTemporaryDtors = addTemporaryDtors;
76 }
77 
78 void AnalysisDeclContextManager::clear() {
79   for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
80     delete I->second;
81   Contexts.clear();
82 }
83 
84 static BodyFarm &getBodyFarm(ASTContext &C) {
85   static BodyFarm *BF = new BodyFarm(C);
86   return *BF;
87 }
88 
89 Stmt *AnalysisDeclContext::getBody() const {
90   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
91     Stmt *Body = FD->getBody();
92     if (!Body && Manager && Manager->synthesizeBodies())
93       return getBodyFarm(getASTContext()).getBody(FD);
94     return Body;
95   }
96   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
97     return MD->getBody();
98   else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
99     return BD->getBody();
100   else if (const FunctionTemplateDecl *FunTmpl
101            = dyn_cast_or_null<FunctionTemplateDecl>(D))
102     return FunTmpl->getTemplatedDecl()->getBody();
103 
104   llvm_unreachable("unknown code decl");
105 }
106 
107 const ImplicitParamDecl *AnalysisDeclContext::getSelfDecl() const {
108   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
109     return MD->getSelfDecl();
110   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
111     // See if 'self' was captured by the block.
112     for (BlockDecl::capture_const_iterator it = BD->capture_begin(),
113          et = BD->capture_end(); it != et; ++it) {
114       const VarDecl *VD = it->getVariable();
115       if (VD->getName() == "self")
116         return dyn_cast<ImplicitParamDecl>(VD);
117     }
118   }
119 
120   return NULL;
121 }
122 
123 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) {
124   if (!forcedBlkExprs)
125     forcedBlkExprs = new CFG::BuildOptions::ForcedBlkExprs();
126   // Default construct an entry for 'stmt'.
127   if (const Expr *e = dyn_cast<Expr>(stmt))
128     stmt = e->IgnoreParens();
129   (void) (*forcedBlkExprs)[stmt];
130 }
131 
132 const CFGBlock *
133 AnalysisDeclContext::getBlockForRegisteredExpression(const Stmt *stmt) {
134   assert(forcedBlkExprs);
135   if (const Expr *e = dyn_cast<Expr>(stmt))
136     stmt = e->IgnoreParens();
137   CFG::BuildOptions::ForcedBlkExprs::const_iterator itr =
138     forcedBlkExprs->find(stmt);
139   assert(itr != forcedBlkExprs->end());
140   return itr->second;
141 }
142 
143 CFG *AnalysisDeclContext::getCFG() {
144   if (!cfgBuildOptions.PruneTriviallyFalseEdges)
145     return getUnoptimizedCFG();
146 
147   if (!builtCFG) {
148     cfg.reset(CFG::buildCFG(D, getBody(),
149                             &D->getASTContext(), cfgBuildOptions));
150     // Even when the cfg is not successfully built, we don't
151     // want to try building it again.
152     builtCFG = true;
153   }
154   return cfg.get();
155 }
156 
157 CFG *AnalysisDeclContext::getUnoptimizedCFG() {
158   if (!builtCompleteCFG) {
159     SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges,
160                                   false);
161     completeCFG.reset(CFG::buildCFG(D, getBody(), &D->getASTContext(),
162                                     cfgBuildOptions));
163     // Even when the cfg is not successfully built, we don't
164     // want to try building it again.
165     builtCompleteCFG = true;
166   }
167   return completeCFG.get();
168 }
169 
170 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() {
171   if (cfgStmtMap)
172     return cfgStmtMap.get();
173 
174   if (CFG *c = getCFG()) {
175     cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap()));
176     return cfgStmtMap.get();
177   }
178 
179   return 0;
180 }
181 
182 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() {
183   if (CFA)
184     return CFA.get();
185 
186   if (CFG *c = getCFG()) {
187     CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c));
188     return CFA.get();
189   }
190 
191   return 0;
192 }
193 
194 void AnalysisDeclContext::dumpCFG(bool ShowColors) {
195     getCFG()->dump(getASTContext().getLangOpts(), ShowColors);
196 }
197 
198 ParentMap &AnalysisDeclContext::getParentMap() {
199   if (!PM) {
200     PM.reset(new ParentMap(getBody()));
201     if (const CXXConstructorDecl *C = dyn_cast<CXXConstructorDecl>(getDecl())) {
202       for (CXXConstructorDecl::init_const_iterator I = C->init_begin(),
203                                                    E = C->init_end();
204            I != E; ++I) {
205         PM->addStmt((*I)->getInit());
206       }
207     }
208   }
209   return *PM;
210 }
211 
212 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() {
213   if (!PCA)
214     PCA.reset(new PseudoConstantAnalysis(getBody()));
215   return PCA.get();
216 }
217 
218 AnalysisDeclContext *AnalysisDeclContextManager::getContext(const Decl *D) {
219   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
220     // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
221     // that has the body.
222     FD->hasBody(FD);
223     D = FD;
224   }
225 
226   AnalysisDeclContext *&AC = Contexts[D];
227   if (!AC)
228     AC = new AnalysisDeclContext(this, D, cfgBuildOptions);
229   return AC;
230 }
231 
232 const StackFrameContext *
233 AnalysisDeclContext::getStackFrame(LocationContext const *Parent, const Stmt *S,
234                                const CFGBlock *Blk, unsigned Idx) {
235   return getLocationContextManager().getStackFrame(this, Parent, S, Blk, Idx);
236 }
237 
238 const BlockInvocationContext *
239 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent,
240                                                const clang::BlockDecl *BD,
241                                                const void *ContextData) {
242   return getLocationContextManager().getBlockInvocationContext(this, parent,
243                                                                BD, ContextData);
244 }
245 
246 LocationContextManager & AnalysisDeclContext::getLocationContextManager() {
247   assert(Manager &&
248          "Cannot create LocationContexts without an AnalysisDeclContextManager!");
249   return Manager->getLocationContextManager();
250 }
251 
252 //===----------------------------------------------------------------------===//
253 // FoldingSet profiling.
254 //===----------------------------------------------------------------------===//
255 
256 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID,
257                                     ContextKind ck,
258                                     AnalysisDeclContext *ctx,
259                                     const LocationContext *parent,
260                                     const void *data) {
261   ID.AddInteger(ck);
262   ID.AddPointer(ctx);
263   ID.AddPointer(parent);
264   ID.AddPointer(data);
265 }
266 
267 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) {
268   Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index);
269 }
270 
271 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) {
272   Profile(ID, getAnalysisDeclContext(), getParent(), Enter);
273 }
274 
275 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) {
276   Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData);
277 }
278 
279 //===----------------------------------------------------------------------===//
280 // LocationContext creation.
281 //===----------------------------------------------------------------------===//
282 
283 template <typename LOC, typename DATA>
284 const LOC*
285 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx,
286                                            const LocationContext *parent,
287                                            const DATA *d) {
288   llvm::FoldingSetNodeID ID;
289   LOC::Profile(ID, ctx, parent, d);
290   void *InsertPos;
291 
292   LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
293 
294   if (!L) {
295     L = new LOC(ctx, parent, d);
296     Contexts.InsertNode(L, InsertPos);
297   }
298   return L;
299 }
300 
301 const StackFrameContext*
302 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx,
303                                       const LocationContext *parent,
304                                       const Stmt *s,
305                                       const CFGBlock *blk, unsigned idx) {
306   llvm::FoldingSetNodeID ID;
307   StackFrameContext::Profile(ID, ctx, parent, s, blk, idx);
308   void *InsertPos;
309   StackFrameContext *L =
310    cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos));
311   if (!L) {
312     L = new StackFrameContext(ctx, parent, s, blk, idx);
313     Contexts.InsertNode(L, InsertPos);
314   }
315   return L;
316 }
317 
318 const ScopeContext *
319 LocationContextManager::getScope(AnalysisDeclContext *ctx,
320                                  const LocationContext *parent,
321                                  const Stmt *s) {
322   return getLocationContext<ScopeContext, Stmt>(ctx, parent, s);
323 }
324 
325 const BlockInvocationContext *
326 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx,
327                                                   const LocationContext *parent,
328                                                   const BlockDecl *BD,
329                                                   const void *ContextData) {
330   llvm::FoldingSetNodeID ID;
331   BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData);
332   void *InsertPos;
333   BlockInvocationContext *L =
334     cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID,
335                                                                     InsertPos));
336   if (!L) {
337     L = new BlockInvocationContext(ctx, parent, BD, ContextData);
338     Contexts.InsertNode(L, InsertPos);
339   }
340   return L;
341 }
342 
343 //===----------------------------------------------------------------------===//
344 // LocationContext methods.
345 //===----------------------------------------------------------------------===//
346 
347 const StackFrameContext *LocationContext::getCurrentStackFrame() const {
348   const LocationContext *LC = this;
349   while (LC) {
350     if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC))
351       return SFC;
352     LC = LC->getParent();
353   }
354   return NULL;
355 }
356 
357 bool LocationContext::inTopFrame() const {
358   return getCurrentStackFrame()->inTopFrame();
359 }
360 
361 bool LocationContext::isParentOf(const LocationContext *LC) const {
362   do {
363     const LocationContext *Parent = LC->getParent();
364     if (Parent == this)
365       return true;
366     else
367       LC = Parent;
368   } while (LC);
369 
370   return false;
371 }
372 
373 //===----------------------------------------------------------------------===//
374 // Lazily generated map to query the external variables referenced by a Block.
375 //===----------------------------------------------------------------------===//
376 
377 namespace {
378 class FindBlockDeclRefExprsVals : public StmtVisitor<FindBlockDeclRefExprsVals>{
379   BumpVector<const VarDecl*> &BEVals;
380   BumpVectorContext &BC;
381   llvm::SmallPtrSet<const VarDecl*, 4> Visited;
382   llvm::SmallPtrSet<const DeclContext*, 4> IgnoredContexts;
383 public:
384   FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals,
385                             BumpVectorContext &bc)
386   : BEVals(bevals), BC(bc) {}
387 
388   bool IsTrackedDecl(const VarDecl *VD) {
389     const DeclContext *DC = VD->getDeclContext();
390     return IgnoredContexts.count(DC) == 0;
391   }
392 
393   void VisitStmt(Stmt *S) {
394     for (Stmt::child_range I = S->children(); I; ++I)
395       if (Stmt *child = *I)
396         Visit(child);
397   }
398 
399   void VisitDeclRefExpr(DeclRefExpr *DR) {
400     // Non-local variables are also directly modified.
401     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
402       if (!VD->hasLocalStorage()) {
403         if (Visited.insert(VD))
404           BEVals.push_back(VD, BC);
405       }
406     }
407   }
408 
409   void VisitBlockExpr(BlockExpr *BR) {
410     // Blocks containing blocks can transitively capture more variables.
411     IgnoredContexts.insert(BR->getBlockDecl());
412     Visit(BR->getBlockDecl()->getBody());
413   }
414 
415   void VisitPseudoObjectExpr(PseudoObjectExpr *PE) {
416     for (PseudoObjectExpr::semantics_iterator it = PE->semantics_begin(),
417          et = PE->semantics_end(); it != et; ++it) {
418       Expr *Semantic = *it;
419       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Semantic))
420         Semantic = OVE->getSourceExpr();
421       Visit(Semantic);
422     }
423   }
424 };
425 } // end anonymous namespace
426 
427 typedef BumpVector<const VarDecl*> DeclVec;
428 
429 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD,
430                                               void *&Vec,
431                                               llvm::BumpPtrAllocator &A) {
432   if (Vec)
433     return (DeclVec*) Vec;
434 
435   BumpVectorContext BC(A);
436   DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>();
437   new (BV) DeclVec(BC, 10);
438 
439   // Go through the capture list.
440   for (BlockDecl::capture_const_iterator CI = BD->capture_begin(),
441        CE = BD->capture_end(); CI != CE; ++CI) {
442     BV->push_back(CI->getVariable(), BC);
443   }
444 
445   // Find the referenced global/static variables.
446   FindBlockDeclRefExprsVals F(*BV, BC);
447   F.Visit(BD->getBody());
448 
449   Vec = BV;
450   return BV;
451 }
452 
453 std::pair<AnalysisDeclContext::referenced_decls_iterator,
454           AnalysisDeclContext::referenced_decls_iterator>
455 AnalysisDeclContext::getReferencedBlockVars(const BlockDecl *BD) {
456   if (!ReferencedBlockVars)
457     ReferencedBlockVars = new llvm::DenseMap<const BlockDecl*,void*>();
458 
459   DeclVec *V = LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A);
460   return std::make_pair(V->begin(), V->end());
461 }
462 
463 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) {
464   if (!ManagedAnalyses)
465     ManagedAnalyses = new ManagedAnalysisMap();
466   ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
467   return (*M)[tag];
468 }
469 
470 //===----------------------------------------------------------------------===//
471 // Cleanup.
472 //===----------------------------------------------------------------------===//
473 
474 ManagedAnalysis::~ManagedAnalysis() {}
475 
476 AnalysisDeclContext::~AnalysisDeclContext() {
477   delete forcedBlkExprs;
478   delete ReferencedBlockVars;
479   // Release the managed analyses.
480   if (ManagedAnalyses) {
481     ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses;
482     for (ManagedAnalysisMap::iterator I = M->begin(), E = M->end(); I!=E; ++I)
483       delete I->second;
484     delete M;
485   }
486 }
487 
488 AnalysisDeclContextManager::~AnalysisDeclContextManager() {
489   for (ContextMap::iterator I = Contexts.begin(), E = Contexts.end(); I!=E; ++I)
490     delete I->second;
491 }
492 
493 LocationContext::~LocationContext() {}
494 
495 LocationContextManager::~LocationContextManager() {
496   clear();
497 }
498 
499 void LocationContextManager::clear() {
500   for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(),
501        E = Contexts.end(); I != E; ) {
502     LocationContext *LC = &*I;
503     ++I;
504     delete LC;
505   }
506 
507   Contexts.clear();
508 }
509 
510