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