37#include "llvm/ADT/PostOrderIterator.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/Support/TimeProfiler.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/Support/raw_ostream.h"
48#define DEBUG_TYPE "AnalysisConsumer"
50STAT_COUNTER(NumFunctionTopLevel,
"The # of functions at top level.");
52 "The # of functions and blocks analyzed (as top level "
53 "with inlining turned on).");
55 "The # of basic blocks in the analyzed functions.");
57 NumVisitedBlocksInAnalyzedFunctions,
58 "The # of visited basic blocks in the analyzed functions.");
60 "The % of reachable basic blocks.");
61STAT_MAX(MaxCFGSize,
"The maximum number of basic blocks in a function.");
75 typedef unsigned AnalysisMode;
78 AnalysisMode RecVisitorMode;
80 BugReporter *RecVisitorBR;
82 std::vector<
std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
87 const std::string OutDir;
88 AnalyzerOptions &Opts;
89 ArrayRef<std::string> Plugins;
90 std::unique_ptr<CodeInjector> Injector;
91 cross_tu::CrossTranslationUnitContext CTU;
100 MacroExpansionContext MacroExpansions;
108 std::unique_ptr<CheckerManager> checkerMgr;
109 std::unique_ptr<AnalysisManager> Mgr;
112 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
113 std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
114 std::unique_ptr<llvm::Timer> ExprEngineTimer;
115 std::unique_ptr<llvm::Timer> BugReporterTimer;
119 FunctionSummariesTy FunctionSummaries;
121 AnalysisConsumer(CompilerInstance &CI,
const std::string &outdir,
122 AnalyzerOptions &opts, ArrayRef<std::string> plugins,
123 std::unique_ptr<CodeInjector> injector)
125 PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts), Plugins(plugins),
126 Injector(std::move(injector)), CTU(CI),
127 MacroExpansions(CI.getLangOpts()) {
129 DigestAnalyzerOptions();
131 if (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||
132 Opts.ShouldSerializeStats) {
133 AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
134 "analyzer",
"Analyzer timers");
135 SyntaxCheckTimer = std::make_unique<llvm::Timer>(
136 "syntaxchecks",
"Syntax-based analysis time", *AnalyzerTimers);
137 ExprEngineTimer = std::make_unique<llvm::Timer>(
138 "exprengine",
"Path exploration time", *AnalyzerTimers);
139 BugReporterTimer = std::make_unique<llvm::Timer>(
140 "bugreporter",
"Path-sensitive report post-processing time",
144 if (Opts.PrintStats || Opts.ShouldSerializeStats) {
145 llvm::EnableStatistics(
false);
148 if (Opts.ShouldDisplayMacroExpansions)
149 MacroExpansions.registerForPreprocessor(PP);
152 ShouldWalkTypesOfTypeLocs =
false;
155 ~AnalysisConsumer()
override {
156 if (Opts.PrintStats) {
157 llvm::PrintStatistics();
161 void DigestAnalyzerOptions() {
162 switch (Opts.AnalysisDiagOpt) {
165#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
167 CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
170#include "clang/StaticAnalyzer/Core/Analyses.def"
172 llvm_unreachable(
"Unknown analyzer output type!");
178 switch (Opts.AnalysisConstraintsOpt) {
180 llvm_unreachable(
"Unknown constraint manager.");
181#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
182 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
183#include "clang/StaticAnalyzer/Core/Analyses.def"
187 void DisplayTime(llvm::TimeRecord &Time) {
188 if (!Opts.AnalyzerDisplayProgress) {
191 llvm::errs() <<
" : " << llvm::format(
"%1.1f", Time.getWallTime() * 1000)
195 void DisplayFunction(
const Decl *D, AnalysisMode Mode,
197 if (!Opts.AnalyzerDisplayProgress)
200 SourceManager &
SM = Mgr->getASTContext().getSourceManager();
203 llvm::errs() <<
"ANALYZE";
205 if (Mode == AM_Syntax)
206 llvm::errs() <<
" (Syntax)";
207 else if (Mode == AM_Path) {
208 llvm::errs() <<
" (Path, ";
211 llvm::errs() <<
" Inline_Minimal";
214 llvm::errs() <<
" Inline_Regular";
219 assert(Mode == (AM_Syntax | AM_Path) &&
"Unexpected mode!");
228 bool HandleTopLevelDecl(DeclGroupRef D)
override;
229 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D)
override;
231 void HandleTranslationUnit(ASTContext &
C)
override;
237 getInliningModeForFunction(
const Decl *D,
const SetOfConstDecls &Visited);
241 void HandleDeclsCallGraph(
const unsigned LocalTUDeclsSize);
249 void HandleCode(Decl *D, AnalysisMode Mode,
253 void RunPathSensitiveChecks(Decl *D,
258 bool VisitDecl(Decl *D)
override {
259 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
260 if (Mode & AM_Syntax) {
261 if (SyntaxCheckTimer)
262 SyntaxCheckTimer->startTimer();
263 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
264 if (SyntaxCheckTimer)
265 SyntaxCheckTimer->stopTimer();
270 bool VisitVarDecl(VarDecl *VD)
override {
271 if (!Opts.IsNaiveCTUEnabled)
285 llvm::Expected<const VarDecl *> CTUDeclOrError =
286 CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,
287 Opts.DisplayCTUProgress);
289 if (!CTUDeclOrError) {
290 handleAllErrors(CTUDeclOrError.takeError(),
291 [&](
const cross_tu::IndexError &IE) {
292 CTU.emitCrossTUDiagnostics(IE);
299 bool VisitFunctionDecl(FunctionDecl *FD)
override {
301 if (II && II->
getName().starts_with(
"__inline"))
308 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
309 HandleCode(FD, RecVisitorMode);
314 bool VisitObjCMethodDecl(ObjCMethodDecl *MD)
override {
316 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
317 HandleCode(MD, RecVisitorMode);
322 bool VisitBlockDecl(BlockDecl *BD)
override {
324 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() ==
false);
328 HandleCode(BD, RecVisitorMode);
334 void AddDiagnosticConsumer(
335 std::unique_ptr<PathDiagnosticConsumer> Consumer)
override {
336 PathConsumers.push_back(std::move(Consumer));
339 void AddCheckerRegistrationFn(
std::function<
void(CheckerRegistry&)> Fn)
override {
340 CheckerRegistrationFns.push_back(std::move(Fn));
344 void storeTopLevelDecls(DeclGroupRef DG);
347 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
348 void runAnalysisOnTranslationUnit(ASTContext &
C);
351 void reportAnalyzerProgress(StringRef S);
354std::string timeTraceScopeDeclName(StringRef FunName,
const Decl *D) {
355 if (llvm::timeTraceProfilerEnabled()) {
356 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(D))
357 return (FunName +
" " + ND->getQualifiedNameAsString()).str();
358 return (FunName +
" <anonymous> ").str();
363llvm::TimeTraceMetadata timeTraceScopeDeclMetadata(
const Decl *D) {
365 assert(llvm::timeTraceProfilerEnabled());
369 return llvm::TimeTraceMetadata{
370 std::move(DeclName),
SM.getFilename(
Loc).str(),
371 static_cast<int>(
SM.getExpansionLineNumber(
Loc))};
373 return llvm::TimeTraceMetadata{
"",
""};
376void flushReports(llvm::Timer *BugReporterTimer,
BugReporter &BR) {
377 llvm::TimeTraceScope TCS{
"Flushing reports"};
379 if (BugReporterTimer)
380 BugReporterTimer->startTimer();
382 if (BugReporterTimer)
383 BugReporterTimer->stopTimer();
390bool AnalysisConsumer::HandleTopLevelDecl(
DeclGroupRef DG) {
391 storeTopLevelDecls(DG);
395void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
396 storeTopLevelDecls(DG);
399void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
407 LocalTUDecls.push_back(I);
414 if (VisitedAsTopLevel.count(D))
420 if (
const auto *CD = dyn_cast<CXXConstructorDecl>(D))
421 if (CD->isInheritingConstructor())
436 if (
const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
437 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
442 return Visited.count(D);
446AnalysisConsumer::getInliningModeForFunction(
const Decl *D,
460void AnalysisConsumer::HandleDeclsCallGraph(
const unsigned LocalTUDeclsSize) {
466 for (
unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
478 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
479 for (
auto &N : RPOT) {
480 NumFunctionTopLevel++;
482 Decl *D = N->getDecl();
497 if (
const auto *FD = dyn_cast<FunctionDecl>(D)) {
508 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
509 (Mgr->options.InliningMode ==
All ?
nullptr : &VisitedCallees));
512 for (
const Decl *Callee : VisitedCallees)
516 :
Callee->getCanonicalDecl());
517 VisitedAsTopLevel.insert(D);
524 StringRef Buffer =
SM.getBufferOrFake(FID).getBuffer();
525 return Buffer.contains(Substring);
530 llvm::errs() <<
"Every top-level function was skipped.\n";
533 llvm::errs() <<
"Pass the -analyzer-display-progress for tracking which "
534 "functions are analyzed.\n";
541 <<
"For analyzing C++ code you need to pass the function parameter "
542 "list: -analyze-function=\"foobar(int, _Bool)\"\n";
543 }
else if (!Ctx.
getLangOpts().CPlusPlus && HasBrackets) {
544 llvm::errs() <<
"For analyzing C code you shouldn't pass the function "
545 "parameter list, only the name of the function: "
546 "-analyze-function=foobar\n";
550void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &
C) {
551 BugReporter BR(*Mgr);
552 const TranslationUnitDecl *TU =
C.getTranslationUnitDecl();
554 if (SyntaxCheckTimer)
555 SyntaxCheckTimer->startTimer();
556 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
557 if (SyntaxCheckTimer)
558 SyntaxCheckTimer->stopTimer();
563 RecVisitorMode = AM_Syntax;
564 if (!Mgr->shouldInlineCall())
565 RecVisitorMode |= AM_Path;
574 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
575 for (
unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
576 TraverseDecl(LocalTUDecls[i]);
579 if (Mgr->shouldInlineCall())
580 HandleDeclsCallGraph(LocalTUDeclsSize);
583 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
586 RecVisitorBR =
nullptr;
597void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
602void AnalysisConsumer::HandleTranslationUnit(ASTContext &
C) {
609 checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,
610 CheckerRegistrationFns);
612 Mgr = std::make_unique<AnalysisManager>(
613 *Ctx, PP, std::move(PathConsumers), CreateStoreMgr, CreateConstraintMgr,
614 checkerMgr.get(), Opts, std::move(Injector));
620 const auto DiagFlusherScopeExit =
621 llvm::make_scope_exit([
this] { Mgr.reset(); });
623 if (Opts.ShouldIgnoreBisonGeneratedFiles &&
625 reportAnalyzerProgress(
"Skipping bison-generated file\n");
629 if (Opts.ShouldIgnoreFlexGeneratedFiles &&
631 reportAnalyzerProgress(
"Skipping flex-generated file\n");
638 reportAnalyzerProgress(
"All checks are disabled using a supplied option\n");
643 runAnalysisOnTranslationUnit(
C);
647 NumVisitedBlocksInAnalyzedFunctions =
649 if (NumBlocksInAnalyzedFunctions > 0)
650 PercentReachableBlocks =
652 NumBlocksInAnalyzedFunctions;
654 if (!Opts.DumpEntryPointStatsToCSV.empty()) {
659AnalysisConsumer::AnalysisMode
660AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
675 const SourceLocation Loc = [&
SM](
Decl *D) -> SourceLocation {
676 const Stmt *Body = D->
getBody();
678 return SM.getExpansionLoc(SL);
686 if (!Mgr->isInCodeFile(Loc))
687 return Mode & ~AM_Path;
694void AnalysisConsumer::HandleCode(
Decl *D, AnalysisMode Mode,
697 llvm::TimeTraceScope TCS(timeTraceScopeDeclName(
"HandleCode", D),
698 [D]() {
return timeTraceScopeDeclMetadata(D); });
701 Mode = getModeForDecl(D, Mode);
706 Mgr->ClearContexts();
708 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
711 CFG *DeclCFG = Mgr->getCFG(D);
713 MaxCFGSize.updateMax(DeclCFG->
size());
715 DisplayFunction(D, Mode, IMode);
716 BugReporter BR(*Mgr);
719 if (Mode & AM_Syntax) {
720 llvm::TimeRecord CheckerStartTime;
721 if (SyntaxCheckTimer) {
722 CheckerStartTime = SyntaxCheckTimer->getTotalTime();
723 SyntaxCheckTimer->startTimer();
725 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
726 if (SyntaxCheckTimer) {
727 SyntaxCheckTimer->stopTimer();
728 llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
729 CheckerEndTime -= CheckerStartTime;
730 DisplayTime(CheckerEndTime);
736 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
737 RunPathSensitiveChecks(D, IMode, VisitedCallees);
740 NumFunctionsAnalyzed++;
748void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
757 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
760 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
763 llvm::TimeRecord ExprEngineStartTime;
764 if (ExprEngineTimer) {
765 ExprEngineStartTime = ExprEngineTimer->getTotalTime();
766 ExprEngineTimer->startTimer();
768 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
769 Mgr->options.MaxNodesPerTopLevelFunction);
770 if (ExprEngineTimer) {
771 ExprEngineTimer->stopTimer();
772 llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
773 ExprEngineEndTime -= ExprEngineStartTime;
774 DisplayTime(ExprEngineEndTime);
777 if (!Mgr->options.DumpExplodedGraphTo.empty())
778 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
781 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
782 Eng.ViewGraph(Mgr->options.TrimGraph);
784 flushReports(BugReporterTimer.get(), Eng.getBugReporter());
791std::unique_ptr<AnalysisASTConsumer>
797 bool hasModelPath = analyzerOpts.
Config.count(
"model-path") > 0;
799 return std::make_unique<AnalysisConsumer>(
802 hasModelPath ? std::make_unique<ModelInjector>(CI) :
nullptr);
static UnsignedEPStat PathRunningTime("PathRunningTime")
ALWAYS_ENABLED_STATISTIC(NumFunctionsAnalyzed, "The # of functions and blocks analyzed (as top level " "with inlining turned on).")
static bool shouldSkipFunction(const Decl *D, const SetOfConstDecls &Visited, const SetOfConstDecls &VisitedAsTopLevel)
static bool fileContainsString(StringRef Substring, ASTContext &C)
static void reportAnalyzerFunctionMisuse(const AnalyzerOptions &Opts, const ASTContext &Ctx)
Defines the clang::CodeInjector interface which is responsible for injecting AST of function definiti...
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
#define STAT_COUNTER(VARNAME, DESC)
#define STAT_MAX(VARNAME, DESC)
This file defines the clang::ento::ModelInjector class which implements the clang::CodeInjector inter...
Defines the clang::Preprocessor interface.
Defines the SourceManager interface.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
SourceManager & getSourceManager()
const LangOptions & getLangOpts() const
static std::string getFunctionName(const Decl *D)
Stores options for the analyzer from the command line.
unsigned DisableAllCheckers
Disable all analyzer checkers.
ConfigTable Config
A key-value table of use-specified configuration values.
std::string AnalyzeSpecificFunction
unsigned AnalyzerDisplayProgress
unsigned size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
AnalyzerOptions & getAnalyzerOpts()
Preprocessor & getPreprocessor() const
Return the current preprocessor.
FrontendOptions & getFrontendOpts()
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Decl - This represents one declaration (or definition), e.g.
ASTContext & getASTContext() const LLVM_READONLY
virtual Stmt * getBody() const
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
virtual bool hasBody() const
Returns true if this Decl represents a declaration for a body of code, such as a function or method d...
SourceLocation getLocation() const
SourceLocation getBeginLoc() const LLVM_READONLY
bool hasErrorOccurred() const
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
bool hasFatalErrorOccurred() const
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
std::string OutputFile
The output file, if any.
std::vector< std::string > Plugins
The list of plugins to load.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
DiagnosticsEngine & getDiagnostics() const
const char * getFilename() const
Return the presumed filename of this location.
This class handles loading and caching of source files into memory.
SourceLocation getBeginLoc() const LLVM_READONLY
bool isStaticDataMember() const
Determines whether this is a static data member.
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
bool isImportedAsNew(const Decl *ToDecl) const
Returns true if the given Decl is newly created during the import.
BugReporter is a utility class for generating PathDiagnostics for analysis.
void FlushReports()
Generate and flush diagnostics for all bug reports.
void setAnalysisEntryPoint(const Decl *EntryPoint)
bool isValid() const =delete
static void dumpStatsAsCSV(llvm::raw_ostream &OS)
static void lockRegistry()
static void takeSnapshot(const Decl *EntryPoint)
InliningModes
The modes of inlining, which override the default analysis-wide settings.
@ Inline_Minimal
Do minimal inlining of callees.
@ Inline_Regular
Follow the default settings for inlining callees.
unsigned getTotalNumBasicBlocks()
unsigned getTotalNumVisitedBasicBlocks()
bool shouldImport(const VarDecl *VD, const ASTContext &ACtx)
Returns true if it makes sense to import a foreign variable definition.
std::deque< Decl * > SetOfDecls
std::unique_ptr< AnalysisASTConsumer > CreateAnalysisConsumer(CompilerInstance &CI)
CreateAnalysisConsumer - Creates an ASTConsumer to run various code analysis passes.
llvm::DenseSet< const Decl * > SetOfConstDecls
std::unique_ptr< ConstraintManager >(* ConstraintManagerCreator)(ProgramStateManager &, ExprEngine *)
std::unique_ptr< StoreManager >(* StoreManagerCreator)(ProgramStateManager &)
std::vector< std::unique_ptr< PathDiagnosticConsumer > > PathDiagnosticConsumers
std::unique_ptr< StoreManager > CreateRegionStoreManager(ProgramStateManager &StMgr)
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
int const char * function