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