1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // "Meta" ASTConsumer for running different source analyses. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h" 14 #include "ModelInjector.h" 15 #include "clang/AST/Decl.h" 16 #include "clang/AST/DeclCXX.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/RecursiveASTVisitor.h" 19 #include "clang/Analysis/Analyses/LiveVariables.h" 20 #include "clang/Analysis/CFG.h" 21 #include "clang/Analysis/CallGraph.h" 22 #include "clang/Analysis/CodeInjector.h" 23 #include "clang/Analysis/MacroExpansionContext.h" 24 #include "clang/Analysis/PathDiagnostic.h" 25 #include "clang/Basic/SourceManager.h" 26 #include "clang/CrossTU/CrossTranslationUnit.h" 27 #include "clang/Frontend/CompilerInstance.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Rewrite/Core/Rewriter.h" 30 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h" 31 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" 32 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" 33 #include "clang/StaticAnalyzer/Core/CheckerManager.h" 34 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" 35 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h" 36 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h" 37 #include "llvm/ADT/PostOrderIterator.h" 38 #include "llvm/ADT/Statistic.h" 39 #include "llvm/Support/FileSystem.h" 40 #include "llvm/Support/Path.h" 41 #include "llvm/Support/Program.h" 42 #include "llvm/Support/Timer.h" 43 #include "llvm/Support/raw_ostream.h" 44 #include <memory> 45 #include <queue> 46 #include <utility> 47 48 using namespace clang; 49 using namespace ento; 50 51 #define DEBUG_TYPE "AnalysisConsumer" 52 53 STATISTIC(NumFunctionTopLevel, "The # of functions at top level."); 54 STATISTIC(NumFunctionsAnalyzed, 55 "The # of functions and blocks analyzed (as top level " 56 "with inlining turned on)."); 57 STATISTIC(NumBlocksInAnalyzedFunctions, 58 "The # of basic blocks in the analyzed functions."); 59 STATISTIC(NumVisitedBlocksInAnalyzedFunctions, 60 "The # of visited basic blocks in the analyzed functions."); 61 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks."); 62 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function."); 63 64 //===----------------------------------------------------------------------===// 65 // AnalysisConsumer declaration. 66 //===----------------------------------------------------------------------===// 67 68 namespace { 69 70 class AnalysisConsumer : public AnalysisASTConsumer, 71 public RecursiveASTVisitor<AnalysisConsumer> { 72 enum { 73 AM_None = 0, 74 AM_Syntax = 0x1, 75 AM_Path = 0x2 76 }; 77 typedef unsigned AnalysisMode; 78 79 /// Mode of the analyzes while recursively visiting Decls. 80 AnalysisMode RecVisitorMode; 81 /// Bug Reporter to use while recursively visiting Decls. 82 BugReporter *RecVisitorBR; 83 84 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns; 85 86 public: 87 ASTContext *Ctx; 88 Preprocessor &PP; 89 const std::string OutDir; 90 AnalyzerOptionsRef Opts; 91 ArrayRef<std::string> Plugins; 92 CodeInjector *Injector; 93 cross_tu::CrossTranslationUnitContext CTU; 94 95 /// Stores the declarations from the local translation unit. 96 /// Note, we pre-compute the local declarations at parse time as an 97 /// optimization to make sure we do not deserialize everything from disk. 98 /// The local declaration to all declarations ratio might be very small when 99 /// working with a PCH file. 100 SetOfDecls LocalTUDecls; 101 102 MacroExpansionContext MacroExpansions; 103 104 // Set of PathDiagnosticConsumers. Owned by AnalysisManager. 105 PathDiagnosticConsumers PathConsumers; 106 107 StoreManagerCreator CreateStoreMgr; 108 ConstraintManagerCreator CreateConstraintMgr; 109 110 std::unique_ptr<CheckerManager> checkerMgr; 111 std::unique_ptr<AnalysisManager> Mgr; 112 113 /// Time the analyzes time of each translation unit. 114 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers; 115 std::unique_ptr<llvm::Timer> SyntaxCheckTimer; 116 std::unique_ptr<llvm::Timer> ExprEngineTimer; 117 std::unique_ptr<llvm::Timer> BugReporterTimer; 118 119 /// The information about analyzed functions shared throughout the 120 /// translation unit. 121 FunctionSummariesTy FunctionSummaries; 122 123 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir, 124 AnalyzerOptionsRef opts, ArrayRef<std::string> plugins, 125 CodeInjector *injector) 126 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr), 127 PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)), 128 Plugins(plugins), Injector(injector), CTU(CI), 129 MacroExpansions(CI.getLangOpts()) { 130 DigestAnalyzerOptions(); 131 if (Opts->AnalyzerDisplayProgress || Opts->PrintStats || 132 Opts->ShouldSerializeStats) { 133 AnalyzerTimers = std::make_unique<llvm::TimerGroup>( 134 "analyzer", "Analyzer timers"); 135 SyntaxCheckTimer = std::make_unique<llvm::Timer>( 136 "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers); 137 ExprEngineTimer = std::make_unique<llvm::Timer>( 138 "exprengine", "Path exploration time", *AnalyzerTimers); 139 BugReporterTimer = std::make_unique<llvm::Timer>( 140 "bugreporter", "Path-sensitive report post-processing time", 141 *AnalyzerTimers); 142 } 143 144 if (Opts->PrintStats || Opts->ShouldSerializeStats) { 145 llvm::EnableStatistics(/* PrintOnExit= */ false); 146 } 147 148 if (Opts->ShouldDisplayMacroExpansions) 149 MacroExpansions.registerForPreprocessor(PP); 150 } 151 152 ~AnalysisConsumer() override { 153 if (Opts->PrintStats) { 154 llvm::PrintStatistics(); 155 } 156 } 157 158 void DigestAnalyzerOptions() { 159 switch (Opts->AnalysisDiagOpt) { 160 case PD_NONE: 161 break; 162 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \ 163 case PD_##NAME: \ 164 CREATEFN(Opts->getDiagOpts(), PathConsumers, OutDir, PP, CTU, \ 165 MacroExpansions); \ 166 break; 167 #include "clang/StaticAnalyzer/Core/Analyses.def" 168 default: 169 llvm_unreachable("Unknown analyzer output type!"); 170 } 171 172 // Create the analyzer component creators. 173 switch (Opts->AnalysisStoreOpt) { 174 default: 175 llvm_unreachable("Unknown store manager."); 176 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \ 177 case NAME##Model: CreateStoreMgr = CREATEFN; break; 178 #include "clang/StaticAnalyzer/Core/Analyses.def" 179 } 180 181 switch (Opts->AnalysisConstraintsOpt) { 182 default: 183 llvm_unreachable("Unknown constraint manager."); 184 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \ 185 case NAME##Model: CreateConstraintMgr = CREATEFN; break; 186 #include "clang/StaticAnalyzer/Core/Analyses.def" 187 } 188 } 189 190 void DisplayTime(llvm::TimeRecord &Time) { 191 if (!Opts->AnalyzerDisplayProgress) { 192 return; 193 } 194 llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000) 195 << " ms\n"; 196 } 197 198 void DisplayFunction(const Decl *D, AnalysisMode Mode, 199 ExprEngine::InliningModes IMode) { 200 if (!Opts->AnalyzerDisplayProgress) 201 return; 202 203 SourceManager &SM = Mgr->getASTContext().getSourceManager(); 204 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation()); 205 if (Loc.isValid()) { 206 llvm::errs() << "ANALYZE"; 207 208 if (Mode == AM_Syntax) 209 llvm::errs() << " (Syntax)"; 210 else if (Mode == AM_Path) { 211 llvm::errs() << " (Path, "; 212 switch (IMode) { 213 case ExprEngine::Inline_Minimal: 214 llvm::errs() << " Inline_Minimal"; 215 break; 216 case ExprEngine::Inline_Regular: 217 llvm::errs() << " Inline_Regular"; 218 break; 219 } 220 llvm::errs() << ")"; 221 } else 222 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!"); 223 224 llvm::errs() << ": " << Loc.getFilename() << ' ' 225 << AnalysisDeclContext::getFunctionName(D); 226 } 227 } 228 229 void Initialize(ASTContext &Context) override { 230 Ctx = &Context; 231 checkerMgr = std::make_unique<CheckerManager>(*Ctx, *Opts, PP, Plugins, 232 CheckerRegistrationFns); 233 234 Mgr = std::make_unique<AnalysisManager>(*Ctx, PP, PathConsumers, 235 CreateStoreMgr, CreateConstraintMgr, 236 checkerMgr.get(), *Opts, Injector); 237 } 238 239 /// Store the top level decls in the set to be processed later on. 240 /// (Doing this pre-processing avoids deserialization of data from PCH.) 241 bool HandleTopLevelDecl(DeclGroupRef D) override; 242 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override; 243 244 void HandleTranslationUnit(ASTContext &C) override; 245 246 /// Determine which inlining mode should be used when this function is 247 /// analyzed. This allows to redefine the default inlining policies when 248 /// analyzing a given function. 249 ExprEngine::InliningModes 250 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited); 251 252 /// Build the call graph for all the top level decls of this TU and 253 /// use it to define the order in which the functions should be visited. 254 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize); 255 256 /// Run analyzes(syntax or path sensitive) on the given function. 257 /// \param Mode - determines if we are requesting syntax only or path 258 /// sensitive only analysis. 259 /// \param VisitedCallees - The output parameter, which is populated with the 260 /// set of functions which should be considered analyzed after analyzing the 261 /// given root function. 262 void HandleCode(Decl *D, AnalysisMode Mode, 263 ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal, 264 SetOfConstDecls *VisitedCallees = nullptr); 265 266 void RunPathSensitiveChecks(Decl *D, 267 ExprEngine::InliningModes IMode, 268 SetOfConstDecls *VisitedCallees); 269 270 /// Visitors for the RecursiveASTVisitor. 271 bool shouldWalkTypesOfTypeLocs() const { return false; } 272 273 /// Handle callbacks for arbitrary Decls. 274 bool VisitDecl(Decl *D) { 275 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode); 276 if (Mode & AM_Syntax) { 277 if (SyntaxCheckTimer) 278 SyntaxCheckTimer->startTimer(); 279 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR); 280 if (SyntaxCheckTimer) 281 SyntaxCheckTimer->stopTimer(); 282 } 283 return true; 284 } 285 286 bool VisitVarDecl(VarDecl *VD) { 287 if (!Opts->IsNaiveCTUEnabled) 288 return true; 289 290 if (VD->hasExternalStorage() || VD->isStaticDataMember()) { 291 if (!cross_tu::containsConst(VD, *Ctx)) 292 return true; 293 } else { 294 // Cannot be initialized in another TU. 295 return true; 296 } 297 298 if (VD->getAnyInitializer()) 299 return true; 300 301 llvm::Expected<const VarDecl *> CTUDeclOrError = 302 CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName, 303 Opts->DisplayCTUProgress); 304 305 if (!CTUDeclOrError) { 306 handleAllErrors(CTUDeclOrError.takeError(), 307 [&](const cross_tu::IndexError &IE) { 308 CTU.emitCrossTUDiagnostics(IE); 309 }); 310 } 311 312 return true; 313 } 314 315 bool VisitFunctionDecl(FunctionDecl *FD) { 316 IdentifierInfo *II = FD->getIdentifier(); 317 if (II && II->getName().startswith("__inline")) 318 return true; 319 320 // We skip function template definitions, as their semantics is 321 // only determined when they are instantiated. 322 if (FD->isThisDeclarationADefinition() && 323 !FD->isDependentContext()) { 324 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 325 HandleCode(FD, RecVisitorMode); 326 } 327 return true; 328 } 329 330 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) { 331 if (MD->isThisDeclarationADefinition()) { 332 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 333 HandleCode(MD, RecVisitorMode); 334 } 335 return true; 336 } 337 338 bool VisitBlockDecl(BlockDecl *BD) { 339 if (BD->hasBody()) { 340 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false); 341 // Since we skip function template definitions, we should skip blocks 342 // declared in those functions as well. 343 if (!BD->isDependentContext()) { 344 HandleCode(BD, RecVisitorMode); 345 } 346 } 347 return true; 348 } 349 350 void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override { 351 PathConsumers.push_back(Consumer); 352 } 353 354 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override { 355 CheckerRegistrationFns.push_back(std::move(Fn)); 356 } 357 358 private: 359 void storeTopLevelDecls(DeclGroupRef DG); 360 std::string getFunctionName(const Decl *D); 361 362 /// Check if we should skip (not analyze) the given function. 363 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode); 364 void runAnalysisOnTranslationUnit(ASTContext &C); 365 366 /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set. 367 void reportAnalyzerProgress(StringRef S); 368 }; // namespace 369 } // end anonymous namespace 370 371 372 //===----------------------------------------------------------------------===// 373 // AnalysisConsumer implementation. 374 //===----------------------------------------------------------------------===// 375 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) { 376 storeTopLevelDecls(DG); 377 return true; 378 } 379 380 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) { 381 storeTopLevelDecls(DG); 382 } 383 384 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) { 385 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { 386 387 // Skip ObjCMethodDecl, wait for the objc container to avoid 388 // analyzing twice. 389 if (isa<ObjCMethodDecl>(*I)) 390 continue; 391 392 LocalTUDecls.push_back(*I); 393 } 394 } 395 396 static bool shouldSkipFunction(const Decl *D, 397 const SetOfConstDecls &Visited, 398 const SetOfConstDecls &VisitedAsTopLevel) { 399 if (VisitedAsTopLevel.count(D)) 400 return true; 401 402 // Skip analysis of inheriting constructors as top-level functions. These 403 // constructors don't even have a body written down in the code, so even if 404 // we find a bug, we won't be able to display it. 405 if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 406 if (CD->isInheritingConstructor()) 407 return true; 408 409 // We want to re-analyse the functions as top level in the following cases: 410 // - The 'init' methods should be reanalyzed because 411 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns 412 // 'nil' and unless we analyze the 'init' functions as top level, we will 413 // not catch errors within defensive code. 414 // - We want to reanalyze all ObjC methods as top level to report Retain 415 // Count naming convention errors more aggressively. 416 if (isa<ObjCMethodDecl>(D)) 417 return false; 418 // We also want to reanalyze all C++ copy and move assignment operators to 419 // separately check the two cases where 'this' aliases with the parameter and 420 // where it may not. (cplusplus.SelfAssignmentChecker) 421 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 422 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) 423 return false; 424 } 425 426 // Otherwise, if we visited the function before, do not reanalyze it. 427 return Visited.count(D); 428 } 429 430 ExprEngine::InliningModes 431 AnalysisConsumer::getInliningModeForFunction(const Decl *D, 432 const SetOfConstDecls &Visited) { 433 // We want to reanalyze all ObjC methods as top level to report Retain 434 // Count naming convention errors more aggressively. But we should tune down 435 // inlining when reanalyzing an already inlined function. 436 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) { 437 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D); 438 if (ObjCM->getMethodFamily() != OMF_init) 439 return ExprEngine::Inline_Minimal; 440 } 441 442 return ExprEngine::Inline_Regular; 443 } 444 445 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) { 446 // Build the Call Graph by adding all the top level declarations to the graph. 447 // Note: CallGraph can trigger deserialization of more items from a pch 448 // (though HandleInterestingDecl); triggering additions to LocalTUDecls. 449 // We rely on random access to add the initially processed Decls to CG. 450 CallGraph CG; 451 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 452 CG.addToCallGraph(LocalTUDecls[i]); 453 } 454 455 // Walk over all of the call graph nodes in topological order, so that we 456 // analyze parents before the children. Skip the functions inlined into 457 // the previously processed functions. Use external Visited set to identify 458 // inlined functions. The topological order allows the "do not reanalyze 459 // previously inlined function" performance heuristic to be triggered more 460 // often. 461 SetOfConstDecls Visited; 462 SetOfConstDecls VisitedAsTopLevel; 463 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG); 464 for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator 465 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) { 466 NumFunctionTopLevel++; 467 468 CallGraphNode *N = *I; 469 Decl *D = N->getDecl(); 470 471 // Skip the abstract root node. 472 if (!D) 473 continue; 474 475 // Skip the functions which have been processed already or previously 476 // inlined. 477 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel)) 478 continue; 479 480 // Analyze the function. 481 SetOfConstDecls VisitedCallees; 482 483 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited), 484 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees)); 485 486 // Add the visited callees to the global visited set. 487 for (const Decl *Callee : VisitedCallees) 488 // Decls from CallGraph are already canonical. But Decls coming from 489 // CallExprs may be not. We should canonicalize them manually. 490 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee 491 : Callee->getCanonicalDecl()); 492 VisitedAsTopLevel.insert(D); 493 } 494 } 495 496 static bool isBisonFile(ASTContext &C) { 497 const SourceManager &SM = C.getSourceManager(); 498 FileID FID = SM.getMainFileID(); 499 StringRef Buffer = SM.getBufferOrFake(FID).getBuffer(); 500 if (Buffer.startswith("/* A Bison parser, made by")) 501 return true; 502 return false; 503 } 504 505 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) { 506 BugReporter BR(*Mgr); 507 TranslationUnitDecl *TU = C.getTranslationUnitDecl(); 508 if (SyntaxCheckTimer) 509 SyntaxCheckTimer->startTimer(); 510 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR); 511 if (SyntaxCheckTimer) 512 SyntaxCheckTimer->stopTimer(); 513 514 // Run the AST-only checks using the order in which functions are defined. 515 // If inlining is not turned on, use the simplest function order for path 516 // sensitive analyzes as well. 517 RecVisitorMode = AM_Syntax; 518 if (!Mgr->shouldInlineCall()) 519 RecVisitorMode |= AM_Path; 520 RecVisitorBR = &BR; 521 522 // Process all the top level declarations. 523 // 524 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more 525 // entries. Thus we don't use an iterator, but rely on LocalTUDecls 526 // random access. By doing so, we automatically compensate for iterators 527 // possibly being invalidated, although this is a bit slower. 528 const unsigned LocalTUDeclsSize = LocalTUDecls.size(); 529 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) { 530 TraverseDecl(LocalTUDecls[i]); 531 } 532 533 if (Mgr->shouldInlineCall()) 534 HandleDeclsCallGraph(LocalTUDeclsSize); 535 536 // After all decls handled, run checkers on the entire TranslationUnit. 537 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR); 538 539 BR.FlushReports(); 540 RecVisitorBR = nullptr; 541 } 542 543 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) { 544 if (Opts->AnalyzerDisplayProgress) 545 llvm::errs() << S; 546 } 547 548 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) { 549 550 // Don't run the actions if an error has occurred with parsing the file. 551 DiagnosticsEngine &Diags = PP.getDiagnostics(); 552 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) 553 return; 554 555 if (isBisonFile(C)) { 556 reportAnalyzerProgress("Skipping bison-generated file\n"); 557 } else if (Opts->DisableAllCheckers) { 558 559 // Don't analyze if the user explicitly asked for no checks to be performed 560 // on this file. 561 reportAnalyzerProgress("All checks are disabled using a supplied option\n"); 562 } else { 563 // Otherwise, just run the analysis. 564 runAnalysisOnTranslationUnit(C); 565 } 566 567 // Count how many basic blocks we have not covered. 568 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks(); 569 NumVisitedBlocksInAnalyzedFunctions = 570 FunctionSummaries.getTotalNumVisitedBasicBlocks(); 571 if (NumBlocksInAnalyzedFunctions > 0) 572 PercentReachableBlocks = 573 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) / 574 NumBlocksInAnalyzedFunctions; 575 576 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output. 577 // FIXME: This should be replaced with something that doesn't rely on 578 // side-effects in PathDiagnosticConsumer's destructor. This is required when 579 // used with option -disable-free. 580 Mgr.reset(); 581 } 582 583 AnalysisConsumer::AnalysisMode 584 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) { 585 if (!Opts->AnalyzeSpecificFunction.empty() && 586 AnalysisDeclContext::getFunctionName(D) != Opts->AnalyzeSpecificFunction) 587 return AM_None; 588 589 // Unless -analyze-all is specified, treat decls differently depending on 590 // where they came from: 591 // - Main source file: run both path-sensitive and non-path-sensitive checks. 592 // - Header files: run non-path-sensitive checks only. 593 // - System headers: don't run any checks. 594 if (Opts->AnalyzeAll) 595 return Mode; 596 597 const SourceManager &SM = Ctx->getSourceManager(); 598 599 const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation { 600 const Stmt *Body = D->getBody(); 601 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation(); 602 return SM.getExpansionLoc(SL); 603 }(D); 604 605 // Ignore system headers. 606 if (Loc.isInvalid() || SM.isInSystemHeader(Loc)) 607 return AM_None; 608 609 // Disable path sensitive analysis in user-headers. 610 if (!Mgr->isInCodeFile(Loc)) 611 return Mode & ~AM_Path; 612 613 return Mode; 614 } 615 616 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode, 617 ExprEngine::InliningModes IMode, 618 SetOfConstDecls *VisitedCallees) { 619 if (!D->hasBody()) 620 return; 621 Mode = getModeForDecl(D, Mode); 622 if (Mode == AM_None) 623 return; 624 625 // Clear the AnalysisManager of old AnalysisDeclContexts. 626 Mgr->ClearContexts(); 627 // Ignore autosynthesized code. 628 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized()) 629 return; 630 631 CFG *DeclCFG = Mgr->getCFG(D); 632 if (DeclCFG) 633 MaxCFGSize.updateMax(DeclCFG->size()); 634 635 DisplayFunction(D, Mode, IMode); 636 BugReporter BR(*Mgr); 637 638 if (Mode & AM_Syntax) { 639 llvm::TimeRecord CheckerStartTime; 640 if (SyntaxCheckTimer) { 641 CheckerStartTime = SyntaxCheckTimer->getTotalTime(); 642 SyntaxCheckTimer->startTimer(); 643 } 644 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR); 645 if (SyntaxCheckTimer) { 646 SyntaxCheckTimer->stopTimer(); 647 llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime(); 648 CheckerEndTime -= CheckerStartTime; 649 DisplayTime(CheckerEndTime); 650 } 651 } 652 653 BR.FlushReports(); 654 655 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) { 656 RunPathSensitiveChecks(D, IMode, VisitedCallees); 657 if (IMode != ExprEngine::Inline_Minimal) 658 NumFunctionsAnalyzed++; 659 } 660 } 661 662 //===----------------------------------------------------------------------===// 663 // Path-sensitive checking. 664 //===----------------------------------------------------------------------===// 665 666 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D, 667 ExprEngine::InliningModes IMode, 668 SetOfConstDecls *VisitedCallees) { 669 // Construct the analysis engine. First check if the CFG is valid. 670 // FIXME: Inter-procedural analysis will need to handle invalid CFGs. 671 if (!Mgr->getCFG(D)) 672 return; 673 674 // See if the LiveVariables analysis scales. 675 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>()) 676 return; 677 678 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode); 679 680 // Execute the worklist algorithm. 681 llvm::TimeRecord ExprEngineStartTime; 682 if (ExprEngineTimer) { 683 ExprEngineStartTime = ExprEngineTimer->getTotalTime(); 684 ExprEngineTimer->startTimer(); 685 } 686 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D), 687 Mgr->options.MaxNodesPerTopLevelFunction); 688 if (ExprEngineTimer) { 689 ExprEngineTimer->stopTimer(); 690 llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime(); 691 ExprEngineEndTime -= ExprEngineStartTime; 692 DisplayTime(ExprEngineEndTime); 693 } 694 695 if (!Mgr->options.DumpExplodedGraphTo.empty()) 696 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo); 697 698 // Visualize the exploded graph. 699 if (Mgr->options.visualizeExplodedGraphWithGraphViz) 700 Eng.ViewGraph(Mgr->options.TrimGraph); 701 702 // Display warnings. 703 if (BugReporterTimer) 704 BugReporterTimer->startTimer(); 705 Eng.getBugReporter().FlushReports(); 706 if (BugReporterTimer) 707 BugReporterTimer->stopTimer(); 708 } 709 710 //===----------------------------------------------------------------------===// 711 // AnalysisConsumer creation. 712 //===----------------------------------------------------------------------===// 713 714 std::unique_ptr<AnalysisASTConsumer> 715 ento::CreateAnalysisConsumer(CompilerInstance &CI) { 716 // Disable the effects of '-Werror' when using the AnalysisConsumer. 717 CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false); 718 719 AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts(); 720 bool hasModelPath = analyzerOpts->Config.count("model-path") > 0; 721 722 return std::make_unique<AnalysisConsumer>( 723 CI, CI.getFrontendOpts().OutputFile, analyzerOpts, 724 CI.getFrontendOpts().Plugins, 725 hasModelPath ? new ModelInjector(CI) : nullptr); 726 } 727