clang  8.0.0svn
AnalysisConsumer.cpp
Go to the documentation of this file.
1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // "Meta" ASTConsumer for running different source analyses.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "ModelInjector.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
21 #include "clang/Analysis/CFG.h"
27 #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 // Special PathDiagnosticConsumers.
66 //===----------------------------------------------------------------------===//
67 
68 void ento::createPlistHTMLDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
70  const std::string &prefix,
71  const Preprocessor &PP) {
72  createHTMLDiagnosticConsumer(AnalyzerOpts, C,
73  llvm::sys::path::parent_path(prefix), PP);
74  createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP);
75 }
76 
77 void ento::createTextPathDiagnosticConsumer(AnalyzerOptions &AnalyzerOpts,
79  const std::string &Prefix,
80  const clang::Preprocessor &PP) {
81  llvm_unreachable("'text' consumer should be enabled on ClangDiags");
82 }
83 
84 namespace {
85 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
87  bool IncludePath;
88 public:
89  ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
90  : Diag(Diag), IncludePath(false) {}
91  ~ClangDiagPathDiagConsumer() override {}
92  StringRef getName() const override { return "ClangDiags"; }
93 
94  bool supportsLogicalOpControlFlow() const override { return true; }
95  bool supportsCrossFileDiagnostics() const override { return true; }
96 
97  PathGenerationScheme getGenerationScheme() const override {
98  return IncludePath ? Minimal : None;
99  }
100 
101  void enablePaths() {
102  IncludePath = true;
103  }
104 
105  void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
106  FilesMade *filesMade) override {
107  unsigned WarnID = Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
108  unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
109 
110  for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
111  E = Diags.end(); I != E; ++I) {
112  const PathDiagnostic *PD = *I;
113  SourceLocation WarnLoc = PD->getLocation().asLocation();
114  Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
115  << PD->path.back()->getRanges();
116 
117  // First, add extra notes, even if paths should not be included.
118  for (const auto &Piece : PD->path) {
119  if (!isa<PathDiagnosticNotePiece>(Piece.get()))
120  continue;
121 
122  SourceLocation NoteLoc = Piece->getLocation().asLocation();
123  Diag.Report(NoteLoc, NoteID) << Piece->getString()
124  << Piece->getRanges();
125  }
126 
127  if (!IncludePath)
128  continue;
129 
130  // Then, add the path notes if necessary.
131  PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
132  for (const auto &Piece : FlatPath) {
133  if (isa<PathDiagnosticNotePiece>(Piece.get()))
134  continue;
135 
136  SourceLocation NoteLoc = Piece->getLocation().asLocation();
137  Diag.Report(NoteLoc, NoteID) << Piece->getString()
138  << Piece->getRanges();
139  }
140  }
141  }
142 };
143 } // end anonymous namespace
144 
145 //===----------------------------------------------------------------------===//
146 // AnalysisConsumer declaration.
147 //===----------------------------------------------------------------------===//
148 
149 namespace {
150 
151 class AnalysisConsumer : public AnalysisASTConsumer,
152  public RecursiveASTVisitor<AnalysisConsumer> {
153  enum {
154  AM_None = 0,
155  AM_Syntax = 0x1,
156  AM_Path = 0x2
157  };
158  typedef unsigned AnalysisMode;
159 
160  /// Mode of the analyzes while recursively visiting Decls.
161  AnalysisMode RecVisitorMode;
162  /// Bug Reporter to use while recursively visiting Decls.
163  BugReporter *RecVisitorBR;
164 
165  std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
166 
167 public:
168  ASTContext *Ctx;
169  const Preprocessor &PP;
170  const std::string OutDir;
171  AnalyzerOptionsRef Opts;
172  ArrayRef<std::string> Plugins;
173  CodeInjector *Injector;
175 
176  /// Stores the declarations from the local translation unit.
177  /// Note, we pre-compute the local declarations at parse time as an
178  /// optimization to make sure we do not deserialize everything from disk.
179  /// The local declaration to all declarations ratio might be very small when
180  /// working with a PCH file.
181  SetOfDecls LocalTUDecls;
182 
183  // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
184  PathDiagnosticConsumers PathConsumers;
185 
186  StoreManagerCreator CreateStoreMgr;
187  ConstraintManagerCreator CreateConstraintMgr;
188 
189  std::unique_ptr<CheckerManager> checkerMgr;
190  std::unique_ptr<AnalysisManager> Mgr;
191 
192  /// Time the analyzes time of each translation unit.
193  std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
194  std::unique_ptr<llvm::Timer> TUTotalTimer;
195 
196  /// The information about analyzed functions shared throughout the
197  /// translation unit.
198  FunctionSummariesTy FunctionSummaries;
199 
200  AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
202  CodeInjector *injector)
203  : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
204  PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
205  Plugins(plugins), Injector(injector), CTU(CI) {
206  DigestAnalyzerOptions();
207  if (Opts->PrintStats || Opts->shouldSerializeStats()) {
208  AnalyzerTimers = llvm::make_unique<llvm::TimerGroup>(
209  "analyzer", "Analyzer timers");
210  TUTotalTimer = llvm::make_unique<llvm::Timer>(
211  "time", "Analyzer total time", *AnalyzerTimers);
212  llvm::EnableStatistics(/* PrintOnExit= */ false);
213  }
214  }
215 
216  ~AnalysisConsumer() override {
217  if (Opts->PrintStats) {
218  llvm::PrintStatistics();
219  }
220  }
221 
222  void DigestAnalyzerOptions() {
223  if (Opts->AnalysisDiagOpt != PD_NONE) {
224  // Create the PathDiagnosticConsumer.
225  ClangDiagPathDiagConsumer *clangDiags =
226  new ClangDiagPathDiagConsumer(PP.getDiagnostics());
227  PathConsumers.push_back(clangDiags);
228 
229  if (Opts->AnalysisDiagOpt == PD_TEXT) {
230  clangDiags->enablePaths();
231 
232  } else if (!OutDir.empty()) {
233  switch (Opts->AnalysisDiagOpt) {
234  default:
235 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
236  case PD_##NAME: \
237  CREATEFN(*Opts.get(), PathConsumers, OutDir, PP); \
238  break;
239 #include "clang/StaticAnalyzer/Core/Analyses.def"
240  }
241  }
242  }
243 
244  // Create the analyzer component creators.
245  switch (Opts->AnalysisStoreOpt) {
246  default:
247  llvm_unreachable("Unknown store manager.");
248 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN) \
249  case NAME##Model: CreateStoreMgr = CREATEFN; break;
250 #include "clang/StaticAnalyzer/Core/Analyses.def"
251  }
252 
253  switch (Opts->AnalysisConstraintsOpt) {
254  default:
255  llvm_unreachable("Unknown constraint manager.");
256 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
257  case NAME##Model: CreateConstraintMgr = CREATEFN; break;
258 #include "clang/StaticAnalyzer/Core/Analyses.def"
259  }
260  }
261 
262  void DisplayFunction(const Decl *D, AnalysisMode Mode,
264  if (!Opts->AnalyzerDisplayProgress)
265  return;
266 
267  SourceManager &SM = Mgr->getASTContext().getSourceManager();
268  PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
269  if (Loc.isValid()) {
270  llvm::errs() << "ANALYZE";
271 
272  if (Mode == AM_Syntax)
273  llvm::errs() << " (Syntax)";
274  else if (Mode == AM_Path) {
275  llvm::errs() << " (Path, ";
276  switch (IMode) {
278  llvm::errs() << " Inline_Minimal";
279  break;
281  llvm::errs() << " Inline_Regular";
282  break;
283  }
284  llvm::errs() << ")";
285  }
286  else
287  assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
288 
289  llvm::errs() << ": " << Loc.getFilename() << ' '
290  << getFunctionName(D) << '\n';
291  }
292  }
293 
294  void Initialize(ASTContext &Context) override {
295  Ctx = &Context;
296  checkerMgr = createCheckerManager(
297  *Ctx, *Opts, Plugins, CheckerRegistrationFns, PP.getDiagnostics());
298 
299  Mgr = llvm::make_unique<AnalysisManager>(
300  *Ctx, PP.getDiagnostics(), PathConsumers, CreateStoreMgr,
301  CreateConstraintMgr, checkerMgr.get(), *Opts, Injector);
302  }
303 
304  /// Store the top level decls in the set to be processed later on.
305  /// (Doing this pre-processing avoids deserialization of data from PCH.)
306  bool HandleTopLevelDecl(DeclGroupRef D) override;
307  void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
308 
309  void HandleTranslationUnit(ASTContext &C) override;
310 
311  /// Determine which inlining mode should be used when this function is
312  /// analyzed. This allows to redefine the default inlining policies when
313  /// analyzing a given function.
315  getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
316 
317  /// Build the call graph for all the top level decls of this TU and
318  /// use it to define the order in which the functions should be visited.
319  void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
320 
321  /// Run analyzes(syntax or path sensitive) on the given function.
322  /// \param Mode - determines if we are requesting syntax only or path
323  /// sensitive only analysis.
324  /// \param VisitedCallees - The output parameter, which is populated with the
325  /// set of functions which should be considered analyzed after analyzing the
326  /// given root function.
327  void HandleCode(Decl *D, AnalysisMode Mode,
329  SetOfConstDecls *VisitedCallees = nullptr);
330 
331  void RunPathSensitiveChecks(Decl *D,
333  SetOfConstDecls *VisitedCallees);
334 
335  /// Visitors for the RecursiveASTVisitor.
336  bool shouldWalkTypesOfTypeLocs() const { return false; }
337 
338  /// Handle callbacks for arbitrary Decls.
339  bool VisitDecl(Decl *D) {
340  AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
341  if (Mode & AM_Syntax)
342  checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
343  return true;
344  }
345 
346  bool VisitFunctionDecl(FunctionDecl *FD) {
347  IdentifierInfo *II = FD->getIdentifier();
348  if (II && II->getName().startswith("__inline"))
349  return true;
350 
351  // We skip function template definitions, as their semantics is
352  // only determined when they are instantiated.
353  if (FD->isThisDeclarationADefinition() &&
354  !FD->isDependentContext()) {
355  assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
356  HandleCode(FD, RecVisitorMode);
357  }
358  return true;
359  }
360 
361  bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
362  if (MD->isThisDeclarationADefinition()) {
363  assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
364  HandleCode(MD, RecVisitorMode);
365  }
366  return true;
367  }
368 
369  bool VisitBlockDecl(BlockDecl *BD) {
370  if (BD->hasBody()) {
371  assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
372  // Since we skip function template definitions, we should skip blocks
373  // declared in those functions as well.
374  if (!BD->isDependentContext()) {
375  HandleCode(BD, RecVisitorMode);
376  }
377  }
378  return true;
379  }
380 
381  void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
382  PathConsumers.push_back(Consumer);
383  }
384 
385  void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
386  CheckerRegistrationFns.push_back(std::move(Fn));
387  }
388 
389 private:
390  void storeTopLevelDecls(DeclGroupRef DG);
391  std::string getFunctionName(const Decl *D);
392 
393  /// Check if we should skip (not analyze) the given function.
394  AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
395  void runAnalysisOnTranslationUnit(ASTContext &C);
396 
397  /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
398  void reportAnalyzerProgress(StringRef S);
399 };
400 } // end anonymous namespace
401 
402 
403 //===----------------------------------------------------------------------===//
404 // AnalysisConsumer implementation.
405 //===----------------------------------------------------------------------===//
406 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
407  storeTopLevelDecls(DG);
408  return true;
409 }
410 
411 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
412  storeTopLevelDecls(DG);
413 }
414 
415 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
416  for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
417 
418  // Skip ObjCMethodDecl, wait for the objc container to avoid
419  // analyzing twice.
420  if (isa<ObjCMethodDecl>(*I))
421  continue;
422 
423  LocalTUDecls.push_back(*I);
424  }
425 }
426 
427 static bool shouldSkipFunction(const Decl *D,
428  const SetOfConstDecls &Visited,
429  const SetOfConstDecls &VisitedAsTopLevel) {
430  if (VisitedAsTopLevel.count(D))
431  return true;
432 
433  // We want to re-analyse the functions as top level in the following cases:
434  // - The 'init' methods should be reanalyzed because
435  // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
436  // 'nil' and unless we analyze the 'init' functions as top level, we will
437  // not catch errors within defensive code.
438  // - We want to reanalyze all ObjC methods as top level to report Retain
439  // Count naming convention errors more aggressively.
440  if (isa<ObjCMethodDecl>(D))
441  return false;
442  // We also want to reanalyze all C++ copy and move assignment operators to
443  // separately check the two cases where 'this' aliases with the parameter and
444  // where it may not. (cplusplus.SelfAssignmentChecker)
445  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
446  if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
447  return false;
448  }
449 
450  // Otherwise, if we visited the function before, do not reanalyze it.
451  return Visited.count(D);
452 }
453 
455 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
456  const SetOfConstDecls &Visited) {
457  // We want to reanalyze all ObjC methods as top level to report Retain
458  // Count naming convention errors more aggressively. But we should tune down
459  // inlining when reanalyzing an already inlined function.
460  if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
461  const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
462  if (ObjCM->getMethodFamily() != OMF_init)
464  }
465 
467 }
468 
469 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
470  // Build the Call Graph by adding all the top level declarations to the graph.
471  // Note: CallGraph can trigger deserialization of more items from a pch
472  // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
473  // We rely on random access to add the initially processed Decls to CG.
474  CallGraph CG;
475  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
476  CG.addToCallGraph(LocalTUDecls[i]);
477  }
478 
479  // Walk over all of the call graph nodes in topological order, so that we
480  // analyze parents before the children. Skip the functions inlined into
481  // the previously processed functions. Use external Visited set to identify
482  // inlined functions. The topological order allows the "do not reanalyze
483  // previously inlined function" performance heuristic to be triggered more
484  // often.
485  SetOfConstDecls Visited;
486  SetOfConstDecls VisitedAsTopLevel;
487  llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
488  for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
489  I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
490  NumFunctionTopLevel++;
491 
492  CallGraphNode *N = *I;
493  Decl *D = N->getDecl();
494 
495  // Skip the abstract root node.
496  if (!D)
497  continue;
498 
499  // Skip the functions which have been processed already or previously
500  // inlined.
501  if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
502  continue;
503 
504  // Analyze the function.
505  SetOfConstDecls VisitedCallees;
506 
507  HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
508  (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
509 
510  // Add the visited callees to the global visited set.
511  for (const Decl *Callee : VisitedCallees)
512  // Decls from CallGraph are already canonical. But Decls coming from
513  // CallExprs may be not. We should canonicalize them manually.
514  Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
515  : Callee->getCanonicalDecl());
516  VisitedAsTopLevel.insert(D);
517  }
518 }
519 
520 static bool isBisonFile(ASTContext &C) {
521  const SourceManager &SM = C.getSourceManager();
522  FileID FID = SM.getMainFileID();
523  StringRef Buffer = SM.getBuffer(FID)->getBuffer();
524  if (Buffer.startswith("/* A Bison parser, made by"))
525  return true;
526  return false;
527 }
528 
529 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
530  BugReporter BR(*Mgr);
532  checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
533 
534  // Run the AST-only checks using the order in which functions are defined.
535  // If inlining is not turned on, use the simplest function order for path
536  // sensitive analyzes as well.
537  RecVisitorMode = AM_Syntax;
538  if (!Mgr->shouldInlineCall())
539  RecVisitorMode |= AM_Path;
540  RecVisitorBR = &BR;
541 
542  // Process all the top level declarations.
543  //
544  // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
545  // entries. Thus we don't use an iterator, but rely on LocalTUDecls
546  // random access. By doing so, we automatically compensate for iterators
547  // possibly being invalidated, although this is a bit slower.
548  const unsigned LocalTUDeclsSize = LocalTUDecls.size();
549  for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
550  TraverseDecl(LocalTUDecls[i]);
551  }
552 
553  if (Mgr->shouldInlineCall())
554  HandleDeclsCallGraph(LocalTUDeclsSize);
555 
556  // After all decls handled, run checkers on the entire TranslationUnit.
557  checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
558 
559  RecVisitorBR = nullptr;
560 }
561 
562 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
563  if (Opts->AnalyzerDisplayProgress)
564  llvm::errs() << S;
565 }
566 
567 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
568 
569  // Don't run the actions if an error has occurred with parsing the file.
570  DiagnosticsEngine &Diags = PP.getDiagnostics();
571  if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
572  return;
573 
574  if (TUTotalTimer) TUTotalTimer->startTimer();
575 
576  if (isBisonFile(C)) {
577  reportAnalyzerProgress("Skipping bison-generated file\n");
578  } else if (Opts->DisableAllChecks) {
579 
580  // Don't analyze if the user explicitly asked for no checks to be performed
581  // on this file.
582  reportAnalyzerProgress("All checks are disabled using a supplied option\n");
583  } else {
584  // Otherwise, just run the analysis.
585  runAnalysisOnTranslationUnit(C);
586  }
587 
588  if (TUTotalTimer) TUTotalTimer->stopTimer();
589 
590  // Count how many basic blocks we have not covered.
591  NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
592  NumVisitedBlocksInAnalyzedFunctions =
593  FunctionSummaries.getTotalNumVisitedBasicBlocks();
594  if (NumBlocksInAnalyzedFunctions > 0)
595  PercentReachableBlocks =
596  (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
597  NumBlocksInAnalyzedFunctions;
598 
599  // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
600  // FIXME: This should be replaced with something that doesn't rely on
601  // side-effects in PathDiagnosticConsumer's destructor. This is required when
602  // used with option -disable-free.
603  Mgr.reset();
604 }
605 
606 std::string AnalysisConsumer::getFunctionName(const Decl *D) {
607  std::string Str;
608  llvm::raw_string_ostream OS(Str);
609 
610  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
611  OS << FD->getQualifiedNameAsString();
612 
613  // In C++, there are overloads.
614  if (Ctx->getLangOpts().CPlusPlus) {
615  OS << '(';
616  for (const auto &P : FD->parameters()) {
617  if (P != *FD->param_begin())
618  OS << ", ";
619  OS << P->getType().getAsString();
620  }
621  OS << ')';
622  }
623 
624  } else if (isa<BlockDecl>(D)) {
625  PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
626 
627  if (Loc.isValid()) {
628  OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
629  << ')';
630  }
631 
632  } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
633 
634  // FIXME: copy-pasted from CGDebugInfo.cpp.
635  OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
636  const DeclContext *DC = OMD->getDeclContext();
637  if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
638  OS << OID->getName();
639  } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
640  OS << OID->getName();
641  } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
642  if (OC->IsClassExtension()) {
643  OS << OC->getClassInterface()->getName();
644  } else {
645  OS << OC->getIdentifier()->getNameStart() << '('
646  << OC->getIdentifier()->getNameStart() << ')';
647  }
648  } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
649  OS << OCD->getClassInterface()->getName() << '('
650  << OCD->getName() << ')';
651  } else if (isa<ObjCProtocolDecl>(DC)) {
652  // We can extract the type of the class from the self pointer.
653  if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
654  QualType ClassTy =
655  cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
656  ClassTy.print(OS, PrintingPolicy(LangOptions()));
657  }
658  }
659  OS << ' ' << OMD->getSelector().getAsString() << ']';
660 
661  }
662 
663  return OS.str();
664 }
665 
666 AnalysisConsumer::AnalysisMode
667 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
668  if (!Opts->AnalyzeSpecificFunction.empty() &&
669  getFunctionName(D) != Opts->AnalyzeSpecificFunction)
670  return AM_None;
671 
672  // Unless -analyze-all is specified, treat decls differently depending on
673  // where they came from:
674  // - Main source file: run both path-sensitive and non-path-sensitive checks.
675  // - Header files: run non-path-sensitive checks only.
676  // - System headers: don't run any checks.
677  SourceManager &SM = Ctx->getSourceManager();
678  const Stmt *Body = D->getBody();
679  SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
680  SL = SM.getExpansionLoc(SL);
681 
682  if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
683  if (SL.isInvalid() || SM.isInSystemHeader(SL))
684  return AM_None;
685  return Mode & ~AM_Path;
686  }
687 
688  return Mode;
689 }
690 
691 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
693  SetOfConstDecls *VisitedCallees) {
694  if (!D->hasBody())
695  return;
696  Mode = getModeForDecl(D, Mode);
697  if (Mode == AM_None)
698  return;
699 
700  // Clear the AnalysisManager of old AnalysisDeclContexts.
701  Mgr->ClearContexts();
702  // Ignore autosynthesized code.
703  if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
704  return;
705 
706  DisplayFunction(D, Mode, IMode);
707  CFG *DeclCFG = Mgr->getCFG(D);
708  if (DeclCFG)
709  MaxCFGSize.updateMax(DeclCFG->size());
710 
711  BugReporter BR(*Mgr);
712 
713  if (Mode & AM_Syntax)
714  checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
715  if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
716  RunPathSensitiveChecks(D, IMode, VisitedCallees);
717  if (IMode != ExprEngine::Inline_Minimal)
718  NumFunctionsAnalyzed++;
719  }
720 }
721 
722 //===----------------------------------------------------------------------===//
723 // Path-sensitive checking.
724 //===----------------------------------------------------------------------===//
725 
726 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
728  SetOfConstDecls *VisitedCallees) {
729  // Construct the analysis engine. First check if the CFG is valid.
730  // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
731  if (!Mgr->getCFG(D))
732  return;
733 
734  // See if the LiveVariables analysis scales.
735  if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
736  return;
737 
738  ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
739 
740  // Execute the worklist algorithm.
741  Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
742  Mgr->options.getMaxNodesPerTopLevelFunction());
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  Eng.getBugReporter().FlushReports();
753 }
754 
755 //===----------------------------------------------------------------------===//
756 // AnalysisConsumer creation.
757 //===----------------------------------------------------------------------===//
758 
759 std::unique_ptr<AnalysisASTConsumer>
761  // Disable the effects of '-Werror' when using the AnalysisConsumer.
763 
764  AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
765  bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
766 
767  return llvm::make_unique<AnalysisConsumer>(
768  CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
769  CI.getFrontendOpts().Plugins,
770  hasModelPath ? new ModelInjector(CI) : nullptr);
771 }
The AST-based call graph.
Definition: CallGraph.h:42
std::string OutputFile
The output file, if any.
Represents a function declaration or definition.
Definition: Decl.h:1732
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition: DeclObjC.h:507
bool hasErrorOccurred() const
Definition: Diagnostic.h:746
A (possibly-)qualified type.
Definition: Type.h:642
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
Definition: Type.h:985
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:979
Stmt - This represents one statement.
Definition: Stmt.h:66
unsigned size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
Definition: CFG.h:1174
Defines the SourceManager interface.
iterator end()
Definition: DeclGroup.h:106
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:87
StringRef P
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1294
std::unique_ptr< CheckerManager > createCheckerManager(ASTContext &context, AnalyzerOptions &opts, ArrayRef< std::string > plugins, ArrayRef< std::function< void(CheckerRegistry &)>> checkerRegistrationFns, DiagnosticsEngine &diags)
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
One of these records is kept for each identifier that is lexed.
Follow the default settings for inlining callees.
Definition: ExprEngine.h:89
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:280
Definition: Format.h:2073
std::unique_ptr< StoreManager >(* StoreManagerCreator)(ProgramStateManager &)
Definition: ProgramState.h:45
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2246
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:986
FrontendOptions & getFrontendOpts()
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:149
iterator begin()
Definition: DeclGroup.h:100
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
AnalyzerOptionsRef getAnalyzerOpts()
Decl * getDecl() const
Definition: CallGraph.h:173
param_iterator param_begin()
Definition: Decl.h:2258
llvm::DenseSet< const Decl * > SetOfConstDecls
std::unique_ptr< ConstraintManager >(* ConstraintManagerCreator)(ProgramStateManager &, SubEngine *)
Definition: ProgramState.h:43
static bool shouldSkipFunction(const Decl *D, const SetOfConstDecls &Visited, const SetOfConstDecls &VisitedAsTopLevel)
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition: ExprEngine.h:87
bool isValid() const
Pepresents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:3850
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt...
Definition: CFG.h:1003
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
unsigned getLine() const
Return the presumed line number of this location.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:1977
Defines the clang::Preprocessor interface.
This file defines the clang::ento::ModelInjector class which implements the clang::CodeInjector inter...
Represents an unpacked "presumed" location which can be presented to the user.
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1081
const SourceManager & SM
Definition: Format.cpp:1490
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:985
const char * getFilename() const
Return the presumed filename of this location.
#define false
Definition: stdbool.h:33
llvm::MemoryBuffer * getBuffer(FileID FID, SourceLocation Loc, bool *Invalid=nullptr) const
Return the buffer for the specified FileID.
unsigned getColumn() const
Return the presumed column number of this location.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
Encodes a location in the source.
STATISTIC(NumFunctionTopLevel, "The # of functions at top level.")
std::vector< PathDiagnosticConsumer * > PathDiagnosticConsumers
Do minimal inlining of callees.
Definition: ExprEngine.h:92
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:775
StringRef getName() const
Return the actual identifier string.
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Dataflow Directional Tag Classes.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1261
CodeInjector is an interface which is responsible for injecting AST of function definitions that may ...
Definition: CodeInjector.h:36
FileID getMainFileID() const
Returns the FileID of the main source file.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
This class is used for tools that requires cross translation unit capability.
std::unique_ptr< AnalysisASTConsumer > CreateAnalysisConsumer(CompilerInstance &CI)
CreateAnalysisConsumer - Creates an ASTConsumer to run various code analysis passes.
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition: Diagnostic.h:606
SourceManager & getSourceManager()
Definition: ASTContext.h:671
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:753
Preprocessor & getPreprocessor() const
Return the current preprocessor.
static bool isBisonFile(ASTContext &C)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1018
DiagnosticsEngine & getDiagnostics() const
Definition: Preprocessor.h:824
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
Definition: CallGraph.h:62
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1520
The top declaration context.
Definition: Decl.h:107
std::deque< Decl * > SetOfDecls
This class handles loading and caching of source files into memory.
SourceLocation getLocation() const
Definition: DeclBase.h:418
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127