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