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/Basic/SourceManager.h"
24 #include "clang/CrossTU/CrossTranslationUnit.h"
25 #include "clang/Frontend/CompilerInstance.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/StaticAnalyzer/Checkers/LocalCheckers.h"
28 #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
29 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
30 #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
31 #include "clang/StaticAnalyzer/Core/CheckerManager.h"
32 #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h"
33 #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
34 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
35 #include "clang/StaticAnalyzer/Frontend/CheckerRegistration.h"
36 #include "llvm/ADT/PostOrderIterator.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/FileSystem.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Program.h"
41 #include "llvm/Support/Timer.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <memory>
44 #include <queue>
45 #include <utility>
46 
47 using namespace clang;
48 using namespace ento;
49 
50 #define DEBUG_TYPE "AnalysisConsumer"
51 
52 STATISTIC(NumFunctionTopLevel, "The # of functions at top level.");
53 STATISTIC(NumFunctionsAnalyzed,
54                       "The # of functions and blocks analyzed (as top level "
55                       "with inlining turned on).");
56 STATISTIC(NumBlocksInAnalyzedFunctions,
57                       "The # of basic blocks in the analyzed functions.");
58 STATISTIC(NumVisitedBlocksInAnalyzedFunctions,
59           "The # of visited basic blocks in the analyzed functions.");
60 STATISTIC(PercentReachableBlocks, "The % of reachable basic blocks.");
61 STATISTIC(MaxCFGSize, "The maximum number of basic blocks in a function.");
62 
63 //===----------------------------------------------------------------------===//
64 // Special PathDiagnosticConsumers.
65 //===----------------------------------------------------------------------===//
66 
67 void ento::createPlistHTMLDiagnosticConsumer(
68     AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
69     const std::string &prefix, const Preprocessor &PP,
70     const cross_tu::CrossTranslationUnitContext &CTU) {
71   createHTMLDiagnosticConsumer(AnalyzerOpts, C,
72                                llvm::sys::path::parent_path(prefix), PP, CTU);
73   createPlistMultiFileDiagnosticConsumer(AnalyzerOpts, C, prefix, PP, CTU);
74 }
75 
76 void ento::createTextPathDiagnosticConsumer(
77     AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C,
78     const std::string &Prefix, const clang::Preprocessor &PP,
79     const cross_tu::CrossTranslationUnitContext &CTU) {
80   llvm_unreachable("'text' consumer should be enabled on ClangDiags");
81 }
82 
83 namespace {
84 class ClangDiagPathDiagConsumer : public PathDiagnosticConsumer {
85   DiagnosticsEngine &Diag;
86   bool IncludePath, ShouldEmitAsError;
87 
88 public:
89   ClangDiagPathDiagConsumer(DiagnosticsEngine &Diag)
90       : Diag(Diag), IncludePath(false), ShouldEmitAsError(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 enableWerror() { ShouldEmitAsError = true; }
106 
107   void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags,
108                             FilesMade *filesMade) override {
109     unsigned WarnID =
110         ShouldEmitAsError
111             ? Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0")
112             : Diag.getCustomDiagID(DiagnosticsEngine::Warning, "%0");
113     unsigned NoteID = Diag.getCustomDiagID(DiagnosticsEngine::Note, "%0");
114 
115     for (std::vector<const PathDiagnostic*>::iterator I = Diags.begin(),
116          E = Diags.end(); I != E; ++I) {
117       const PathDiagnostic *PD = *I;
118       SourceLocation WarnLoc = PD->getLocation().asLocation();
119       Diag.Report(WarnLoc, WarnID) << PD->getShortDescription()
120                                    << PD->path.back()->getRanges();
121 
122       // First, add extra notes, even if paths should not be included.
123       for (const auto &Piece : PD->path) {
124         if (!isa<PathDiagnosticNotePiece>(Piece.get()))
125           continue;
126 
127         SourceLocation NoteLoc = Piece->getLocation().asLocation();
128         Diag.Report(NoteLoc, NoteID) << Piece->getString()
129                                      << Piece->getRanges();
130       }
131 
132       if (!IncludePath)
133         continue;
134 
135       // Then, add the path notes if necessary.
136       PathPieces FlatPath = PD->path.flatten(/*ShouldFlattenMacros=*/true);
137       for (const auto &Piece : FlatPath) {
138         if (isa<PathDiagnosticNotePiece>(Piece.get()))
139           continue;
140 
141         SourceLocation NoteLoc = Piece->getLocation().asLocation();
142         Diag.Report(NoteLoc, NoteID) << Piece->getString()
143                                      << Piece->getRanges();
144       }
145     }
146   }
147 };
148 } // end anonymous namespace
149 
150 //===----------------------------------------------------------------------===//
151 // AnalysisConsumer declaration.
152 //===----------------------------------------------------------------------===//
153 
154 namespace {
155 
156 class AnalysisConsumer : public AnalysisASTConsumer,
157                          public RecursiveASTVisitor<AnalysisConsumer> {
158   enum {
159     AM_None = 0,
160     AM_Syntax = 0x1,
161     AM_Path = 0x2
162   };
163   typedef unsigned AnalysisMode;
164 
165   /// Mode of the analyzes while recursively visiting Decls.
166   AnalysisMode RecVisitorMode;
167   /// Bug Reporter to use while recursively visiting Decls.
168   BugReporter *RecVisitorBR;
169 
170   std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
171 
172 public:
173   ASTContext *Ctx;
174   const Preprocessor &PP;
175   const std::string OutDir;
176   AnalyzerOptionsRef Opts;
177   ArrayRef<std::string> Plugins;
178   CodeInjector *Injector;
179   cross_tu::CrossTranslationUnitContext CTU;
180 
181   /// Stores the declarations from the local translation unit.
182   /// Note, we pre-compute the local declarations at parse time as an
183   /// optimization to make sure we do not deserialize everything from disk.
184   /// The local declaration to all declarations ratio might be very small when
185   /// working with a PCH file.
186   SetOfDecls LocalTUDecls;
187 
188   // Set of PathDiagnosticConsumers.  Owned by AnalysisManager.
189   PathDiagnosticConsumers PathConsumers;
190 
191   StoreManagerCreator CreateStoreMgr;
192   ConstraintManagerCreator CreateConstraintMgr;
193 
194   std::unique_ptr<CheckerManager> checkerMgr;
195   std::unique_ptr<AnalysisManager> Mgr;
196 
197   /// Time the analyzes time of each translation unit.
198   std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
199   std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
200   std::unique_ptr<llvm::Timer> ExprEngineTimer;
201   std::unique_ptr<llvm::Timer> BugReporterTimer;
202 
203   /// The information about analyzed functions shared throughout the
204   /// translation unit.
205   FunctionSummariesTy FunctionSummaries;
206 
207   AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
208                    AnalyzerOptionsRef opts, ArrayRef<std::string> plugins,
209                    CodeInjector *injector)
210       : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
211         PP(CI.getPreprocessor()), OutDir(outdir), Opts(std::move(opts)),
212         Plugins(plugins), Injector(injector), CTU(CI) {
213     DigestAnalyzerOptions();
214     if (Opts->PrintStats || Opts->ShouldSerializeStats) {
215       AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
216           "analyzer", "Analyzer timers");
217       SyntaxCheckTimer = std::make_unique<llvm::Timer>(
218           "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
219       ExprEngineTimer = std::make_unique<llvm::Timer>(
220           "exprengine", "Path exploration time", *AnalyzerTimers);
221       BugReporterTimer = std::make_unique<llvm::Timer>(
222           "bugreporter", "Path-sensitive report post-processing time",
223           *AnalyzerTimers);
224       llvm::EnableStatistics(/* PrintOnExit= */ false);
225     }
226   }
227 
228   ~AnalysisConsumer() override {
229     if (Opts->PrintStats) {
230       llvm::PrintStatistics();
231     }
232   }
233 
234   void DigestAnalyzerOptions() {
235     if (Opts->AnalysisDiagOpt != PD_NONE) {
236       // Create the PathDiagnosticConsumer.
237       ClangDiagPathDiagConsumer *clangDiags =
238           new ClangDiagPathDiagConsumer(PP.getDiagnostics());
239       PathConsumers.push_back(clangDiags);
240 
241       if (Opts->AnalyzerWerror)
242         clangDiags->enableWerror();
243 
244       if (Opts->AnalysisDiagOpt == PD_TEXT) {
245         clangDiags->enablePaths();
246 
247       } else if (!OutDir.empty()) {
248         switch (Opts->AnalysisDiagOpt) {
249         default:
250 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN)                    \
251   case PD_##NAME:                                                              \
252     CREATEFN(*Opts.get(), PathConsumers, OutDir, PP, CTU);                     \
253     break;
254 #include "clang/StaticAnalyzer/Core/Analyses.def"
255         }
256       }
257     }
258 
259     // Create the analyzer component creators.
260     switch (Opts->AnalysisStoreOpt) {
261     default:
262       llvm_unreachable("Unknown store manager.");
263 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATEFN)           \
264       case NAME##Model: CreateStoreMgr = CREATEFN; break;
265 #include "clang/StaticAnalyzer/Core/Analyses.def"
266     }
267 
268     switch (Opts->AnalysisConstraintsOpt) {
269     default:
270       llvm_unreachable("Unknown constraint manager.");
271 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN)     \
272       case NAME##Model: CreateConstraintMgr = CREATEFN; break;
273 #include "clang/StaticAnalyzer/Core/Analyses.def"
274     }
275   }
276 
277   void DisplayFunction(const Decl *D, AnalysisMode Mode,
278                        ExprEngine::InliningModes IMode) {
279     if (!Opts->AnalyzerDisplayProgress)
280       return;
281 
282     SourceManager &SM = Mgr->getASTContext().getSourceManager();
283     PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
284     if (Loc.isValid()) {
285       llvm::errs() << "ANALYZE";
286 
287       if (Mode == AM_Syntax)
288         llvm::errs() << " (Syntax)";
289       else if (Mode == AM_Path) {
290         llvm::errs() << " (Path, ";
291         switch (IMode) {
292           case ExprEngine::Inline_Minimal:
293             llvm::errs() << " Inline_Minimal";
294             break;
295           case ExprEngine::Inline_Regular:
296             llvm::errs() << " Inline_Regular";
297             break;
298         }
299         llvm::errs() << ")";
300       }
301       else
302         assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
303 
304       llvm::errs() << ": " << Loc.getFilename() << ' '
305                            << getFunctionName(D) << '\n';
306     }
307   }
308 
309   void Initialize(ASTContext &Context) override {
310     Ctx = &Context;
311     checkerMgr = createCheckerManager(
312         *Ctx, *Opts, Plugins, CheckerRegistrationFns, PP.getDiagnostics());
313 
314     Mgr = std::make_unique<AnalysisManager>(*Ctx, PathConsumers, CreateStoreMgr,
315                                             CreateConstraintMgr,
316                                             checkerMgr.get(), *Opts, Injector);
317   }
318 
319   /// Store the top level decls in the set to be processed later on.
320   /// (Doing this pre-processing avoids deserialization of data from PCH.)
321   bool HandleTopLevelDecl(DeclGroupRef D) override;
322   void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
323 
324   void HandleTranslationUnit(ASTContext &C) override;
325 
326   /// Determine which inlining mode should be used when this function is
327   /// analyzed. This allows to redefine the default inlining policies when
328   /// analyzing a given function.
329   ExprEngine::InliningModes
330     getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
331 
332   /// Build the call graph for all the top level decls of this TU and
333   /// use it to define the order in which the functions should be visited.
334   void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
335 
336   /// Run analyzes(syntax or path sensitive) on the given function.
337   /// \param Mode - determines if we are requesting syntax only or path
338   /// sensitive only analysis.
339   /// \param VisitedCallees - The output parameter, which is populated with the
340   /// set of functions which should be considered analyzed after analyzing the
341   /// given root function.
342   void HandleCode(Decl *D, AnalysisMode Mode,
343                   ExprEngine::InliningModes IMode = ExprEngine::Inline_Minimal,
344                   SetOfConstDecls *VisitedCallees = nullptr);
345 
346   void RunPathSensitiveChecks(Decl *D,
347                               ExprEngine::InliningModes IMode,
348                               SetOfConstDecls *VisitedCallees);
349 
350   /// Visitors for the RecursiveASTVisitor.
351   bool shouldWalkTypesOfTypeLocs() const { return false; }
352 
353   /// Handle callbacks for arbitrary Decls.
354   bool VisitDecl(Decl *D) {
355     AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
356     if (Mode & AM_Syntax) {
357       if (SyntaxCheckTimer)
358         SyntaxCheckTimer->startTimer();
359       checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
360       if (SyntaxCheckTimer)
361         SyntaxCheckTimer->stopTimer();
362     }
363     return true;
364   }
365 
366   bool VisitVarDecl(VarDecl *VD) {
367     if (!Opts->IsNaiveCTUEnabled)
368       return true;
369 
370     if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
371       if (!cross_tu::containsConst(VD, *Ctx))
372         return true;
373     } else {
374       // Cannot be initialized in another TU.
375       return true;
376     }
377 
378     if (VD->getAnyInitializer())
379       return true;
380 
381     llvm::Expected<const VarDecl *> CTUDeclOrError =
382       CTU.getCrossTUDefinition(VD, Opts->CTUDir, Opts->CTUIndexName,
383                                Opts->DisplayCTUProgress);
384 
385     if (!CTUDeclOrError) {
386       handleAllErrors(CTUDeclOrError.takeError(),
387                       [&](const cross_tu::IndexError &IE) {
388                         CTU.emitCrossTUDiagnostics(IE);
389                       });
390     }
391 
392     return true;
393   }
394 
395   bool VisitFunctionDecl(FunctionDecl *FD) {
396     IdentifierInfo *II = FD->getIdentifier();
397     if (II && II->getName().startswith("__inline"))
398       return true;
399 
400     // We skip function template definitions, as their semantics is
401     // only determined when they are instantiated.
402     if (FD->isThisDeclarationADefinition() &&
403         !FD->isDependentContext()) {
404       assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
405       HandleCode(FD, RecVisitorMode);
406     }
407     return true;
408   }
409 
410   bool VisitObjCMethodDecl(ObjCMethodDecl *MD) {
411     if (MD->isThisDeclarationADefinition()) {
412       assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
413       HandleCode(MD, RecVisitorMode);
414     }
415     return true;
416   }
417 
418   bool VisitBlockDecl(BlockDecl *BD) {
419     if (BD->hasBody()) {
420       assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
421       // Since we skip function template definitions, we should skip blocks
422       // declared in those functions as well.
423       if (!BD->isDependentContext()) {
424         HandleCode(BD, RecVisitorMode);
425       }
426     }
427     return true;
428   }
429 
430   void AddDiagnosticConsumer(PathDiagnosticConsumer *Consumer) override {
431     PathConsumers.push_back(Consumer);
432   }
433 
434   void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
435     CheckerRegistrationFns.push_back(std::move(Fn));
436   }
437 
438 private:
439   void storeTopLevelDecls(DeclGroupRef DG);
440   std::string getFunctionName(const Decl *D);
441 
442   /// Check if we should skip (not analyze) the given function.
443   AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
444   void runAnalysisOnTranslationUnit(ASTContext &C);
445 
446   /// Print \p S to stderr if \c Opts->AnalyzerDisplayProgress is set.
447   void reportAnalyzerProgress(StringRef S);
448 };
449 } // end anonymous namespace
450 
451 
452 //===----------------------------------------------------------------------===//
453 // AnalysisConsumer implementation.
454 //===----------------------------------------------------------------------===//
455 bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
456   storeTopLevelDecls(DG);
457   return true;
458 }
459 
460 void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
461   storeTopLevelDecls(DG);
462 }
463 
464 void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
465   for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) {
466 
467     // Skip ObjCMethodDecl, wait for the objc container to avoid
468     // analyzing twice.
469     if (isa<ObjCMethodDecl>(*I))
470       continue;
471 
472     LocalTUDecls.push_back(*I);
473   }
474 }
475 
476 static bool shouldSkipFunction(const Decl *D,
477                                const SetOfConstDecls &Visited,
478                                const SetOfConstDecls &VisitedAsTopLevel) {
479   if (VisitedAsTopLevel.count(D))
480     return true;
481 
482   // We want to re-analyse the functions as top level in the following cases:
483   // - The 'init' methods should be reanalyzed because
484   //   ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
485   //   'nil' and unless we analyze the 'init' functions as top level, we will
486   //   not catch errors within defensive code.
487   // - We want to reanalyze all ObjC methods as top level to report Retain
488   //   Count naming convention errors more aggressively.
489   if (isa<ObjCMethodDecl>(D))
490     return false;
491   // We also want to reanalyze all C++ copy and move assignment operators to
492   // separately check the two cases where 'this' aliases with the parameter and
493   // where it may not. (cplusplus.SelfAssignmentChecker)
494   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
495     if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
496       return false;
497   }
498 
499   // Otherwise, if we visited the function before, do not reanalyze it.
500   return Visited.count(D);
501 }
502 
503 ExprEngine::InliningModes
504 AnalysisConsumer::getInliningModeForFunction(const Decl *D,
505                                              const SetOfConstDecls &Visited) {
506   // We want to reanalyze all ObjC methods as top level to report Retain
507   // Count naming convention errors more aggressively. But we should tune down
508   // inlining when reanalyzing an already inlined function.
509   if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
510     const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
511     if (ObjCM->getMethodFamily() != OMF_init)
512       return ExprEngine::Inline_Minimal;
513   }
514 
515   return ExprEngine::Inline_Regular;
516 }
517 
518 void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
519   // Build the Call Graph by adding all the top level declarations to the graph.
520   // Note: CallGraph can trigger deserialization of more items from a pch
521   // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
522   // We rely on random access to add the initially processed Decls to CG.
523   CallGraph CG;
524   for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
525     CG.addToCallGraph(LocalTUDecls[i]);
526   }
527 
528   // Walk over all of the call graph nodes in topological order, so that we
529   // analyze parents before the children. Skip the functions inlined into
530   // the previously processed functions. Use external Visited set to identify
531   // inlined functions. The topological order allows the "do not reanalyze
532   // previously inlined function" performance heuristic to be triggered more
533   // often.
534   SetOfConstDecls Visited;
535   SetOfConstDecls VisitedAsTopLevel;
536   llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
537   for (llvm::ReversePostOrderTraversal<clang::CallGraph*>::rpo_iterator
538          I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
539     NumFunctionTopLevel++;
540 
541     CallGraphNode *N = *I;
542     Decl *D = N->getDecl();
543 
544     // Skip the abstract root node.
545     if (!D)
546       continue;
547 
548     // Skip the functions which have been processed already or previously
549     // inlined.
550     if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
551       continue;
552 
553     // Analyze the function.
554     SetOfConstDecls VisitedCallees;
555 
556     HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
557                (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
558 
559     // Add the visited callees to the global visited set.
560     for (const Decl *Callee : VisitedCallees)
561       // Decls from CallGraph are already canonical. But Decls coming from
562       // CallExprs may be not. We should canonicalize them manually.
563       Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
564                                                  : Callee->getCanonicalDecl());
565     VisitedAsTopLevel.insert(D);
566   }
567 }
568 
569 static bool isBisonFile(ASTContext &C) {
570   const SourceManager &SM = C.getSourceManager();
571   FileID FID = SM.getMainFileID();
572   StringRef Buffer = SM.getBuffer(FID)->getBuffer();
573   if (Buffer.startswith("/* A Bison parser, made by"))
574     return true;
575   return false;
576 }
577 
578 void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
579   BugReporter BR(*Mgr);
580   TranslationUnitDecl *TU = C.getTranslationUnitDecl();
581   if (SyntaxCheckTimer)
582     SyntaxCheckTimer->startTimer();
583   checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
584   if (SyntaxCheckTimer)
585     SyntaxCheckTimer->stopTimer();
586 
587   // Run the AST-only checks using the order in which functions are defined.
588   // If inlining is not turned on, use the simplest function order for path
589   // sensitive analyzes as well.
590   RecVisitorMode = AM_Syntax;
591   if (!Mgr->shouldInlineCall())
592     RecVisitorMode |= AM_Path;
593   RecVisitorBR = &BR;
594 
595   // Process all the top level declarations.
596   //
597   // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
598   // entries.  Thus we don't use an iterator, but rely on LocalTUDecls
599   // random access.  By doing so, we automatically compensate for iterators
600   // possibly being invalidated, although this is a bit slower.
601   const unsigned LocalTUDeclsSize = LocalTUDecls.size();
602   for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
603     TraverseDecl(LocalTUDecls[i]);
604   }
605 
606   if (Mgr->shouldInlineCall())
607     HandleDeclsCallGraph(LocalTUDeclsSize);
608 
609   // After all decls handled, run checkers on the entire TranslationUnit.
610   checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
611 
612   BR.FlushReports();
613   RecVisitorBR = nullptr;
614 }
615 
616 void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
617   if (Opts->AnalyzerDisplayProgress)
618     llvm::errs() << S;
619 }
620 
621 void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
622 
623   // Don't run the actions if an error has occurred with parsing the file.
624   DiagnosticsEngine &Diags = PP.getDiagnostics();
625   if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
626     return;
627 
628   if (isBisonFile(C)) {
629     reportAnalyzerProgress("Skipping bison-generated file\n");
630   } else if (Opts->DisableAllChecks) {
631 
632     // Don't analyze if the user explicitly asked for no checks to be performed
633     // on this file.
634     reportAnalyzerProgress("All checks are disabled using a supplied option\n");
635   } else {
636     // Otherwise, just run the analysis.
637     runAnalysisOnTranslationUnit(C);
638   }
639 
640   // Count how many basic blocks we have not covered.
641   NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
642   NumVisitedBlocksInAnalyzedFunctions =
643       FunctionSummaries.getTotalNumVisitedBasicBlocks();
644   if (NumBlocksInAnalyzedFunctions > 0)
645     PercentReachableBlocks =
646       (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
647         NumBlocksInAnalyzedFunctions;
648 
649   // Explicitly destroy the PathDiagnosticConsumer.  This will flush its output.
650   // FIXME: This should be replaced with something that doesn't rely on
651   // side-effects in PathDiagnosticConsumer's destructor. This is required when
652   // used with option -disable-free.
653   Mgr.reset();
654 }
655 
656 std::string AnalysisConsumer::getFunctionName(const Decl *D) {
657   std::string Str;
658   llvm::raw_string_ostream OS(Str);
659 
660   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
661     OS << FD->getQualifiedNameAsString();
662 
663     // In C++, there are overloads.
664     if (Ctx->getLangOpts().CPlusPlus) {
665       OS << '(';
666       for (const auto &P : FD->parameters()) {
667         if (P != *FD->param_begin())
668           OS << ", ";
669         OS << P->getType().getAsString();
670       }
671       OS << ')';
672     }
673 
674   } else if (isa<BlockDecl>(D)) {
675     PresumedLoc Loc = Ctx->getSourceManager().getPresumedLoc(D->getLocation());
676 
677     if (Loc.isValid()) {
678       OS << "block (line: " << Loc.getLine() << ", col: " << Loc.getColumn()
679          << ')';
680     }
681 
682   } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
683 
684     // FIXME: copy-pasted from CGDebugInfo.cpp.
685     OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
686     const DeclContext *DC = OMD->getDeclContext();
687     if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
688       OS << OID->getName();
689     } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
690       OS << OID->getName();
691     } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
692       if (OC->IsClassExtension()) {
693         OS << OC->getClassInterface()->getName();
694       } else {
695         OS << OC->getIdentifier()->getNameStart() << '('
696            << OC->getIdentifier()->getNameStart() << ')';
697       }
698     } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
699       OS << OCD->getClassInterface()->getName() << '('
700          << OCD->getName() << ')';
701     } else if (isa<ObjCProtocolDecl>(DC)) {
702       // We can extract the type of the class from the self pointer.
703       if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
704         QualType ClassTy =
705             cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
706         ClassTy.print(OS, PrintingPolicy(LangOptions()));
707       }
708     }
709     OS << ' ' << OMD->getSelector().getAsString() << ']';
710 
711   }
712 
713   return OS.str();
714 }
715 
716 AnalysisConsumer::AnalysisMode
717 AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
718   if (!Opts->AnalyzeSpecificFunction.empty() &&
719       getFunctionName(D) != Opts->AnalyzeSpecificFunction)
720     return AM_None;
721 
722   // Unless -analyze-all is specified, treat decls differently depending on
723   // where they came from:
724   // - Main source file: run both path-sensitive and non-path-sensitive checks.
725   // - Header files: run non-path-sensitive checks only.
726   // - System headers: don't run any checks.
727   SourceManager &SM = Ctx->getSourceManager();
728   const Stmt *Body = D->getBody();
729   SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
730   SL = SM.getExpansionLoc(SL);
731 
732   if (!Opts->AnalyzeAll && !Mgr->isInCodeFile(SL)) {
733     if (SL.isInvalid() || SM.isInSystemHeader(SL))
734       return AM_None;
735     return Mode & ~AM_Path;
736   }
737 
738   return Mode;
739 }
740 
741 void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
742                                   ExprEngine::InliningModes IMode,
743                                   SetOfConstDecls *VisitedCallees) {
744   if (!D->hasBody())
745     return;
746   Mode = getModeForDecl(D, Mode);
747   if (Mode == AM_None)
748     return;
749 
750   // Clear the AnalysisManager of old AnalysisDeclContexts.
751   Mgr->ClearContexts();
752   // Ignore autosynthesized code.
753   if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
754     return;
755 
756   DisplayFunction(D, Mode, IMode);
757   CFG *DeclCFG = Mgr->getCFG(D);
758   if (DeclCFG)
759     MaxCFGSize.updateMax(DeclCFG->size());
760 
761   BugReporter BR(*Mgr);
762 
763   if (Mode & AM_Syntax) {
764     if (SyntaxCheckTimer)
765       SyntaxCheckTimer->startTimer();
766     checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
767     if (SyntaxCheckTimer)
768       SyntaxCheckTimer->stopTimer();
769   }
770 
771   BR.FlushReports();
772 
773   if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
774     RunPathSensitiveChecks(D, IMode, VisitedCallees);
775     if (IMode != ExprEngine::Inline_Minimal)
776       NumFunctionsAnalyzed++;
777   }
778 }
779 
780 //===----------------------------------------------------------------------===//
781 // Path-sensitive checking.
782 //===----------------------------------------------------------------------===//
783 
784 void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
785                                               ExprEngine::InliningModes IMode,
786                                               SetOfConstDecls *VisitedCallees) {
787   // Construct the analysis engine.  First check if the CFG is valid.
788   // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
789   if (!Mgr->getCFG(D))
790     return;
791 
792   // See if the LiveVariables analysis scales.
793   if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
794     return;
795 
796   ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
797 
798   // Execute the worklist algorithm.
799   if (ExprEngineTimer)
800     ExprEngineTimer->startTimer();
801   Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
802                       Mgr->options.MaxNodesPerTopLevelFunction);
803   if (ExprEngineTimer)
804     ExprEngineTimer->stopTimer();
805 
806   if (!Mgr->options.DumpExplodedGraphTo.empty())
807     Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
808 
809   // Visualize the exploded graph.
810   if (Mgr->options.visualizeExplodedGraphWithGraphViz)
811     Eng.ViewGraph(Mgr->options.TrimGraph);
812 
813   // Display warnings.
814   if (BugReporterTimer)
815     BugReporterTimer->startTimer();
816   Eng.getBugReporter().FlushReports();
817   if (BugReporterTimer)
818     BugReporterTimer->stopTimer();
819 }
820 
821 //===----------------------------------------------------------------------===//
822 // AnalysisConsumer creation.
823 //===----------------------------------------------------------------------===//
824 
825 std::unique_ptr<AnalysisASTConsumer>
826 ento::CreateAnalysisConsumer(CompilerInstance &CI) {
827   // Disable the effects of '-Werror' when using the AnalysisConsumer.
828   CI.getPreprocessor().getDiagnostics().setWarningsAsErrors(false);
829 
830   AnalyzerOptionsRef analyzerOpts = CI.getAnalyzerOpts();
831   bool hasModelPath = analyzerOpts->Config.count("model-path") > 0;
832 
833   return std::make_unique<AnalysisConsumer>(
834       CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
835       CI.getFrontendOpts().Plugins,
836       hasModelPath ? new ModelInjector(CI) : nullptr);
837 }
838