1 //===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // "Meta" ASTConsumer for running different source analyses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/StaticAnalyzer/Frontend/AnalysisConsumer.h"
14 #include "ModelInjector.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/Analysis/Analyses/LiveVariables.h"
20 #include "clang/Analysis/CFG.h"
21 #include "clang/Analysis/CallGraph.h"
22 #include "clang/Analysis/CodeInjector.h"
23 #include "clang/Analysis/MacroExpansionContext.h"
24 #include "clang/Analysis/PathDiagnostic.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/CrossTU/CrossTranslationUnit.h"
27 #include "clang/Frontend/CompilerInstance.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Rewrite/Core/Rewriter.h"
30 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
31 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
32 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
33 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
34 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
35 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
36 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.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;
94   cross_tu::CrossTranslationUnitContext CTU;
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,
125                    AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
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     CreateStoreMgr = &CreateRegionStoreManager;
175 
176     switch (Opts->AnalysisConstraintsOpt) {
177     default:
178       llvm_unreachable("Unknown constraint manager.");
179 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
180       case NAME##Model: CreateConstraintMgr = CREATEFN; break;
181 #include "clang/StaticAnalyzer/Core/Analyses.def"
182     }
183   }
184 
185   void DisplayTime(llvm::TimeRecord &Time) {
186     if (!Opts->AnalyzerDisplayProgress) {
187       return;
188     }
189     llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)
190                  << " ms\n";
191   }
192 
193   void DisplayFunction(const Decl *D, AnalysisMode Mode,
194                        ExprEngine::InliningModes IMode) {
195     if (!Opts->AnalyzerDisplayProgress)
196       return;
197 
198     SourceManager &SM = Mgr->getASTContext().getSourceManager();
199     PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
200     if (Loc.isValid()) {
201       llvm::errs() << "ANALYZE";
202 
203       if (Mode == AM_Syntax)
204         llvm::errs() << " (Syntax)";
205       else if (Mode == AM_Path) {
206         llvm::errs() << " (Path, ";
207         switch (IMode) {
208         case ExprEngine::Inline_Minimal:
209           llvm::errs() << " Inline_Minimal";
210           break;
211         case ExprEngine::Inline_Regular:
212           llvm::errs() << " Inline_Regular";
213           break;
214         }
215         llvm::errs() << ")";
216       } else
217         assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
218 
219       llvm::errs() << ": " << Loc.getFilename() << ' '
220                    << AnalysisDeclContext::getFunctionName(D);
221     }
222   }
223 
224   void Initialize(ASTContext &Context) override {
225     Ctx = &Context;
226     checkerMgr = std::make_unique<CheckerManager>(*Ctx, *Opts, PP, Plugins,
227                                                   CheckerRegistrationFns);
228 
229     Mgr = std::make_unique<AnalysisManager>(*Ctx, PP, PathConsumers,
230                                             CreateStoreMgr, CreateConstraintMgr,
231                                             checkerMgr.get(), *Opts, Injector);
232   }
233 
234   /// Store the top level decls in the set to be processed later on.
235   /// (Doing this pre-processing avoids deserialization of data from PCH.)
236   bool HandleTopLevelDecl(DeclGroupRef D) override;
237   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
238 
239   void HandleTranslationUnit(ASTContext &C) override;
240 
241   /// Determine which inlining mode should be used when this function is
242   /// analyzed. This allows to redefine the default inlining policies when
243   /// analyzing a given function.
244   ExprEngine::InliningModes
245     getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
246 
247   /// Build the call graph for all the top level decls of this TU and
248   /// use it to define the order in which the functions should be visited.
249   void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
250 
251   /// Run analyzes(syntax or path sensitive) on the given function.
252   /// \param Mode - determines if we are requesting syntax only or path
253   /// sensitive only analysis.
254   /// \param VisitedCallees - The output parameter, which is populated with the
255   /// set of functions which should be considered analyzed after analyzing the
256   /// given root function.
257   void HandleCode(Decl *D, AnalysisMode Mode,
258                   ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
259                   SetOfConstDecls *VisitedCallees = nullptr);
260 
261   void RunPathSensitiveChecks(Decl *D,
262                               ExprEngine::InliningModes IMode,
263                               SetOfConstDecls *VisitedCallees);
264 
265   /// Visitors for the RecursiveASTVisitor.
266   bool shouldWalkTypesOfTypeLocs() const { return false; }
267 
268   /// Handle callbacks for arbitrary Decls.
269   bool VisitDecl(Decl *D) {
270     AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
271     if (Mode & AM_Syntax) {
272       if (SyntaxCheckTimer)
273         SyntaxCheckTimer->startTimer();
274       checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
275       if (SyntaxCheckTimer)
276         SyntaxCheckTimer->stopTimer();
277     }
278     return true;
279   }
280 
281   bool VisitVarDecl(VarDecl *VD) {
282     if (!Opts->IsNaiveCTUEnabled)
283       return true;
284 
285     if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
286       if (!cross_tu::shouldImport(VD, *Ctx))
287         return true;
288     } else {
289       // Cannot be initialized in another TU.
290       return true;
291     }
292 
293     if (VD->getAnyInitializer())
294       return true;
295 
296     llvm::Expected<const VarDecl *> CTUDeclOrError =
297       CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName,
298                                Opts->DisplayCTUProgress);
299 
300     if (!CTUDeclOrError) {
301       handleAllErrors(CTUDeclOrError.takeError(),
302                       [&](const cross_tu::IndexError &IE) {
303                         CTU.emitCrossTUDiagnostics(IE);
304                       });
305     }
306 
307     return true;
308   }
309 
310   bool VisitFunctionDecl(FunctionDecl *FD) {
311     IdentifierInfo *II = FD->getIdentifier();
312     if (II && II->getName().startswith("__inline"))
313       return true;
314 
315     // We skip function template definitions, as their semantics is
316     // only determined when they are instantiated.
317     if (FD->isThisDeclarationADefinition() &&
318         !FD->isDependentContext()) {
319       assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
320       HandleCode(FD, RecVisitorMode);
321     }
322     return true;
323   }
324 
325   bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
326     if (MD->isThisDeclarationADefinition()) {
327       assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
328       HandleCode(MD, RecVisitorMode);
329     }
330     return true;
331   }
332 
333   bool VisitBlockDecl(BlockDecl *BD) {
334     if (BD->hasBody()) {
335       assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
336       // Since we skip function template definitions, we should skip blocks
337       // declared in those functions as well.
338       if (!BD->isDependentContext()) {
339         HandleCode(BD, RecVisitorMode);
340       }
341     }
342     return true;
343   }
344 
345   void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
346     PathConsumers.push_back(Consumer);
347   }
348 
349   void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
350     CheckerRegistrationFns.push_back(std::move(Fn));
351   }
352 
353 private:
354   void storeTopLevelDecls(DeclGroupRef DG);
355   std::string getFunctionName(const Decl *D);
356 
357   /// Check if we should skip (not analyze) the given function.
358   AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
359   void runAnalysisOnTranslationUnit(ASTContext &C);
360 
361   /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
362   void reportAnalyzerProgress(StringRef S);
363 }; // namespace
364 } // end anonymous namespace
365 
366 
367 //===----------------------------------------------------------------------===//
368 // AnalysisConsumer implementation.
369 //===----------------------------------------------------------------------===//
370 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
371   storeTopLevelDecls(DG);
372   return true;
373 }
374 
375 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
376   storeTopLevelDecls(DG);
377 }
378 
379 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
380   for (auto &I : DG) {
381 
382     // Skip ObjCMethodDecl, wait for the objc container to avoid
383     // analyzing twice.
384     if (isa<ObjCMethodDecl>(I))
385       continue;
386 
387     LocalTUDecls.push_back(I);
388   }
389 }
390 
391 static bool shouldSkipFunction(const Decl *D,
392                                const SetOfConstDecls &Visited,
393                                const SetOfConstDecls &VisitedAsTopLevel) {
394   if (VisitedAsTopLevel.count(D))
395     return true;
396 
397   // Skip analysis of inheriting constructors as top-level functions. These
398   // constructors don't even have a body written down in the code, so even if
399   // we find a bug, we won't be able to display it.
400   if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
401     if (CD->isInheritingConstructor())
402       return true;
403 
404   // We want to re-analyse the functions as top level in the following cases:
405   // - The 'init' methods should be reanalyzed because
406   //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
407   //   'nil' and unless we analyze the 'init' functions as top level, we will
408   //   not catch errors within defensive code.
409   // - We want to reanalyze all ObjC methods as top level to report Retain
410   //   Count naming convention errors more aggressively.
411   if (isa<ObjCMethodDecl>(D))
412     return false;
413   // We also want to reanalyze all C++ copy and move assignment operators to
414   // separately check the two cases where 'this' aliases with the parameter and
415   // where it may not. (cplusplus.SelfAssignmentChecker)
416   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
417     if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
418       return false;
419   }
420 
421   // Otherwise, if we visited the function before, do not reanalyze it.
422   return Visited.count(D);
423 }
424 
425 ExprEngine::InliningModes
426 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
427                                              const SetOfConstDecls &Visited) {
428   // We want to reanalyze all ObjC methods as top level to report Retain
429   // Count naming convention errors more aggressively. But we should tune down
430   // inlining when reanalyzing an already inlined function.
431   if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
432     const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
433     if (ObjCM->getMethodFamily() != OMF_init)
434       return ExprEngine::Inline_Minimal;
435   }
436 
437   return ExprEngine::Inline_Regular;
438 }
439 
440 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
441   // Build the Call Graph by adding all the top level declarations to the graph.
442   // Note: CallGraph can trigger deserialization of more items from a pch
443   // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
444   // We rely on random access to add the initially processed Decls to CG.
445   CallGraph CG;
446   for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
447     CG.addToCallGraph(LocalTUDecls[i]);
448   }
449 
450   // Walk over all of the call graph nodes in topological order, so that we
451   // analyze parents before the children. Skip the functions inlined into
452   // the previously processed functions. Use external Visited set to identify
453   // inlined functions. The topological order allows the "do not reanalyze
454   // previously inlined function" performance heuristic to be triggered more
455   // often.
456   SetOfConstDecls Visited;
457   SetOfConstDecls VisitedAsTopLevel;
458   llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
459   for (auto &N : RPOT) {
460     NumFunctionTopLevel++;
461 
462     Decl *D = N->getDecl();
463 
464     // Skip the abstract root node.
465     if (!D)
466       continue;
467 
468     // Skip the functions which have been processed already or previously
469     // inlined.
470     if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
471       continue;
472 
473     // The CallGraph might have declarations as callees. However, during CTU
474     // the declaration might form a declaration chain with the newly imported
475     // definition from another TU. In this case we don't want to analyze the
476     // function definition as toplevel.
477     if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
478       // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
479       // that has the body.
480       FD->hasBody(FD);
481       if (CTU.isImportedAsNew(FD))
482         continue;
483     }
484 
485     // Analyze the function.
486     SetOfConstDecls VisitedCallees;
487 
488     HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
489                (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
490 
491     // Add the visited callees to the global visited set.
492     for (const Decl *Callee : VisitedCallees)
493       // Decls from CallGraph are already canonical. But Decls coming from
494       // CallExprs may be not. We should canonicalize them manually.
495       Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
496                                                  : Callee->getCanonicalDecl());
497     VisitedAsTopLevel.insert(D);
498   }
499 }
500 
501 static bool fileContainsString(StringRef Substring, ASTContext &C) {
502   const SourceManager &SM = C.getSourceManager();
503   FileID FID = SM.getMainFileID();
504   StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
505   return Buffer.contains(Substring);
506 }
507 
508 static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts,
509                                          const ASTContext &Ctx) {
510   llvm::errs() << "Every top-level function was skipped.\n";
511 
512   if (!Opts.AnalyzerDisplayProgress)
513     llvm::errs() << "Pass the -analyzer-display-progress for tracking which "
514                     "functions are analyzed.\n";
515 
516   bool HasBrackets =
517       Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;
518 
519   if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {
520     llvm::errs()
521         << "For analyzing C++ code you need to pass the function parameter "
522            "list: -analyze-function=\"foobar(int, _Bool)\"\n";
523   } else if (!Ctx.getLangOpts().CPlusPlus && HasBrackets) {
524     llvm::errs() << "For analyzing C code you shouldn't pass the function "
525                     "parameter list, only the name of the function: "
526                     "-analyze-function=foobar\n";
527   }
528 }
529 
530 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
531   BugReporter BR(*Mgr);
532   TranslationUnitDecl *TU = C.getTranslationUnitDecl();
533   if (SyntaxCheckTimer)
534     SyntaxCheckTimer->startTimer();
535   checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
536   if (SyntaxCheckTimer)
537     SyntaxCheckTimer->stopTimer();
538 
539   // Run the AST-only checks using the order in which functions are defined.
540   // If inlining is not turned on, use the simplest function order for path
541   // sensitive analyzes as well.
542   RecVisitorMode = AM_Syntax;
543   if (!Mgr->shouldInlineCall())
544     RecVisitorMode |= AM_Path;
545   RecVisitorBR = &BR;
546 
547   // Process all the top level declarations.
548   //
549   // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
550   // entries.  Thus we don't use an iterator, but rely on LocalTUDecls
551   // random access.  By doing so, we automatically compensate for iterators
552   // possibly being invalidated, although this is a bit slower.
553   const unsigned LocalTUDeclsSize = LocalTUDecls.size();
554   for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
555     TraverseDecl(LocalTUDecls[i]);
556   }
557 
558   if (Mgr->shouldInlineCall())
559     HandleDeclsCallGraph(LocalTUDeclsSize);
560 
561   // After all decls handled, run checkers on the entire TranslationUnit.
562   checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
563 
564   BR.FlushReports();
565   RecVisitorBR = nullptr;
566 
567   // If the user wanted to analyze a specific function and the number of basic
568   // blocks analyzed is zero, than the user might not specified the function
569   // name correctly.
570   // FIXME: The user might have analyzed the requested function in Syntax mode,
571   // but we are unaware of that.
572   if (!Opts->AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0)
573     reportAnalyzerFunctionMisuse(*Opts, *Ctx);
574 }
575 
576 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
577   if (Opts->AnalyzerDisplayProgress)
578     llvm::errs() << S;
579 }
580 
581 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
582   // Don't run the actions if an error has occurred with parsing the file.
583   DiagnosticsEngine &Diags = PP.getDiagnostics();
584   if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
585     return;
586 
587   // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
588   // FIXME: This should be replaced with something that doesn't rely on
589   // side-effects in PathDiagnosticConsumer's destructor. This is required when
590   // used with option -disable-free.
591   const auto DiagFlusherScopeExit =
592       llvm::make_scope_exit([this] { Mgr.reset(); });
593 
594   if (Opts->ShouldIgnoreBisonGeneratedFiles &&
595       fileContainsString("/* A Bison parser, made by", C)) {
596     reportAnalyzerProgress("Skipping bison-generated file\n");
597     return;
598   }
599 
600   if (Opts->ShouldIgnoreFlexGeneratedFiles &&
601       fileContainsString("/* A lexical scanner generated by flex", C)) {
602     reportAnalyzerProgress("Skipping flex-generated file\n");
603     return;
604   }
605 
606   // Don't analyze if the user explicitly asked for no checks to be performed
607   // on this file.
608   if (Opts->DisableAllCheckers) {
609     reportAnalyzerProgress("All checks are disabled using a supplied option\n");
610     return;
611   }
612 
613   // Otherwise, just run the analysis.
614   runAnalysisOnTranslationUnit(C);
615 
616   // Count how many basic blocks we have not covered.
617   NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
618   NumVisitedBlocksInAnalyzedFunctions =
619       FunctionSummaries.getTotalNumVisitedBasicBlocks();
620   if (NumBlocksInAnalyzedFunctions > 0)
621     PercentReachableBlocks =
622         (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
623         NumBlocksInAnalyzedFunctions;
624 }
625 
626 AnalysisConsumer::AnalysisMode
627 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
628   if (!Opts->AnalyzeSpecificFunction.empty() &&
629       AnalysisDeclContext::getFunctionName(D) != Opts->AnalyzeSpecificFunction)
630     return AM_None;
631 
632   // Unless -analyze-all is specified, treat decls differently depending on
633   // where they came from:
634   // - Main source file: run both path-sensitive and non-path-sensitive checks.
635   // - Header files: run non-path-sensitive checks only.
636   // - System headers: don't run any checks.
637   if (Opts->AnalyzeAll)
638     return Mode;
639 
640   const SourceManager &SM = Ctx->getSourceManager();
641 
642   const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
643     const Stmt *Body = D->getBody();
644     SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
645     return SM.getExpansionLoc(SL);
646   }(D);
647 
648   // Ignore system headers.
649   if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
650     return AM_None;
651 
652   // Disable path sensitive analysis in user-headers.
653   if (!Mgr->isInCodeFile(Loc))
654     return Mode & ~AM_Path;
655 
656   return Mode;
657 }
658 
659 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
660                                   ExprEngine::InliningModes IMode,
661                                   SetOfConstDecls *VisitedCallees) {
662   if (!D->hasBody())
663     return;
664   Mode = getModeForDecl(D, Mode);
665   if (Mode == AM_None)
666     return;
667 
668   // Clear the AnalysisManager of old AnalysisDeclContexts.
669   Mgr->ClearContexts();
670   // Ignore autosynthesized code.
671   if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
672     return;
673 
674   CFG *DeclCFG = Mgr->getCFG(D);
675   if (DeclCFG)
676     MaxCFGSize.updateMax(DeclCFG->size());
677 
678   DisplayFunction(D, Mode, IMode);
679   BugReporter BR(*Mgr);
680 
681   if (Mode & AM_Syntax) {
682     llvm::TimeRecord CheckerStartTime;
683     if (SyntaxCheckTimer) {
684       CheckerStartTime = SyntaxCheckTimer->getTotalTime();
685       SyntaxCheckTimer->startTimer();
686     }
687     checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
688     if (SyntaxCheckTimer) {
689       SyntaxCheckTimer->stopTimer();
690       llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
691       CheckerEndTime -= CheckerStartTime;
692       DisplayTime(CheckerEndTime);
693     }
694   }
695 
696   BR.FlushReports();
697 
698   if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
699     RunPathSensitiveChecks(D, IMode, VisitedCallees);
700     if (IMode != ExprEngine::Inline_Minimal)
701       NumFunctionsAnalyzed++;
702   }
703 }
704 
705 //===----------------------------------------------------------------------===//
706 // Path-sensitive checking.
707 //===----------------------------------------------------------------------===//
708 
709 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
710                                               ExprEngine::InliningModes IMode,
711                                               SetOfConstDecls *VisitedCallees) {
712   // Construct the analysis engine.  First check if the CFG is valid.
713   // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
714   if (!Mgr->getCFG(D))
715     return;
716 
717   // See if the LiveVariables analysis scales.
718   if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
719     return;
720 
721   ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
722 
723   // Execute the worklist algorithm.
724   llvm::TimeRecord ExprEngineStartTime;
725   if (ExprEngineTimer) {
726     ExprEngineStartTime = ExprEngineTimer->getTotalTime();
727     ExprEngineTimer->startTimer();
728   }
729   Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
730                       Mgr->options.MaxNodesPerTopLevelFunction);
731   if (ExprEngineTimer) {
732     ExprEngineTimer->stopTimer();
733     llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
734     ExprEngineEndTime -= ExprEngineStartTime;
735     DisplayTime(ExprEngineEndTime);
736   }
737 
738   if (!Mgr->options.DumpExplodedGraphTo.empty())
739     Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
740 
741   // Visualize the exploded graph.
742   if (Mgr->options.visualizeExplodedGraphWithGraphViz)
743     Eng.ViewGraph(Mgr->options.TrimGraph);
744 
745   // Display warnings.
746   if (BugReporterTimer)
747     BugReporterTimer->startTimer();
748   Eng.getBugReporter().FlushReports();
749   if (BugReporterTimer)
750     BugReporterTimer->stopTimer();
751 }
752 
753 //===----------------------------------------------------------------------===//
754 // AnalysisConsumer creation.
755 //===----------------------------------------------------------------------===//
756 
757 std::unique_ptr<AnalysisASTConsumer>
758 ento::CreateAnalysisConsumer(CompilerInstance &CI) {
759   // Disable the effects of '-Werror' when using the AnalysisConsumer.
760   CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
761 
762   AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
763   bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
764 
765   return std::make_unique<AnalysisConsumer>(
766       CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
767       CI.getFrontendOpts().Plugins,
768       hasModelPath ? new ModelInjector(CI) : nullptr);
769 }
770