clang  15.0.0git
AnalysisConsumer.cpp
Go to the documentation of this file.
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 
14 #include "ModelInjector.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
20 #include "clang/Analysis/CFG.h"
28 #include "clang/Lex/Preprocessor.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;
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,
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,
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) {
215  llvm::errs() << " Inline_Minimal";
216  break;
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() << ' '
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.
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,
265  SetOfConstDecls *VisitedCallees = nullptr);
266 
267  void RunPathSensitiveChecks(Decl *D,
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::shouldImport(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 (auto &I : DG) {
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 
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)
441  }
442 
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 (auto &N : RPOT) {
466  NumFunctionTopLevel++;
467 
468  Decl *D = N->getDecl();
469 
470  // Skip the abstract root node.
471  if (!D)
472  continue;
473 
474  // Skip the functions which have been processed already or previously
475  // inlined.
476  if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
477  continue;
478 
479  // The CallGraph might have declarations as callees. However, during CTU
480  // the declaration might form a declaration chain with the newly imported
481  // definition from another TU. In this case we don't want to analyze the
482  // function definition as toplevel.
483  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
484  // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
485  // that has the body.
486  FD->hasBody(FD);
487  if (CTU.isImportedAsNew(FD))
488  continue;
489  }
490 
491  // Analyze the function.
492  SetOfConstDecls VisitedCallees;
493 
494  HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
495  (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
496 
497  // Add the visited callees to the global visited set.
498  for (const Decl *Callee : VisitedCallees)
499  // Decls from CallGraph are already canonical. But Decls coming from
500  // CallExprs may be not. We should canonicalize them manually.
501  Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
502  : Callee->getCanonicalDecl());
503  VisitedAsTopLevel.insert(D);
504  }
505 }
506 
507 static bool fileContainsString(StringRef Substring, ASTContext &C) {
508  const SourceManager &SM = C.getSourceManager();
509  FileID FID = SM.getMainFileID();
510  StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
511  return Buffer.contains(Substring);
512 }
513 
515  const ASTContext &Ctx) {
516  llvm::errs() << "Every top-level function was skipped.\n";
517 
518  if (!Opts.AnalyzerDisplayProgress)
519  llvm::errs() << "Pass the -analyzer-display-progress for tracking which "
520  "functions are analyzed.\n";
521 
522  bool HasBrackets =
523  Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;
524 
525  if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {
526  llvm::errs()
527  << "For analyzing C++ code you need to pass the function parameter "
528  "list: -analyze-function=\"foobar(int, _Bool)\"\n";
529  } else if (!Ctx.getLangOpts().CPlusPlus && HasBrackets) {
530  llvm::errs() << "For analyzing C code you shouldn't pass the function "
531  "parameter list, only the name of the function: "
532  "-analyze-function=foobar\n";
533  }
534 }
535 
536 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
537  BugReporter BR(*Mgr);
538  TranslationUnitDecl *TU = C.getTranslationUnitDecl();
539  if (SyntaxCheckTimer)
540  SyntaxCheckTimer->startTimer();
541  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
542  if (SyntaxCheckTimer)
543  SyntaxCheckTimer->stopTimer();
544 
545  // Run the AST-only checks using the order in which functions are defined.
546  // If inlining is not turned on, use the simplest function order for path
547  // sensitive analyzes as well.
548  RecVisitorMode = AM_Syntax;
549  if (!Mgr->shouldInlineCall())
550  RecVisitorMode |= AM_Path;
551  RecVisitorBR = &BR;
552 
553  // Process all the top level declarations.
554  //
555  // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
556  // entries. Thus we don't use an iterator, but rely on LocalTUDecls
557  // random access. By doing so, we automatically compensate for iterators
558  // possibly being invalidated, although this is a bit slower.
559  const unsigned LocalTUDeclsSize = LocalTUDecls.size();
560  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
561  TraverseDecl(LocalTUDecls[i]);
562  }
563 
564  if (Mgr->shouldInlineCall())
565  HandleDeclsCallGraph(LocalTUDeclsSize);
566 
567  // After all decls handled, run checkers on the entire TranslationUnit.
568  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
569 
570  BR.FlushReports();
571  RecVisitorBR = nullptr;
572 
573  // If the user wanted to analyze a specific function and the number of basic
574  // blocks analyzed is zero, than the user might not specified the function
575  // name correctly.
576  // FIXME: The user might have analyzed the requested function in Syntax mode,
577  // but we are unaware of that.
578  if (!Opts->AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0)
579  reportAnalyzerFunctionMisuse(*Opts, *Ctx);
580 }
581 
582 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
583  if (Opts->AnalyzerDisplayProgress)
584  llvm::errs() << S;
585 }
586 
587 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
588  // Don't run the actions if an error has occurred with parsing the file.
589  DiagnosticsEngine &Diags = PP.getDiagnostics();
590  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
591  return;
592 
593  // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
594  // FIXME: This should be replaced with something that doesn't rely on
595  // side-effects in PathDiagnosticConsumer's destructor. This is required when
596  // used with option -disable-free.
597  const auto DiagFlusherScopeExit =
598  llvm::make_scope_exit([this] { Mgr.reset(); });
599 
600  if (Opts->ShouldIgnoreBisonGeneratedFiles &&
601  fileContainsString("/* A Bison parser, made by", C)) {
602  reportAnalyzerProgress("Skipping bison-generated file\n");
603  return;
604  }
605 
606  if (Opts->ShouldIgnoreFlexGeneratedFiles &&
607  fileContainsString("/* A lexical scanner generated by flex", C)) {
608  reportAnalyzerProgress("Skipping flex-generated file\n");
609  return;
610  }
611 
612  // Don't analyze if the user explicitly asked for no checks to be performed
613  // on this file.
614  if (Opts->DisableAllCheckers) {
615  reportAnalyzerProgress("All checks are disabled using a supplied option\n");
616  return;
617  }
618 
619  // Otherwise, just run the analysis.
620  runAnalysisOnTranslationUnit(C);
621 
622  // Count how many basic blocks we have not covered.
623  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
624  NumVisitedBlocksInAnalyzedFunctions =
625  FunctionSummaries.getTotalNumVisitedBasicBlocks();
626  if (NumBlocksInAnalyzedFunctions > 0)
627  PercentReachableBlocks =
628  (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
629  NumBlocksInAnalyzedFunctions;
630 }
631 
632 AnalysisConsumer::AnalysisMode
633 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
634  if (!Opts->AnalyzeSpecificFunction.empty() &&
635  AnalysisDeclContext::getFunctionName(D) != Opts->AnalyzeSpecificFunction)
636  return AM_None;
637 
638  // Unless -analyze-all is specified, treat decls differently depending on
639  // where they came from:
640  // - Main source file: run both path-sensitive and non-path-sensitive checks.
641  // - Header files: run non-path-sensitive checks only.
642  // - System headers: don't run any checks.
643  if (Opts->AnalyzeAll)
644  return Mode;
645 
646  const SourceManager &SM = Ctx->getSourceManager();
647 
648  const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
649  const Stmt *Body = D->getBody();
650  SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
651  return SM.getExpansionLoc(SL);
652  }(D);
653 
654  // Ignore system headers.
655  if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
656  return AM_None;
657 
658  // Disable path sensitive analysis in user-headers.
659  if (!Mgr->isInCodeFile(Loc))
660  return Mode & ~AM_Path;
661 
662  return Mode;
663 }
664 
665 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
667  SetOfConstDecls *VisitedCallees) {
668  if (!D->hasBody())
669  return;
670  Mode = getModeForDecl(D, Mode);
671  if (Mode == AM_None)
672  return;
673 
674  // Clear the AnalysisManager of old AnalysisDeclContexts.
675  Mgr->ClearContexts();
676  // Ignore autosynthesized code.
677  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
678  return;
679 
680  CFG *DeclCFG = Mgr->getCFG(D);
681  if (DeclCFG)
682  MaxCFGSize.updateMax(DeclCFG->size());
683 
684  DisplayFunction(D, Mode, IMode);
685  BugReporter BR(*Mgr);
686 
687  if (Mode & AM_Syntax) {
688  llvm::TimeRecord CheckerStartTime;
689  if (SyntaxCheckTimer) {
690  CheckerStartTime = SyntaxCheckTimer->getTotalTime();
691  SyntaxCheckTimer->startTimer();
692  }
693  checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
694  if (SyntaxCheckTimer) {
695  SyntaxCheckTimer->stopTimer();
696  llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
697  CheckerEndTime -= CheckerStartTime;
698  DisplayTime(CheckerEndTime);
699  }
700  }
701 
702  BR.FlushReports();
703 
704  if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
705  RunPathSensitiveChecks(D, IMode, VisitedCallees);
706  if (IMode != ExprEngine::Inline_Minimal)
707  NumFunctionsAnalyzed++;
708  }
709 }
710 
711 //===----------------------------------------------------------------------===//
712 // Path-sensitive checking.
713 //===----------------------------------------------------------------------===//
714 
715 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
717  SetOfConstDecls *VisitedCallees) {
718  // Construct the analysis engine. First check if the CFG is valid.
719  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
720  if (!Mgr->getCFG(D))
721  return;
722 
723  // See if the LiveVariables analysis scales.
724  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
725  return;
726 
727  ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
728 
729  // Execute the worklist algorithm.
730  llvm::TimeRecord ExprEngineStartTime;
731  if (ExprEngineTimer) {
732  ExprEngineStartTime = ExprEngineTimer->getTotalTime();
733  ExprEngineTimer->startTimer();
734  }
735  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
736  Mgr->options.MaxNodesPerTopLevelFunction);
737  if (ExprEngineTimer) {
738  ExprEngineTimer->stopTimer();
739  llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
740  ExprEngineEndTime -= ExprEngineStartTime;
741  DisplayTime(ExprEngineEndTime);
742  }
743 
744  if (!Mgr->options.DumpExplodedGraphTo.empty())
745  Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
746 
747  // Visualize the exploded graph.
748  if (Mgr->options.visualizeExplodedGraphWithGraphViz)
749  Eng.ViewGraph(Mgr->options.TrimGraph);
750 
751  // Display warnings.
752  if (BugReporterTimer)
753  BugReporterTimer->startTimer();
754  Eng.getBugReporter().FlushReports();
755  if (BugReporterTimer)
756  BugReporterTimer->stopTimer();
757 }
758 
759 //===----------------------------------------------------------------------===//
760 // AnalysisConsumer creation.
761 //===----------------------------------------------------------------------===//
762 
763 std::unique_ptr<AnalysisASTConsumer>
765  // Disable the effects of '-Werror' when using the AnalysisConsumer.
767 
768  AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
769  bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
770 
771  return std::make_unique<AnalysisConsumer>(
772  CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
774  hasModelPath ? new ModelInjector(CI) : nullptr);
775 }
clang::ento::SetOfDecls
std::deque< Decl * > SetOfDecls
Definition: FunctionSummary.h:30
AnalyzerOptions.h
reportAnalyzerFunctionMisuse
static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts, const ASTContext &Ctx)
Definition: AnalysisConsumer.cpp:514
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::cross_tu::shouldImport
bool shouldImport(const VarDecl *VD, const ASTContext &ACtx)
Returns true if it makes sense to import a foreign variable definition.
Definition: CrossTranslationUnit.cpp:223
CodeInjector.h
clang::ento::StoreManagerCreator
std::unique_ptr< StoreManager >(* StoreManagerCreator)(ProgramStateManager &)
Definition: ProgramState.h:43
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
PathDiagnosticConsumers.h
AttributeLangSupport::C
@ C
Definition: SemaDeclAttr.cpp:55
shouldSkipFunction
static bool shouldSkipFunction(const Decl *D, const SetOfConstDecls &Visited, const SetOfConstDecls &VisitedAsTopLevel)
Definition: AnalysisConsumer.cpp:397
clang::OMF_init
@ OMF_init
Definition: IdentifierTable.h:700
clang::Decl::hasBody
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
Definition: DeclBase.h:1025
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DeclCXX.h
SourceManager.h
llvm::Expected
Definition: LLVM.h:41
clang::CFG::size
unsigned size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
Definition: CFG.h:1416
clang::CompilerInstance::getAnalyzerOpts
AnalyzerOptionsRef getAnalyzerOpts()
Definition: CompilerInstance.h:250
clang::CFG
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
Definition: CFG.h:1225
clang::ASTContext::getSourceManager
SourceManager & getSourceManager()
Definition: ASTContext.h:716
clang::ento::ModelInjector
Definition: ModelInjector.h:35
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:627
AnalysisConsumer.h
Preprocessor.h
Decl.h
DeclObjC.h
clang::ento::ExprEngine::Inline_Minimal
@ Inline_Minimal
Do minimal inlining of callees.
Definition: ExprEngine.h:133
clang::TranslationUnitDecl
The top declaration context.
Definition: Decl.h:80
clang::AnalyzerOptions::AnalyzerDisplayProgress
unsigned AnalyzerDisplayProgress
Definition: AnalyzerOptions.h:246
clang::BlockDecl
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4201
clang::FrontendOptions::OutputFile
std::string OutputFile
The output file, if any.
Definition: FrontendOptions.h:433
clang::DiagnosticsEngine::hasFatalErrorOccurred
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:844
clang::cross_tu::CrossTranslationUnitContext
This class is used for tools that requires cross translation unit capability.
Definition: CrossTranslationUnit.h:127
LiveVariables.h
clang::syntax::NodeRole::Callee
@ Callee
clang::PresumedLoc::getFilename
const char * getFilename() const
Return the presumed filename of this location.
Definition: SourceLocation.h:324
CheckerManager.h
BugReporter.h
clang::ObjCMethodDecl::getMethodFamily
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1018
clang::VarDecl::isStaticDataMember
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1198
clang::DiagnosticsEngine::hasErrorOccurred
bool hasErrorOccurred() const
Definition: Diagnostic.h:837
clang::FunctionDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2167
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:208
clang::RecursiveASTVisitor
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Definition: RecursiveASTVisitor.h:165
LocalCheckers.h
clang::PD_NONE
@ PD_NONE
Definition: AnalyzerOptions.h:62
clang::VarDecl::hasExternalStorage
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1132
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:874
clang::ento::ExprEngine::InliningModes
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:128
clang::CompilerInstance::getPreprocessor
Preprocessor & getPreprocessor() const
Return the current preprocessor.
Definition: CompilerInstance.h:442
PathDiagnostic.h
clang::CompilerInstance
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Definition: CompilerInstance.h:72
clang::ento::SetOfConstDecls
llvm::DenseSet< const Decl * > SetOfConstDecls
Definition: FunctionSummary.h:31
MacroExpansionContext.h
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3012
clang::AnalyzerOptions::AnalyzeSpecificFunction
std::string AnalyzeSpecificFunction
Definition: AnalyzerOptions.h:215
clang::DiagnosticsEngine::setWarningsAsErrors
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition: Diagnostic.h:663
clang::VarDecl::getAnyInitializer
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1273
clang::MacroExpansionContext::registerForPreprocessor
void registerForPreprocessor(Preprocessor &PP)
Register the necessary callbacks to the Preprocessor to record the expansion events and the generated...
Definition: MacroExpansionContext.cpp:88
ModelInjector.h
fileContainsString
static bool fileContainsString(StringRef Substring, ASTContext &C)
Definition: AnalysisConsumer.cpp:507
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
llvm::ArrayRef< std::string >
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::FrontendOptions::Plugins
std::vector< std::string > Plugins
The list of plugins to load.
Definition: FrontendOptions.h:461
clang::AnalyzerOptions
Stores options for the analyzer from the command line.
Definition: AnalyzerOptions.h:165
clang::MacroExpansionContext
MacroExpansionContext tracks the macro expansions processed by the Preprocessor.
Definition: MacroExpansionContext.h:73
clang::AnalysisDeclContext::getFunctionName
static std::string getFunctionName(const Decl *D)
Definition: AnalysisDeclContext.cpp:340
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::ento::CreateAnalysisConsumer
std::unique_ptr< AnalysisASTConsumer > CreateAnalysisConsumer(CompilerInstance &CI)
CreateAnalysisConsumer - Creates an ASTConsumer to run various code analysis passes.
Definition: AnalysisConsumer.cpp:764
clang::cross_tu::CrossTranslationUnitContext::getCrossTUDefinition
llvm::Expected< const FunctionDecl * > getCrossTUDefinition(const FunctionDecl *FD, StringRef CrossTUDir, StringRef IndexName, bool DisplayCTUProgress=false)
This function loads a function or variable definition from an external AST file and merges it into th...
Definition: CrossTranslationUnit.cpp:353
clang::Decl::getBody
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
Definition: DeclBase.h:1019
std
Definition: Format.h:4296
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
ExprEngine.h
clang::CallGraph::addToCallGraph
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
Definition: CallGraph.h:62
clang::PresumedLoc::isValid
bool isValid() const
Definition: SourceLocation.h:319
clang::ento::PathDiagnosticConsumers
std::vector< PathDiagnosticConsumer * > PathDiagnosticConsumers
Definition: PathDiagnosticConsumers.h:32
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:195
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang
Definition: CalledOnceCheck.h:17
RecursiveASTVisitor.h
CFG.h
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
clang::Preprocessor::getDiagnostics
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:991
clang::FileID
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Definition: SourceLocation.h:38
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1152
CallGraph.h
clang::RelaxedLiveVariables
Definition: LiveVariables.h:112
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
clang::cross_tu::IndexError
Definition: CrossTranslationUnit.h:61
CompilerInstance.h
clang::CompilerInstance::getFrontendOpts
FrontendOptions & getFrontendOpts()
Definition: CompilerInstance.h:282
clang::CodeInjector
CodeInjector is an interface which is responsible for injecting AST of function definitions that may ...
Definition: CodeInjector.h:35
clang::PresumedLoc
Represents an unpacked "presumed" location which can be presented to the user.
Definition: SourceLocation.h:302
Rewriter.h
clang::ento::ConstraintManagerCreator
std::unique_ptr< ConstraintManager >(* ConstraintManagerCreator)(ProgramStateManager &, ExprEngine *)
Definition: ProgramState.h:41
clang::Preprocessor
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:131
CrossTranslationUnit.h
SM
#define SM(sm)
Definition: Cuda.cpp:81
clang::cross_tu::CrossTranslationUnitContext::isImportedAsNew
bool isImportedAsNew(const Decl *ToDecl) const
Returns true if the given Decl is newly created during the import.
Definition: CrossTranslationUnit.cpp:804
clang::ento::ExprEngine::Inline_Regular
@ Inline_Regular
Follow the default settings for inlining callees.
Definition: ExprEngine.h:130
AnalysisManager.h
clang::ObjCMethodDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition: DeclObjC.h:538
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:425
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1872
STATISTIC
STATISTIC(NumFunctionTopLevel, "The # of functions at top level.")
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:786
llvm::IntrusiveRefCntPtr< AnalyzerOptions >
clang::CallGraph
The AST-based call graph.
Definition: CallGraph.h:42