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