brintos

brintos / llvm-project-archived public Read only

0
0
Text · 30.8 KiB · 7b5dca6 Raw
849 lines · cpp
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-exception6//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/DynamicRecursiveASTVisitor.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/Core/AnalyzerOptions.h"31#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"32#include "clang/StaticAnalyzer/Core/CheckerManager.h"33#include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"34#include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"35#include "clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h"36#include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"37#include "llvm/ADT/PostOrderIterator.h"38#include "llvm/ADT/ScopeExit.h"39#include "llvm/Support/TimeProfiler.h"40#include "llvm/Support/Timer.h"41#include "llvm/Support/raw_ostream.h"42#include <cmath>43#include <memory>44#include <utility>45 46using namespace clang;47using namespace ento;48 49#define DEBUG_TYPE "AnalysisConsumer"50 51STAT_COUNTER(NumFunctionTopLevel, "The # of functions at top level.");52ALWAYS_ENABLED_STATISTIC(NumFunctionsAnalyzed,53                         "The # of functions and blocks analyzed (as top level "54                         "with inlining turned on).");55ALWAYS_ENABLED_STATISTIC(56    NumFunctionsAnalyzedSyntaxOnly,57    "The # of functions analyzed by syntax checkers only.");58ALWAYS_ENABLED_STATISTIC(NumBlocksInAnalyzedFunctions,59                         "The # of basic blocks in the analyzed functions.");60ALWAYS_ENABLED_STATISTIC(61    NumVisitedBlocksInAnalyzedFunctions,62    "The # of visited basic blocks in the analyzed functions.");63ALWAYS_ENABLED_STATISTIC(PercentReachableBlocks,64                         "The % of reachable basic blocks.");65ALWAYS_ENABLED_STATISTIC(MaxCFGSize,66                         "The maximum number of basic blocks in a function.");67static UnsignedEPStat CFGSize("CFGSize");68//===----------------------------------------------------------------------===//69// AnalysisConsumer declaration.70//===----------------------------------------------------------------------===//71 72namespace {73 74StringRef getMainFileName(const CompilerInvocation &Invocation) {75  if (!Invocation.getFrontendOpts().Inputs.empty()) {76    const FrontendInputFile &Input = Invocation.getFrontendOpts().Inputs[0];77    return Input.isFile() ? Input.getFile()78                          : Input.getBuffer().getBufferIdentifier();79  }80  return "<no input>";81}82 83class AnalysisConsumer : public AnalysisASTConsumer,84                         public DynamicRecursiveASTVisitor {85  enum {86    AM_None = 0,87    AM_Syntax = 0x1,88    AM_Path = 0x289  };90  typedef unsigned AnalysisMode;91 92  /// Mode of the analyzes while recursively visiting Decls.93  AnalysisMode RecVisitorMode;94  /// Bug Reporter to use while recursively visiting Decls.95  BugReporter *RecVisitorBR;96 97  std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;98 99public:100  ASTContext *Ctx;101  Preprocessor &PP;102  const std::string OutDir;103  AnalyzerOptions &Opts;104  ArrayRef<std::string> Plugins;105  std::unique_ptr<CodeInjector> Injector;106  cross_tu::CrossTranslationUnitContext CTU;107 108  /// Stores the declarations from the local translation unit.109  /// Note, we pre-compute the local declarations at parse time as an110  /// optimization to make sure we do not deserialize everything from disk.111  /// The local declaration to all declarations ratio might be very small when112  /// working with a PCH file.113  SetOfDecls LocalTUDecls;114 115  MacroExpansionContext MacroExpansions;116 117  // Set of PathDiagnosticConsumers.  Owned by AnalysisManager.118  PathDiagnosticConsumers PathConsumers;119 120  StoreManagerCreator CreateStoreMgr;121  ConstraintManagerCreator CreateConstraintMgr;122 123  std::unique_ptr<CheckerManager> checkerMgr;124  std::unique_ptr<AnalysisManager> Mgr;125 126  /// Time the analyzes time of each translation unit.127  std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;128  std::unique_ptr<llvm::Timer> SyntaxCheckTimer;129  std::unique_ptr<llvm::Timer> ExprEngineTimer;130  std::unique_ptr<llvm::Timer> BugReporterTimer;131 132  /// The information about analyzed functions shared throughout the133  /// translation unit.134  FunctionSummariesTy FunctionSummaries;135 136  AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,137                   AnalyzerOptions &opts, ArrayRef<std::string> plugins,138                   std::unique_ptr<CodeInjector> injector)139      : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),140        PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts), Plugins(plugins),141        Injector(std::move(injector)), CTU(CI),142        MacroExpansions(CI.getLangOpts()) {143 144    EntryPointStat::lockRegistry(getMainFileName(CI.getInvocation()),145                                 CI.getASTContext());146    DigestAnalyzerOptions();147 148    if (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||149        Opts.ShouldSerializeStats || !Opts.DumpEntryPointStatsToCSV.empty()) {150      AnalyzerTimers = std::make_unique<llvm::TimerGroup>(151          "analyzer", "Analyzer timers",152          /*PrintOnExit=*/153          (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||154           Opts.ShouldSerializeStats));155      SyntaxCheckTimer = std::make_unique<llvm::Timer>(156          "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);157      ExprEngineTimer = std::make_unique<llvm::Timer>(158          "exprengine", "Path exploration time", *AnalyzerTimers);159      BugReporterTimer = std::make_unique<llvm::Timer>(160          "bugreporter", "Path-sensitive report post-processing time",161          *AnalyzerTimers);162    }163 164    if (Opts.PrintStats || Opts.ShouldSerializeStats) {165      llvm::EnableStatistics(/* DoPrintOnExit= */ false);166    }167 168    if (Opts.ShouldDisplayMacroExpansions)169      MacroExpansions.registerForPreprocessor(PP);170 171    // Visitor options.172    ShouldWalkTypesOfTypeLocs = false;173  }174 175  ~AnalysisConsumer() override {176    if (Opts.PrintStats) {177      llvm::PrintStatistics();178    }179  }180 181  void DigestAnalyzerOptions() {182    switch (Opts.AnalysisDiagOpt) {183    case PD_NONE:184      break;185#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)                    \186  case PD_##NAME:                                                              \187    CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU,              \188             MacroExpansions);                                                 \189    break;190#include "clang/StaticAnalyzer/Core/Analyses.def"191    default:192      llvm_unreachable("Unknown analyzer output type!");193    }194 195    // Create the analyzer component creators.196    CreateStoreMgr = &CreateRegionStoreManager;197 198    switch (Opts.AnalysisConstraintsOpt) {199    default:200      llvm_unreachable("Unknown constraint manager.");201#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \202      case NAME##Model: CreateConstraintMgr = CREATEFN; break;203#include "clang/StaticAnalyzer/Core/Analyses.def"204    }205  }206 207  void DisplayTime(llvm::TimeRecord &Time) {208    if (!Opts.AnalyzerDisplayProgress) {209      return;210    }211    llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)212                 << " ms\n";213  }214 215  void DisplayFunction(const Decl *D, AnalysisMode Mode,216                       ExprEngine::InliningModes IMode) {217    if (!Opts.AnalyzerDisplayProgress)218      return;219 220    SourceManager &SM = Mgr->getASTContext().getSourceManager();221    PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());222    if (Loc.isValid()) {223      llvm::errs() << "ANALYZE";224 225      if (Mode == AM_Syntax)226        llvm::errs() << " (Syntax)";227      else if (Mode == AM_Path) {228        llvm::errs() << " (Path, ";229        switch (IMode) {230        case ExprEngine::Inline_Minimal:231          llvm::errs() << " Inline_Minimal";232          break;233        case ExprEngine::Inline_Regular:234          llvm::errs() << " Inline_Regular";235          break;236        }237        llvm::errs() << ")";238      } else239        assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");240 241      llvm::errs() << ": " << Loc.getFilename() << ' '242                   << AnalysisDeclContext::getFunctionName(D);243    }244  }245 246  /// Store the top level decls in the set to be processed later on.247  /// (Doing this pre-processing avoids deserialization of data from PCH.)248  bool HandleTopLevelDecl(DeclGroupRef D) override;249  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;250 251  void HandleTranslationUnit(ASTContext &C) override;252 253  /// Determine which inlining mode should be used when this function is254  /// analyzed. This allows to redefine the default inlining policies when255  /// analyzing a given function.256  ExprEngine::InliningModes257    getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);258 259  /// Build the call graph for all the top level decls of this TU and260  /// use it to define the order in which the functions should be visited.261  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);262 263  /// Run analyzes(syntax or path sensitive) on the given function.264  /// \param Mode - determines if we are requesting syntax only or path265  /// sensitive only analysis.266  /// \param VisitedCallees - The output parameter, which is populated with the267  /// set of functions which should be considered analyzed after analyzing the268  /// given root function.269  void HandleCode(Decl *D, AnalysisMode Mode,270                  ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,271                  SetOfConstDecls *VisitedCallees = nullptr);272 273  void RunPathSensitiveChecks(Decl *D,274                              ExprEngine::InliningModes IMode,275                              SetOfConstDecls *VisitedCallees);276 277  /// Handle callbacks for arbitrary Decls.278  bool VisitDecl(Decl *D) override {279    AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);280    if (Mode & AM_Syntax) {281      if (SyntaxCheckTimer)282        SyntaxCheckTimer->startTimer();283      checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);284      if (SyntaxCheckTimer)285        SyntaxCheckTimer->stopTimer();286    }287    return true;288  }289 290  bool VisitVarDecl(VarDecl *VD) override {291    if (!Opts.IsNaiveCTUEnabled)292      return true;293 294    if (VD->hasExternalStorage() || VD->isStaticDataMember()) {295      if (!cross_tu::shouldImport(VD, *Ctx))296        return true;297    } else {298      // Cannot be initialized in another TU.299      return true;300    }301 302    if (VD->getAnyInitializer())303      return true;304 305    llvm::Expected<const VarDecl *> CTUDeclOrError =306      CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,307                               Opts.DisplayCTUProgress);308 309    if (!CTUDeclOrError) {310      handleAllErrors(CTUDeclOrError.takeError(),311                      [&](const cross_tu::IndexError &IE) {312                        CTU.emitCrossTUDiagnostics(IE);313                      });314    }315 316    return true;317  }318 319  bool VisitFunctionDecl(FunctionDecl *FD) override {320    IdentifierInfo *II = FD->getIdentifier();321    if (II && II->getName().starts_with("__inline"))322      return true;323 324    // We skip function template definitions, as their semantics is325    // only determined when they are instantiated.326    if (FD->isThisDeclarationADefinition() &&327        !FD->isDependentContext()) {328      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);329      HandleCode(FD, RecVisitorMode);330    }331    return true;332  }333 334  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) override {335    if (MD->isThisDeclarationADefinition()) {336      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);337      HandleCode(MD, RecVisitorMode);338    }339    return true;340  }341 342  bool VisitBlockDecl(BlockDecl *BD) override {343    if (BD->hasBody()) {344      assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);345      // Since we skip function template definitions, we should skip blocks346      // declared in those functions as well.347      if (!BD->isDependentContext()) {348        HandleCode(BD, RecVisitorMode);349      }350    }351    return true;352  }353 354  void AddDiagnosticConsumer(355      std::unique_ptr<PathDiagnosticConsumer> Consumer) override {356    PathConsumers.push_back(std::move(Consumer));357  }358 359  void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {360    CheckerRegistrationFns.push_back(std::move(Fn));361  }362 363private:364  void storeTopLevelDecls(DeclGroupRef DG);365 366  /// Check if we should skip (not analyze) the given function.367  AnalysisMode getModeForDecl(const Decl *D, AnalysisMode Mode);368  void runAnalysisOnTranslationUnit(ASTContext &C);369 370  /// Print \p S to stderr if \c Opts.AnalyzerDisplayProgress is set.371  void reportAnalyzerProgress(StringRef S);372};373 374std::string timeTraceScopeDeclName(StringRef FunName, const Decl *D) {375  if (llvm::timeTraceProfilerEnabled()) {376    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))377      return (FunName + " " + ND->getQualifiedNameAsString()).str();378    return (FunName + " <anonymous> ").str();379  }380  return "";381}382 383llvm::TimeTraceMetadata timeTraceScopeDeclMetadata(const Decl *D) {384  // If time-trace profiler is not enabled, this function is never called.385  assert(llvm::timeTraceProfilerEnabled());386  if (const auto &Loc = D->getBeginLoc(); Loc.isValid()) {387    const auto &SM = D->getASTContext().getSourceManager();388    std::string DeclName = AnalysisDeclContext::getFunctionName(D);389    return llvm::TimeTraceMetadata{390        std::move(DeclName), SM.getFilename(Loc).str(),391        static_cast<int>(SM.getExpansionLineNumber(Loc))};392  }393  return llvm::TimeTraceMetadata{"", ""};394}395 396void flushReports(llvm::Timer *BugReporterTimer, BugReporter &BR) {397  llvm::TimeTraceScope TCS{"Flushing reports"};398  // Display warnings.399  if (BugReporterTimer)400    BugReporterTimer->startTimer();401  BR.FlushReports();402  if (BugReporterTimer)403    BugReporterTimer->stopTimer();404}405} // namespace406 407//===----------------------------------------------------------------------===//408// AnalysisConsumer implementation.409//===----------------------------------------------------------------------===//410bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {411  storeTopLevelDecls(DG);412  return true;413}414 415void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {416  storeTopLevelDecls(DG);417}418 419void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {420  for (auto &I : DG) {421 422    // Skip ObjCMethodDecl, wait for the objc container to avoid423    // analyzing twice.424    if (isa<ObjCMethodDecl>(I))425      continue;426 427    LocalTUDecls.push_back(I);428  }429}430 431static bool shouldSkipFunction(const Decl *D,432                               const SetOfConstDecls &Visited,433                               const SetOfConstDecls &VisitedAsTopLevel) {434  if (VisitedAsTopLevel.count(D))435    return true;436 437  // Skip analysis of inheriting constructors as top-level functions. These438  // constructors don't even have a body written down in the code, so even if439  // we find a bug, we won't be able to display it.440  if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))441    if (CD->isInheritingConstructor())442      return true;443 444  // We want to re-analyse the functions as top level in the following cases:445  // - The 'init' methods should be reanalyzed because446  //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns447  //   'nil' and unless we analyze the 'init' functions as top level, we will448  //   not catch errors within defensive code.449  // - We want to reanalyze all ObjC methods as top level to report Retain450  //   Count naming convention errors more aggressively.451  if (isa<ObjCMethodDecl>(D))452    return false;453  // We also want to reanalyze all C++ copy and move assignment operators to454  // separately check the two cases where 'this' aliases with the parameter and455  // where it may not. (cplusplus.SelfAssignmentChecker)456  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {457    if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())458      return false;459  }460 461  // Otherwise, if we visited the function before, do not reanalyze it.462  return Visited.count(D);463}464 465ExprEngine::InliningModes466AnalysisConsumer::getInliningModeForFunction(const Decl *D,467                                             const SetOfConstDecls &Visited) {468  // We want to reanalyze all ObjC methods as top level to report Retain469  // Count naming convention errors more aggressively. But we should tune down470  // inlining when reanalyzing an already inlined function.471  if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {472    const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);473    if (ObjCM->getMethodFamily() != OMF_init)474      return ExprEngine::Inline_Minimal;475  }476 477  return ExprEngine::Inline_Regular;478}479 480void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {481  // Build the Call Graph by adding all the top level declarations to the graph.482  // Note: CallGraph can trigger deserialization of more items from a pch483  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.484  // We rely on random access to add the initially processed Decls to CG.485  CallGraph CG;486  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {487    CG.addToCallGraph(LocalTUDecls[i]);488  }489 490  // Walk over all of the call graph nodes in topological order, so that we491  // analyze parents before the children. Skip the functions inlined into492  // the previously processed functions. Use external Visited set to identify493  // inlined functions. The topological order allows the "do not reanalyze494  // previously inlined function" performance heuristic to be triggered more495  // often.496  SetOfConstDecls Visited;497  SetOfConstDecls VisitedAsTopLevel;498  llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);499  for (auto &N : RPOT) {500    NumFunctionTopLevel++;501 502    Decl *D = N->getDecl();503 504    // Skip the abstract root node.505    if (!D)506      continue;507 508    // Skip the functions which have been processed already or previously509    // inlined.510    if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))511      continue;512 513    // The CallGraph might have declarations as callees. However, during CTU514    // the declaration might form a declaration chain with the newly imported515    // definition from another TU. In this case we don't want to analyze the516    // function definition as toplevel.517    if (const auto *FD = dyn_cast<FunctionDecl>(D)) {518      // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl519      // that has the body.520      FD->hasBody(FD);521      if (CTU.isImportedAsNew(FD))522        continue;523    }524 525    // Analyze the function.526    SetOfConstDecls VisitedCallees;527 528    HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),529               (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));530 531    // Add the visited callees to the global visited set.532    for (const Decl *Callee : VisitedCallees)533      // Decls from CallGraph are already canonical. But Decls coming from534      // CallExprs may be not. We should canonicalize them manually.535      Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee536                                                 : Callee->getCanonicalDecl());537    VisitedAsTopLevel.insert(D);538  }539}540 541static bool fileContainsString(StringRef Substring, ASTContext &C) {542  const SourceManager &SM = C.getSourceManager();543  FileID FID = SM.getMainFileID();544  StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();545  return Buffer.contains(Substring);546}547 548static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts,549                                         const ASTContext &Ctx) {550  llvm::errs() << "Every top-level function was skipped.\n";551 552  if (!Opts.AnalyzerDisplayProgress)553    llvm::errs() << "Pass the -analyzer-display-progress for tracking which "554                    "functions are analyzed.\n";555 556  bool HasBrackets =557      Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;558 559  if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {560    llvm::errs()561        << "For analyzing C++ code you need to pass the function parameter "562           "list: -analyze-function=\"foobar(int, _Bool)\"\n";563  } else if (!Ctx.getLangOpts().CPlusPlus && HasBrackets) {564    llvm::errs() << "For analyzing C code you shouldn't pass the function "565                    "parameter list, only the name of the function: "566                    "-analyze-function=foobar\n";567  }568}569 570void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {571  BugReporter BR(*Mgr);572  const TranslationUnitDecl *TU = C.getTranslationUnitDecl();573  BR.setAnalysisEntryPoint(TU);574  if (SyntaxCheckTimer)575    SyntaxCheckTimer->startTimer();576  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);577  if (SyntaxCheckTimer)578    SyntaxCheckTimer->stopTimer();579 580  // Run the AST-only checks using the order in which functions are defined.581  // If inlining is not turned on, use the simplest function order for path582  // sensitive analyzes as well.583  RecVisitorMode = AM_Syntax;584  if (!Mgr->shouldInlineCall())585    RecVisitorMode |= AM_Path;586  RecVisitorBR = &BR;587 588  // Process all the top level declarations.589  //590  // Note: TraverseDecl may modify LocalTUDecls, but only by appending more591  // entries.  Thus we don't use an iterator, but rely on LocalTUDecls592  // random access.  By doing so, we automatically compensate for iterators593  // possibly being invalidated, although this is a bit slower.594  const unsigned LocalTUDeclsSize = LocalTUDecls.size();595  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {596    TraverseDecl(LocalTUDecls[i]);597  }598 599  if (Mgr->shouldInlineCall())600    HandleDeclsCallGraph(LocalTUDeclsSize);601 602  // After all decls handled, run checkers on the entire TranslationUnit.603  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);604 605  BR.FlushReports();606  RecVisitorBR = nullptr;607 608  // If the user wanted to analyze a specific function and the number of basic609  // blocks analyzed is zero, than the user might not specified the function610  // name correctly.611  if (!Opts.AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0 &&612      NumFunctionsAnalyzedSyntaxOnly == 0) {613    reportAnalyzerFunctionMisuse(Opts, *Ctx);614  }615}616 617void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {618  if (Opts.AnalyzerDisplayProgress)619    llvm::errs() << S;620}621 622void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {623  // Don't run the actions if an error has occurred with parsing the file.624  DiagnosticsEngine &Diags = PP.getDiagnostics();625  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())626    return;627 628  Ctx = &C;629  checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,630                                                CheckerRegistrationFns);631 632  Mgr = std::make_unique<AnalysisManager>(633      *Ctx, PP, std::move(PathConsumers), CreateStoreMgr, CreateConstraintMgr,634      checkerMgr.get(), Opts, std::move(Injector));635 636  // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.637  // FIXME: This should be replaced with something that doesn't rely on638  // side-effects in PathDiagnosticConsumer's destructor. This is required when639  // used with option -disable-free.640  const auto DiagFlusherScopeExit =641      llvm::make_scope_exit([this] { Mgr.reset(); });642 643  if (Opts.ShouldIgnoreBisonGeneratedFiles &&644      fileContainsString("/* A Bison parser, made by", C)) {645    reportAnalyzerProgress("Skipping bison-generated file\n");646    return;647  }648 649  if (Opts.ShouldIgnoreFlexGeneratedFiles &&650      fileContainsString("/* A lexical scanner generated by flex", C)) {651    reportAnalyzerProgress("Skipping flex-generated file\n");652    return;653  }654 655  // Don't analyze if the user explicitly asked for no checks to be performed656  // on this file.657  if (Opts.DisableAllCheckers) {658    reportAnalyzerProgress("All checks are disabled using a supplied option\n");659    return;660  }661 662  // Otherwise, just run the analysis.663  runAnalysisOnTranslationUnit(C);664 665  // Count how many basic blocks we have not covered.666  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();667  NumVisitedBlocksInAnalyzedFunctions =668      FunctionSummaries.getTotalNumVisitedBasicBlocks();669  if (NumBlocksInAnalyzedFunctions > 0)670    PercentReachableBlocks =671        (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /672        NumBlocksInAnalyzedFunctions;673 674  if (!Opts.DumpEntryPointStatsToCSV.empty()) {675    EntryPointStat::dumpStatsAsCSV(Opts.DumpEntryPointStatsToCSV);676  }677}678 679AnalysisConsumer::AnalysisMode680AnalysisConsumer::getModeForDecl(const Decl *D, AnalysisMode Mode) {681  if (!Opts.AnalyzeSpecificFunction.empty() &&682      AnalysisDeclContext::getFunctionName(D) != Opts.AnalyzeSpecificFunction &&683      cross_tu::CrossTranslationUnitContext::getLookupName(D).value_or("") !=684          Opts.AnalyzeSpecificFunction) {685    return AM_None;686  }687 688  // Unless -analyze-all is specified, treat decls differently depending on689  // where they came from:690  // - Main source file: run both path-sensitive and non-path-sensitive checks.691  // - Header files: run non-path-sensitive checks only.692  // - System headers: don't run any checks.693  if (Opts.AnalyzeAll)694    return Mode;695 696  const SourceManager &SM = Ctx->getSourceManager();697 698  const SourceLocation Loc = [&SM](const Decl *D) -> SourceLocation {699    const Stmt *Body = D->getBody();700    SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();701    return SM.getExpansionLoc(SL);702  }(D);703 704  // Ignore system headers.705  if (Loc.isInvalid() || SM.isInSystemHeader(Loc))706    return AM_None;707 708  // Disable path sensitive analysis in user-headers.709  if (!Mgr->isInCodeFile(Loc))710    return Mode & ~AM_Path;711 712  return Mode;713}714 715static UnsignedEPStat PathRunningTime("PathRunningTime");716static UnsignedEPStat SyntaxRunningTime("SyntaxRunningTime");717 718void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,719                                  ExprEngine::InliningModes IMode,720                                  SetOfConstDecls *VisitedCallees) {721  llvm::TimeTraceScope TCS(timeTraceScopeDeclName("HandleCode", D),722                           [D]() { return timeTraceScopeDeclMetadata(D); });723  if (!D->hasBody())724    return;725  Mode = getModeForDecl(D, Mode);726  if (Mode == AM_None)727    return;728 729  // Clear the AnalysisManager of old AnalysisDeclContexts.730  Mgr->ClearContexts();731  // Ignore autosynthesized code.732  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())733    return;734 735  CFG *DeclCFG = Mgr->getCFG(D);736  if (DeclCFG)737    MaxCFGSize.updateMax(DeclCFG->size());738 739  DisplayFunction(D, Mode, IMode);740  BugReporter BR(*Mgr);741  BR.setAnalysisEntryPoint(D);742 743  if (Mode & AM_Syntax) {744    llvm::TimeRecord CheckerStartTime;745    if (SyntaxCheckTimer) {746      CheckerStartTime = SyntaxCheckTimer->getTotalTime();747      SyntaxCheckTimer->startTimer();748    }749    checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);750    ++NumFunctionsAnalyzedSyntaxOnly;751    if (SyntaxCheckTimer) {752      SyntaxCheckTimer->stopTimer();753      llvm::TimeRecord CheckerDuration =754          SyntaxCheckTimer->getTotalTime() - CheckerStartTime;755      FunctionSummaries.findOrInsertSummary(D)->second.SyntaxRunningTime =756          std::lround(CheckerDuration.getWallTime() * 1000);757      DisplayTime(CheckerDuration);758    }759  }760 761  BR.FlushReports();762 763  if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {764    RunPathSensitiveChecks(D, IMode, VisitedCallees);765    EntryPointStat::takeSnapshot(D);766    if (IMode != ExprEngine::Inline_Minimal)767      NumFunctionsAnalyzed++;768  }769}770 771//===----------------------------------------------------------------------===//772// Path-sensitive checking.773//===----------------------------------------------------------------------===//774 775void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,776                                              ExprEngine::InliningModes IMode,777                                              SetOfConstDecls *VisitedCallees) {778  auto *CFG = Mgr->getCFG(D);779 780  // Construct the analysis engine.  First check if the CFG is valid.781  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.782  if (!CFG)783    return;784 785  CFGSize.set(CFG->size());786 787  auto *DeclContext = Mgr->getAnalysisDeclContext(D);788  // See if the LiveVariables analysis scales.789  if (!DeclContext->getAnalysis<RelaxedLiveVariables>())790    return;791 792  // DeclContext declaration is the redeclaration of D that has a body.793  const Decl *DefDecl = DeclContext->getDecl();794 795  // Get the SyntaxRunningTime from the function summary, because it is computed796  // during the AM_Syntax analysis, which is done at a different point in time797  // and in different order, but always before AM_Path.798  if (const auto *Summary = FunctionSummaries.findSummary(DefDecl);799      Summary && Summary->SyntaxRunningTime.has_value()) {800    SyntaxRunningTime.set(*Summary->SyntaxRunningTime);801  }802 803  ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);804 805  // Execute the worklist algorithm.806  llvm::TimeRecord ExprEngineStartTime;807  if (ExprEngineTimer) {808    ExprEngineStartTime = ExprEngineTimer->getTotalTime();809    ExprEngineTimer->startTimer();810  }811  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),812                      Mgr->options.MaxNodesPerTopLevelFunction);813  if (ExprEngineTimer) {814    ExprEngineTimer->stopTimer();815    llvm::TimeRecord ExprEngineDuration =816        ExprEngineTimer->getTotalTime() - ExprEngineStartTime;817    PathRunningTime.set(static_cast<unsigned>(818        std::lround(ExprEngineDuration.getWallTime() * 1000)));819    DisplayTime(ExprEngineDuration);820  }821 822  if (!Mgr->options.DumpExplodedGraphTo.empty())823    Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);824 825  // Visualize the exploded graph.826  if (Mgr->options.visualizeExplodedGraphWithGraphViz)827    Eng.ViewGraph(Mgr->options.TrimGraph);828 829  flushReports(BugReporterTimer.get(), Eng.getBugReporter());830}831 832//===----------------------------------------------------------------------===//833// AnalysisConsumer creation.834//===----------------------------------------------------------------------===//835 836std::unique_ptr<AnalysisASTConsumer>837ento::CreateAnalysisConsumer(CompilerInstance &CI) {838  // Disable the effects of '-Werror' when using the AnalysisConsumer.839  CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);840 841  AnalyzerOptions &analyzerOpts = CI.getAnalyzerOpts();842  bool hasModelPath = analyzerOpts.Config.count("model-path") > 0;843 844  return std::make_unique<AnalysisConsumer>(845      CI, CI.getFrontendOpts().OutputFile, analyzerOpts,846      CI.getFrontendOpts().Plugins,847      hasModelPath ? std::make_unique<ModelInjector>(CI) : nullptr);848}849