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 addLifetime, 71 bool synthesizeBodies, 72 bool addStaticInitBranch, 73 bool addCXXNewAllocator, 74 CodeInjector *injector) 75 : Injector(injector), SynthesizeBodies(synthesizeBodies) 76 { 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; 84 } 85 86 void AnalysisDeclContextManager::clear() { Contexts.clear(); } 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 (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; 105 } 106 } 107 return Body; 108 } 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; 117 } 118 } 119 return Body; 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(); 125 126 llvm_unreachable("unknown code decl"); 127 } 128 129 Stmt *AnalysisDeclContext::getBody() const { 130 bool Tmp; 131 return getBody(Tmp); 132 } 133 134 bool AnalysisDeclContext::isBodyAutosynthesized() const { 135 bool Tmp; 136 getBody(Tmp); 137 return Tmp; 138 } 139 140 bool AnalysisDeclContext::isBodyAutosynthesizedFromModelFile() const { 141 bool Tmp; 142 Stmt *Body = getBody(Tmp); 143 return Tmp && Body->getLocStart().isValid(); 144 } 145 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"; 149 } 150 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(); 158 if (isSelfDecl(VD)) 159 return dyn_cast<ImplicitParamDecl>(VD); 160 } 161 } 162 163 auto *CXXMethod = dyn_cast<CXXMethodDecl>(D); 164 if (!CXXMethod) 165 return nullptr; 166 167 const CXXRecordDecl *parent = CXXMethod->getParent(); 168 if (!parent->isLambda()) 169 return nullptr; 170 171 for (const LambdaCapture &LC : parent->captures()) { 172 if (!LC.capturesVariable()) 173 continue; 174 175 VarDecl *VD = LC.getCapturedVar(); 176 if (isSelfDecl(VD)) 177 return dyn_cast<ImplicitParamDecl>(VD); 178 } 179 180 return nullptr; 181 } 182 183 void AnalysisDeclContext::registerForcedBlockExpression(const Stmt *stmt) { 184 if (!forcedBlkExprs) 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]; 190 } 191 192 const CFGBlock * 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()); 200 return itr->second; 201 } 202 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) { 206 if (!TheCFG) 207 return; 208 209 for (CFG::synthetic_stmt_iterator I = TheCFG->synthetic_stmt_begin(), 210 E = TheCFG->synthetic_stmt_end(); 211 I != E; ++I) { 212 PM.setParent(I->first, PM.getParent(I->second)); 213 } 214 } 215 216 CFG *AnalysisDeclContext::getCFG() { 217 if (!cfgBuildOptions.PruneTriviallyFalseEdges) 218 return getUnoptimizedCFG(); 219 220 if (!builtCFG) { 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. 224 builtCFG = true; 225 226 if (PM) 227 addParentsForSyntheticStmts(cfg.get(), *PM); 228 229 // The Observer should only observe one build of the CFG. 230 getCFGBuildOptions().Observer = nullptr; 231 } 232 return cfg.get(); 233 } 234 235 CFG *AnalysisDeclContext::getUnoptimizedCFG() { 236 if (!builtCompleteCFG) { 237 SaveAndRestore<bool> NotPrune(cfgBuildOptions.PruneTriviallyFalseEdges, 238 false); 239 completeCFG = 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; 244 245 if (PM) 246 addParentsForSyntheticStmts(completeCFG.get(), *PM); 247 248 // The Observer should only observe one build of the CFG. 249 getCFGBuildOptions().Observer = nullptr; 250 } 251 return completeCFG.get(); 252 } 253 254 CFGStmtMap *AnalysisDeclContext::getCFGStmtMap() { 255 if (cfgStmtMap) 256 return cfgStmtMap.get(); 257 258 if (CFG *c = getCFG()) { 259 cfgStmtMap.reset(CFGStmtMap::Build(c, &getParentMap())); 260 return cfgStmtMap.get(); 261 } 262 263 return nullptr; 264 } 265 266 CFGReverseBlockReachabilityAnalysis *AnalysisDeclContext::getCFGReachablityAnalysis() { 267 if (CFA) 268 return CFA.get(); 269 270 if (CFG *c = getCFG()) { 271 CFA.reset(new CFGReverseBlockReachabilityAnalysis(*c)); 272 return CFA.get(); 273 } 274 275 return nullptr; 276 } 277 278 void AnalysisDeclContext::dumpCFG(bool ShowColors) { 279 getCFG()->dump(getASTContext().getLangOpts(), ShowColors); 280 } 281 282 ParentMap &AnalysisDeclContext::getParentMap() { 283 if (!PM) { 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()); 288 } 289 } 290 if (builtCFG) 291 addParentsForSyntheticStmts(getCFG(), *PM); 292 if (builtCompleteCFG) 293 addParentsForSyntheticStmts(getUnoptimizedCFG(), *PM); 294 } 295 return *PM; 296 } 297 298 PseudoConstantAnalysis *AnalysisDeclContext::getPseudoConstantAnalysis() { 299 if (!PCA) 300 PCA.reset(new PseudoConstantAnalysis(getBody())); 301 return PCA.get(); 302 } 303 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. 308 FD->hasBody(FD); 309 D = FD; 310 } 311 312 std::unique_ptr<AnalysisDeclContext> &AC = Contexts[D]; 313 if (!AC) 314 AC = llvm::make_unique<AnalysisDeclContext>(this, D, cfgBuildOptions); 315 return AC.get(); 316 } 317 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); 322 } 323 324 const BlockInvocationContext * 325 AnalysisDeclContext::getBlockInvocationContext(const LocationContext *parent, 326 const clang::BlockDecl *BD, 327 const void *ContextData) { 328 return getLocationContextManager().getBlockInvocationContext(this, parent, 329 BD, ContextData); 330 } 331 332 bool AnalysisDeclContext::isInStdNamespace(const Decl *D) { 333 const DeclContext *DC = D->getDeclContext()->getEnclosingNamespaceContext(); 334 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); 335 if (!ND) 336 return false; 337 338 while (const DeclContext *Parent = ND->getParent()) { 339 if (!isa<NamespaceDecl>(Parent)) 340 break; 341 ND = cast<NamespaceDecl>(Parent); 342 } 343 344 return ND->isStdNamespace(); 345 } 346 347 LocationContextManager & AnalysisDeclContext::getLocationContextManager() { 348 assert(Manager && 349 "Cannot create LocationContexts without an AnalysisDeclContextManager!"); 350 return Manager->getLocationContextManager(); 351 } 352 353 //===----------------------------------------------------------------------===// 354 // FoldingSet profiling. 355 //===----------------------------------------------------------------------===// 356 357 void LocationContext::ProfileCommon(llvm::FoldingSetNodeID &ID, 358 ContextKind ck, 359 AnalysisDeclContext *ctx, 360 const LocationContext *parent, 361 const void *data) { 362 ID.AddInteger(ck); 363 ID.AddPointer(ctx); 364 ID.AddPointer(parent); 365 ID.AddPointer(data); 366 } 367 368 void StackFrameContext::Profile(llvm::FoldingSetNodeID &ID) { 369 Profile(ID, getAnalysisDeclContext(), getParent(), CallSite, Block, Index); 370 } 371 372 void ScopeContext::Profile(llvm::FoldingSetNodeID &ID) { 373 Profile(ID, getAnalysisDeclContext(), getParent(), Enter); 374 } 375 376 void BlockInvocationContext::Profile(llvm::FoldingSetNodeID &ID) { 377 Profile(ID, getAnalysisDeclContext(), getParent(), BD, ContextData); 378 } 379 380 //===----------------------------------------------------------------------===// 381 // LocationContext creation. 382 //===----------------------------------------------------------------------===// 383 384 template <typename LOC, typename DATA> 385 const LOC* 386 LocationContextManager::getLocationContext(AnalysisDeclContext *ctx, 387 const LocationContext *parent, 388 const DATA *d) { 389 llvm::FoldingSetNodeID ID; 390 LOC::Profile(ID, ctx, parent, d); 391 void *InsertPos; 392 393 LOC *L = cast_or_null<LOC>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); 394 395 if (!L) { 396 L = new LOC(ctx, parent, d); 397 Contexts.InsertNode(L, InsertPos); 398 } 399 return L; 400 } 401 402 const StackFrameContext* 403 LocationContextManager::getStackFrame(AnalysisDeclContext *ctx, 404 const LocationContext *parent, 405 const Stmt *s, 406 const CFGBlock *blk, unsigned idx) { 407 llvm::FoldingSetNodeID ID; 408 StackFrameContext::Profile(ID, ctx, parent, s, blk, idx); 409 void *InsertPos; 410 StackFrameContext *L = 411 cast_or_null<StackFrameContext>(Contexts.FindNodeOrInsertPos(ID, InsertPos)); 412 if (!L) { 413 L = new StackFrameContext(ctx, parent, s, blk, idx); 414 Contexts.InsertNode(L, InsertPos); 415 } 416 return L; 417 } 418 419 const ScopeContext * 420 LocationContextManager::getScope(AnalysisDeclContext *ctx, 421 const LocationContext *parent, 422 const Stmt *s) { 423 return getLocationContext<ScopeContext, Stmt>(ctx, parent, s); 424 } 425 426 const BlockInvocationContext * 427 LocationContextManager::getBlockInvocationContext(AnalysisDeclContext *ctx, 428 const LocationContext *parent, 429 const BlockDecl *BD, 430 const void *ContextData) { 431 llvm::FoldingSetNodeID ID; 432 BlockInvocationContext::Profile(ID, ctx, parent, BD, ContextData); 433 void *InsertPos; 434 BlockInvocationContext *L = 435 cast_or_null<BlockInvocationContext>(Contexts.FindNodeOrInsertPos(ID, 436 InsertPos)); 437 if (!L) { 438 L = new BlockInvocationContext(ctx, parent, BD, ContextData); 439 Contexts.InsertNode(L, InsertPos); 440 } 441 return L; 442 } 443 444 //===----------------------------------------------------------------------===// 445 // LocationContext methods. 446 //===----------------------------------------------------------------------===// 447 448 const StackFrameContext *LocationContext::getCurrentStackFrame() const { 449 const LocationContext *LC = this; 450 while (LC) { 451 if (const StackFrameContext *SFC = dyn_cast<StackFrameContext>(LC)) 452 return SFC; 453 LC = LC->getParent(); 454 } 455 return nullptr; 456 } 457 458 bool LocationContext::inTopFrame() const { 459 return getCurrentStackFrame()->inTopFrame(); 460 } 461 462 bool LocationContext::isParentOf(const LocationContext *LC) const { 463 do { 464 const LocationContext *Parent = LC->getParent(); 465 if (Parent == this) 466 return true; 467 else 468 LC = Parent; 469 } while (LC); 470 471 return false; 472 } 473 474 void LocationContext::dumpStack(raw_ostream &OS, StringRef Indent) const { 475 ASTContext &Ctx = getAnalysisDeclContext()->getASTContext(); 476 PrintingPolicy PP(Ctx.getLangOpts()); 477 PP.TerseOutput = 1; 478 479 unsigned Frame = 0; 480 for (const LocationContext *LCtx = this; LCtx; LCtx = LCtx->getParent()) { 481 switch (LCtx->getKind()) { 482 case StackFrame: 483 OS << Indent << '#' << Frame++ << ' '; 484 cast<StackFrameContext>(LCtx)->getDecl()->print(OS, PP); 485 OS << '\n'; 486 break; 487 case Scope: 488 OS << Indent << " (scope)\n"; 489 break; 490 case Block: 491 OS << Indent << " (block context: " 492 << cast<BlockInvocationContext>(LCtx)->getContextData() 493 << ")\n"; 494 break; 495 } 496 } 497 } 498 499 LLVM_DUMP_METHOD void LocationContext::dumpStack() const { 500 dumpStack(llvm::errs()); 501 } 502 503 //===----------------------------------------------------------------------===// 504 // Lazily generated map to query the external variables referenced by a Block. 505 //===----------------------------------------------------------------------===// 506 507 namespace { 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; 513 public: 514 FindBlockDeclRefExprsVals(BumpVector<const VarDecl*> &bevals, 515 BumpVectorContext &bc) 516 : BEVals(bevals), BC(bc) {} 517 518 void VisitStmt(Stmt *S) { 519 for (Stmt *Child : S->children()) 520 if (Child) 521 Visit(Child); 522 } 523 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); 530 } 531 } 532 } 533 534 void VisitBlockExpr(BlockExpr *BR) { 535 // Blocks containing blocks can transitively capture more variables. 536 IgnoredContexts.insert(BR->getBlockDecl()); 537 Visit(BR->getBlockDecl()->getBody()); 538 } 539 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(); 546 Visit(Semantic); 547 } 548 } 549 }; 550 } // end anonymous namespace 551 552 typedef BumpVector<const VarDecl*> DeclVec; 553 554 static DeclVec* LazyInitializeReferencedDecls(const BlockDecl *BD, 555 void *&Vec, 556 llvm::BumpPtrAllocator &A) { 557 if (Vec) 558 return (DeclVec*) Vec; 559 560 BumpVectorContext BC(A); 561 DeclVec *BV = (DeclVec*) A.Allocate<DeclVec>(); 562 new (BV) DeclVec(BC, 10); 563 564 // Go through the capture list. 565 for (const auto &CI : BD->captures()) { 566 BV->push_back(CI.getVariable(), BC); 567 } 568 569 // Find the referenced global/static variables. 570 FindBlockDeclRefExprsVals F(*BV, BC); 571 F.Visit(BD->getBody()); 572 573 Vec = BV; 574 return BV; 575 } 576 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*>(); 581 582 const DeclVec *V = 583 LazyInitializeReferencedDecls(BD, (*ReferencedBlockVars)[BD], A); 584 return llvm::make_range(V->begin(), V->end()); 585 } 586 587 ManagedAnalysis *&AnalysisDeclContext::getAnalysisImpl(const void *tag) { 588 if (!ManagedAnalyses) 589 ManagedAnalyses = new ManagedAnalysisMap(); 590 ManagedAnalysisMap *M = (ManagedAnalysisMap*) ManagedAnalyses; 591 return (*M)[tag]; 592 } 593 594 //===----------------------------------------------------------------------===// 595 // Cleanup. 596 //===----------------------------------------------------------------------===// 597 598 ManagedAnalysis::~ManagedAnalysis() {} 599 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); 607 delete M; 608 } 609 } 610 611 AnalysisDeclContextManager::~AnalysisDeclContextManager() {} 612 613 LocationContext::~LocationContext() {} 614 615 LocationContextManager::~LocationContextManager() { 616 clear(); 617 } 618 619 void LocationContextManager::clear() { 620 for (llvm::FoldingSet<LocationContext>::iterator I = Contexts.begin(), 621 E = Contexts.end(); I != E; ) { 622 LocationContext *LC = &*I; 623 ++I; 624 delete LC; 625 } 626 627 Contexts.clear(); 628 } 629 630