clang 22.0.0git
AnalysisConsumer.cpp
Go to the documentation of this file.
1//===--- AnalysisConsumer.cpp - ASTConsumer for running Analyses ----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// "Meta" ASTConsumer for running different source analyses.
10//
11//===----------------------------------------------------------------------===//
12
14#include "ModelInjector.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
20#include "clang/Analysis/CFG.h"
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"
42#include <cmath>
43#include <memory>
44#include <utility>
45
46using namespace clang;
47using namespace ento;
48
49#define DEBUG_TYPE "AnalysisConsumer"
50
51STAT_COUNTER(NumFunctionTopLevel, "The # of functions at top level.");
52ALWAYS_ENABLED_STATISTIC(NumFunctionsAnalyzed,
53 "The # of functions and blocks analyzed (as top level "
54 "with inlining turned on).");
56 NumFunctionsAnalyzedSyntaxOnly,
57 "The # of functions analyzed by syntax checkers only.");
58ALWAYS_ENABLED_STATISTIC(NumBlocksInAnalyzedFunctions,
59 "The # of basic blocks in the analyzed functions.");
61 NumVisitedBlocksInAnalyzedFunctions,
62 "The # of visited basic blocks in the analyzed functions.");
63ALWAYS_ENABLED_STATISTIC(PercentReachableBlocks,
64 "The % of reachable basic blocks.");
65STAT_MAX(MaxCFGSize, "The maximum number of basic blocks in a function.");
66//===----------------------------------------------------------------------===//
67// AnalysisConsumer declaration.
68//===----------------------------------------------------------------------===//
69
70namespace {
71
72StringRef getMainFileName(const CompilerInvocation &Invocation) {
73 if (!Invocation.getFrontendOpts().Inputs.empty()) {
74 const FrontendInputFile &Input = Invocation.getFrontendOpts().Inputs[0];
75 return Input.isFile() ? Input.getFile()
76 : Input.getBuffer().getBufferIdentifier();
77 }
78 return "<no input>";
79}
80
81class AnalysisConsumer : public AnalysisASTConsumer,
83 enum {
84 AM_None = 0,
85 AM_Syntax = 0x1,
86 AM_Path = 0x2
87 };
88 typedef unsigned AnalysisMode;
89
90 /// Mode of the analyzes while recursively visiting Decls.
91 AnalysisMode RecVisitorMode;
92 /// Bug Reporter to use while recursively visiting Decls.
93 BugReporter *RecVisitorBR;
94
95 std::vector<std::function<void(CheckerRegistry &)>> CheckerRegistrationFns;
96
97public:
98 ASTContext *Ctx;
99 Preprocessor &PP;
100 const std::string OutDir;
101 AnalyzerOptions &Opts;
102 ArrayRef<std::string> Plugins;
103 std::unique_ptr<CodeInjector> Injector;
104 cross_tu::CrossTranslationUnitContext CTU;
105
106 /// Stores the declarations from the local translation unit.
107 /// Note, we pre-compute the local declarations at parse time as an
108 /// optimization to make sure we do not deserialize everything from disk.
109 /// The local declaration to all declarations ratio might be very small when
110 /// working with a PCH file.
111 SetOfDecls LocalTUDecls;
112
113 MacroExpansionContext MacroExpansions;
114
115 // Set of PathDiagnosticConsumers. Owned by AnalysisManager.
116 PathDiagnosticConsumers PathConsumers;
117
118 StoreManagerCreator CreateStoreMgr;
119 ConstraintManagerCreator CreateConstraintMgr;
120
121 std::unique_ptr<CheckerManager> checkerMgr;
122 std::unique_ptr<AnalysisManager> Mgr;
123
124 /// Time the analyzes time of each translation unit.
125 std::unique_ptr<llvm::TimerGroup> AnalyzerTimers;
126 std::unique_ptr<llvm::Timer> SyntaxCheckTimer;
127 std::unique_ptr<llvm::Timer> ExprEngineTimer;
128 std::unique_ptr<llvm::Timer> BugReporterTimer;
129 bool ShouldClearTimersToPreventDisplayingThem;
130
131 /// The information about analyzed functions shared throughout the
132 /// translation unit.
133 FunctionSummariesTy FunctionSummaries;
134
135 AnalysisConsumer(CompilerInstance &CI, const std::string &outdir,
136 AnalyzerOptions &opts, ArrayRef<std::string> plugins,
137 std::unique_ptr<CodeInjector> injector)
138 : RecVisitorMode(0), RecVisitorBR(nullptr), Ctx(nullptr),
139 PP(CI.getPreprocessor()), OutDir(outdir), Opts(opts), Plugins(plugins),
140 Injector(std::move(injector)), CTU(CI),
141 MacroExpansions(CI.getLangOpts()) {
142
143 EntryPointStat::lockRegistry(getMainFileName(CI.getInvocation()),
144 CI.getASTContext());
145 DigestAnalyzerOptions();
146
147 if (Opts.AnalyzerDisplayProgress || Opts.PrintStats ||
148 Opts.ShouldSerializeStats || !Opts.DumpEntryPointStatsToCSV.empty()) {
149 AnalyzerTimers = std::make_unique<llvm::TimerGroup>(
150 "analyzer", "Analyzer timers");
151 SyntaxCheckTimer = std::make_unique<llvm::Timer>(
152 "syntaxchecks", "Syntax-based analysis time", *AnalyzerTimers);
153 ExprEngineTimer = std::make_unique<llvm::Timer>(
154 "exprengine", "Path exploration time", *AnalyzerTimers);
155 BugReporterTimer = std::make_unique<llvm::Timer>(
156 "bugreporter", "Path-sensitive report post-processing time",
157 *AnalyzerTimers);
158 }
159
160 // Avoid displaying the timers created above in case we only want to record
161 // per-entry-point stats.
162 ShouldClearTimersToPreventDisplayingThem = !Opts.AnalyzerDisplayProgress &&
163 !Opts.PrintStats &&
164 !Opts.ShouldSerializeStats;
165
166 if (Opts.PrintStats || Opts.ShouldSerializeStats) {
167 llvm::EnableStatistics(/* DoPrintOnExit= */ false);
168 }
169
170 if (Opts.ShouldDisplayMacroExpansions)
171 MacroExpansions.registerForPreprocessor(PP);
172
173 // Visitor options.
174 ShouldWalkTypesOfTypeLocs = false;
175 }
176
177 ~AnalysisConsumer() override {
178 if (Opts.PrintStats) {
179 llvm::PrintStatistics();
180 }
181 }
182
183 void DigestAnalyzerOptions() {
184 switch (Opts.AnalysisDiagOpt) {
185 case PD_NONE:
186 break;
187#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATEFN) \
188 case PD_##NAME: \
189 CREATEFN(Opts.getDiagOpts(), PathConsumers, OutDir, PP, CTU, \
190 MacroExpansions); \
191 break;
192#include "clang/StaticAnalyzer/Core/Analyses.def"
193 default:
194 llvm_unreachable("Unknown analyzer output type!");
195 }
196
197 // Create the analyzer component creators.
198 CreateStoreMgr = &CreateRegionStoreManager;
199
200 switch (Opts.AnalysisConstraintsOpt) {
201 default:
202 llvm_unreachable("Unknown constraint manager.");
203#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATEFN) \
204 case NAME##Model: CreateConstraintMgr = CREATEFN; break;
205#include "clang/StaticAnalyzer/Core/Analyses.def"
206 }
207 }
208
209 void DisplayTime(llvm::TimeRecord &Time) {
210 if (!Opts.AnalyzerDisplayProgress) {
211 return;
212 }
213 llvm::errs() << " : " << llvm::format("%1.1f", Time.getWallTime() * 1000)
214 << " ms\n";
215 }
216
217 void DisplayFunction(const Decl *D, AnalysisMode Mode,
219 if (!Opts.AnalyzerDisplayProgress)
220 return;
221
222 SourceManager &SM = Mgr->getASTContext().getSourceManager();
223 PresumedLoc Loc = SM.getPresumedLoc(D->getLocation());
224 if (Loc.isValid()) {
225 llvm::errs() << "ANALYZE";
226
227 if (Mode == AM_Syntax)
228 llvm::errs() << " (Syntax)";
229 else if (Mode == AM_Path) {
230 llvm::errs() << " (Path, ";
231 switch (IMode) {
233 llvm::errs() << " Inline_Minimal";
234 break;
236 llvm::errs() << " Inline_Regular";
237 break;
238 }
239 llvm::errs() << ")";
240 } else
241 assert(Mode == (AM_Syntax | AM_Path) && "Unexpected mode!");
242
243 llvm::errs() << ": " << Loc.getFilename() << ' '
245 }
246 }
247
248 /// Store the top level decls in the set to be processed later on.
249 /// (Doing this pre-processing avoids deserialization of data from PCH.)
250 bool HandleTopLevelDecl(DeclGroupRef D) override;
251 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override;
252
253 void HandleTranslationUnit(ASTContext &C) override;
254
255 /// Determine which inlining mode should be used when this function is
256 /// analyzed. This allows to redefine the default inlining policies when
257 /// analyzing a given function.
259 getInliningModeForFunction(const Decl *D, const SetOfConstDecls &Visited);
260
261 /// Build the call graph for all the top level decls of this TU and
262 /// use it to define the order in which the functions should be visited.
263 void HandleDeclsCallGraph(const unsigned LocalTUDeclsSize);
264
265 /// Run analyzes(syntax or path sensitive) on the given function.
266 /// \param Mode - determines if we are requesting syntax only or path
267 /// sensitive only analysis.
268 /// \param VisitedCallees - The output parameter, which is populated with the
269 /// set of functions which should be considered analyzed after analyzing the
270 /// given root function.
271 void HandleCode(Decl *D, AnalysisMode Mode,
273 SetOfConstDecls *VisitedCallees = nullptr);
274
275 void RunPathSensitiveChecks(Decl *D,
277 SetOfConstDecls *VisitedCallees);
278
279 /// Handle callbacks for arbitrary Decls.
280 bool VisitDecl(Decl *D) override {
281 AnalysisMode Mode = getModeForDecl(D, RecVisitorMode);
282 if (Mode & AM_Syntax) {
283 if (SyntaxCheckTimer)
284 SyntaxCheckTimer->startTimer();
285 checkerMgr->runCheckersOnASTDecl(D, *Mgr, *RecVisitorBR);
286 if (SyntaxCheckTimer)
287 SyntaxCheckTimer->stopTimer();
288 if (AnalyzerTimers && ShouldClearTimersToPreventDisplayingThem) {
289 AnalyzerTimers->clear();
290 }
291 }
292 return true;
293 }
294
295 bool VisitVarDecl(VarDecl *VD) override {
296 if (!Opts.IsNaiveCTUEnabled)
297 return true;
298
299 if (VD->hasExternalStorage() || VD->isStaticDataMember()) {
300 if (!cross_tu::shouldImport(VD, *Ctx))
301 return true;
302 } else {
303 // Cannot be initialized in another TU.
304 return true;
305 }
306
307 if (VD->getAnyInitializer())
308 return true;
309
310 llvm::Expected<const VarDecl *> CTUDeclOrError =
311 CTU.getCrossTUDefinition(VD, Opts.CTUDir, Opts.CTUIndexName,
312 Opts.DisplayCTUProgress);
313
314 if (!CTUDeclOrError) {
315 handleAllErrors(CTUDeclOrError.takeError(),
316 [&](const cross_tu::IndexError &IE) {
317 CTU.emitCrossTUDiagnostics(IE);
318 });
319 }
320
321 return true;
322 }
323
324 bool VisitFunctionDecl(FunctionDecl *FD) override {
325 IdentifierInfo *II = FD->getIdentifier();
326 if (II && II->getName().starts_with("__inline"))
327 return true;
328
329 // We skip function template definitions, as their semantics is
330 // only determined when they are instantiated.
332 !FD->isDependentContext()) {
333 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
334 HandleCode(FD, RecVisitorMode);
335 }
336 return true;
337 }
338
339 bool VisitObjCMethodDecl(ObjCMethodDecl *MD) override {
341 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
342 HandleCode(MD, RecVisitorMode);
343 }
344 return true;
345 }
346
347 bool VisitBlockDecl(BlockDecl *BD) override {
348 if (BD->hasBody()) {
349 assert(RecVisitorMode == AM_Syntax || Mgr->shouldInlineCall() == false);
350 // Since we skip function template definitions, we should skip blocks
351 // declared in those functions as well.
352 if (!BD->isDependentContext()) {
353 HandleCode(BD, RecVisitorMode);
354 }
355 }
356 return true;
357 }
358
359 void AddDiagnosticConsumer(
360 std::unique_ptr<PathDiagnosticConsumer> Consumer) override {
361 PathConsumers.push_back(std::move(Consumer));
362 }
363
364 void AddCheckerRegistrationFn(std::function<void(CheckerRegistry&)> Fn) override {
365 CheckerRegistrationFns.push_back(std::move(Fn));
366 }
367
368private:
369 void storeTopLevelDecls(DeclGroupRef DG);
370
371 /// Check if we should skip (not analyze) the given function.
372 AnalysisMode getModeForDecl(Decl *D, AnalysisMode Mode);
373 void runAnalysisOnTranslationUnit(ASTContext &C);
374
375 /// Print \p S to stderr if \c Opts.AnalyzerDisplayProgress is set.
376 void reportAnalyzerProgress(StringRef S);
377};
378
379std::string timeTraceScopeDeclName(StringRef FunName, const Decl *D) {
380 if (llvm::timeTraceProfilerEnabled()) {
381 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
382 return (FunName + " " + ND->getQualifiedNameAsString()).str();
383 return (FunName + " <anonymous> ").str();
384 }
385 return "";
386}
387
388llvm::TimeTraceMetadata timeTraceScopeDeclMetadata(const Decl *D) {
389 // If time-trace profiler is not enabled, this function is never called.
390 assert(llvm::timeTraceProfilerEnabled());
391 if (const auto &Loc = D->getBeginLoc(); Loc.isValid()) {
392 const auto &SM = D->getASTContext().getSourceManager();
393 std::string DeclName = AnalysisDeclContext::getFunctionName(D);
394 return llvm::TimeTraceMetadata{
395 std::move(DeclName), SM.getFilename(Loc).str(),
396 static_cast<int>(SM.getExpansionLineNumber(Loc))};
397 }
398 return llvm::TimeTraceMetadata{"", ""};
399}
400
401void flushReports(llvm::Timer *BugReporterTimer, BugReporter &BR) {
402 llvm::TimeTraceScope TCS{"Flushing reports"};
403 // Display warnings.
404 if (BugReporterTimer)
405 BugReporterTimer->startTimer();
406 BR.FlushReports();
407 if (BugReporterTimer)
408 BugReporterTimer->stopTimer();
409}
410} // namespace
411
412//===----------------------------------------------------------------------===//
413// AnalysisConsumer implementation.
414//===----------------------------------------------------------------------===//
415bool AnalysisConsumer::HandleTopLevelDecl(DeclGroupRef DG) {
416 storeTopLevelDecls(DG);
417 return true;
418}
419
420void AnalysisConsumer::HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
421 storeTopLevelDecls(DG);
422}
423
424void AnalysisConsumer::storeTopLevelDecls(DeclGroupRef DG) {
425 for (auto &I : DG) {
426
427 // Skip ObjCMethodDecl, wait for the objc container to avoid
428 // analyzing twice.
429 if (isa<ObjCMethodDecl>(I))
430 continue;
431
432 LocalTUDecls.push_back(I);
433 }
434}
435
436static bool shouldSkipFunction(const Decl *D,
437 const SetOfConstDecls &Visited,
438 const SetOfConstDecls &VisitedAsTopLevel) {
439 if (VisitedAsTopLevel.count(D))
440 return true;
441
442 // Skip analysis of inheriting constructors as top-level functions. These
443 // constructors don't even have a body written down in the code, so even if
444 // we find a bug, we won't be able to display it.
445 if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
446 if (CD->isInheritingConstructor())
447 return true;
448
449 // We want to re-analyse the functions as top level in the following cases:
450 // - The 'init' methods should be reanalyzed because
451 // ObjCNonNilReturnValueChecker assumes that '[super init]' never returns
452 // 'nil' and unless we analyze the 'init' functions as top level, we will
453 // not catch errors within defensive code.
454 // - We want to reanalyze all ObjC methods as top level to report Retain
455 // Count naming convention errors more aggressively.
456 if (isa<ObjCMethodDecl>(D))
457 return false;
458 // We also want to reanalyze all C++ copy and move assignment operators to
459 // separately check the two cases where 'this' aliases with the parameter and
460 // where it may not. (cplusplus.SelfAssignmentChecker)
461 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
462 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())
463 return false;
464 }
465
466 // Otherwise, if we visited the function before, do not reanalyze it.
467 return Visited.count(D);
468}
469
471AnalysisConsumer::getInliningModeForFunction(const Decl *D,
472 const SetOfConstDecls &Visited) {
473 // We want to reanalyze all ObjC methods as top level to report Retain
474 // Count naming convention errors more aggressively. But we should tune down
475 // inlining when reanalyzing an already inlined function.
476 if (Visited.count(D) && isa<ObjCMethodDecl>(D)) {
477 const ObjCMethodDecl *ObjCM = cast<ObjCMethodDecl>(D);
478 if (ObjCM->getMethodFamily() != OMF_init)
480 }
481
483}
484
485void AnalysisConsumer::HandleDeclsCallGraph(const unsigned LocalTUDeclsSize) {
486 // Build the Call Graph by adding all the top level declarations to the graph.
487 // Note: CallGraph can trigger deserialization of more items from a pch
488 // (though HandleInterestingDecl); triggering additions to LocalTUDecls.
489 // We rely on random access to add the initially processed Decls to CG.
490 CallGraph CG;
491 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
492 CG.addToCallGraph(LocalTUDecls[i]);
493 }
494
495 // Walk over all of the call graph nodes in topological order, so that we
496 // analyze parents before the children. Skip the functions inlined into
497 // the previously processed functions. Use external Visited set to identify
498 // inlined functions. The topological order allows the "do not reanalyze
499 // previously inlined function" performance heuristic to be triggered more
500 // often.
501 SetOfConstDecls Visited;
502 SetOfConstDecls VisitedAsTopLevel;
503 llvm::ReversePostOrderTraversal<clang::CallGraph*> RPOT(&CG);
504 for (auto &N : RPOT) {
505 NumFunctionTopLevel++;
506
507 Decl *D = N->getDecl();
508
509 // Skip the abstract root node.
510 if (!D)
511 continue;
512
513 // Skip the functions which have been processed already or previously
514 // inlined.
515 if (shouldSkipFunction(D, Visited, VisitedAsTopLevel))
516 continue;
517
518 // The CallGraph might have declarations as callees. However, during CTU
519 // the declaration might form a declaration chain with the newly imported
520 // definition from another TU. In this case we don't want to analyze the
521 // function definition as toplevel.
522 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
523 // Calling 'hasBody' replaces 'FD' in place with the FunctionDecl
524 // that has the body.
525 FD->hasBody(FD);
526 if (CTU.isImportedAsNew(FD))
527 continue;
528 }
529
530 // Analyze the function.
531 SetOfConstDecls VisitedCallees;
532
533 HandleCode(D, AM_Path, getInliningModeForFunction(D, Visited),
534 (Mgr->options.InliningMode == All ? nullptr : &VisitedCallees));
535
536 // Add the visited callees to the global visited set.
537 for (const Decl *Callee : VisitedCallees)
538 // Decls from CallGraph are already canonical. But Decls coming from
539 // CallExprs may be not. We should canonicalize them manually.
540 Visited.insert(isa<ObjCMethodDecl>(Callee) ? Callee
541 : Callee->getCanonicalDecl());
542 VisitedAsTopLevel.insert(D);
543 }
544}
545
546static bool fileContainsString(StringRef Substring, ASTContext &C) {
547 const SourceManager &SM = C.getSourceManager();
548 FileID FID = SM.getMainFileID();
549 StringRef Buffer = SM.getBufferOrFake(FID).getBuffer();
550 return Buffer.contains(Substring);
551}
552
554 const ASTContext &Ctx) {
555 llvm::errs() << "Every top-level function was skipped.\n";
556
557 if (!Opts.AnalyzerDisplayProgress)
558 llvm::errs() << "Pass the -analyzer-display-progress for tracking which "
559 "functions are analyzed.\n";
560
561 bool HasBrackets =
562 Opts.AnalyzeSpecificFunction.find("(") != std::string::npos;
563
564 if (Ctx.getLangOpts().CPlusPlus && !HasBrackets) {
565 llvm::errs()
566 << "For analyzing C++ code you need to pass the function parameter "
567 "list: -analyze-function=\"foobar(int, _Bool)\"\n";
568 } else if (!Ctx.getLangOpts().CPlusPlus && HasBrackets) {
569 llvm::errs() << "For analyzing C code you shouldn't pass the function "
570 "parameter list, only the name of the function: "
571 "-analyze-function=foobar\n";
572 }
573}
574
575void AnalysisConsumer::runAnalysisOnTranslationUnit(ASTContext &C) {
576 BugReporter BR(*Mgr);
577 const TranslationUnitDecl *TU = C.getTranslationUnitDecl();
579 if (SyntaxCheckTimer)
580 SyntaxCheckTimer->startTimer();
581 checkerMgr->runCheckersOnASTDecl(TU, *Mgr, BR);
582 if (SyntaxCheckTimer)
583 SyntaxCheckTimer->stopTimer();
584 if (AnalyzerTimers && ShouldClearTimersToPreventDisplayingThem) {
585 AnalyzerTimers->clear();
586 }
587
588 // Run the AST-only checks using the order in which functions are defined.
589 // If inlining is not turned on, use the simplest function order for path
590 // sensitive analyzes as well.
591 RecVisitorMode = AM_Syntax;
592 if (!Mgr->shouldInlineCall())
593 RecVisitorMode |= AM_Path;
594 RecVisitorBR = &BR;
595
596 // Process all the top level declarations.
597 //
598 // Note: TraverseDecl may modify LocalTUDecls, but only by appending more
599 // entries. Thus we don't use an iterator, but rely on LocalTUDecls
600 // random access. By doing so, we automatically compensate for iterators
601 // possibly being invalidated, although this is a bit slower.
602 const unsigned LocalTUDeclsSize = LocalTUDecls.size();
603 for (unsigned i = 0 ; i < LocalTUDeclsSize ; ++i) {
604 TraverseDecl(LocalTUDecls[i]);
605 }
606
607 if (Mgr->shouldInlineCall())
608 HandleDeclsCallGraph(LocalTUDeclsSize);
609
610 // After all decls handled, run checkers on the entire TranslationUnit.
611 checkerMgr->runCheckersOnEndOfTranslationUnit(TU, *Mgr, BR);
612
613 BR.FlushReports();
614 RecVisitorBR = nullptr;
615
616 // If the user wanted to analyze a specific function and the number of basic
617 // blocks analyzed is zero, than the user might not specified the function
618 // name correctly.
619 if (!Opts.AnalyzeSpecificFunction.empty() && NumFunctionsAnalyzed == 0 &&
620 NumFunctionsAnalyzedSyntaxOnly == 0) {
622 }
623}
624
625void AnalysisConsumer::reportAnalyzerProgress(StringRef S) {
627 llvm::errs() << S;
628}
629
630void AnalysisConsumer::HandleTranslationUnit(ASTContext &C) {
631 // Don't run the actions if an error has occurred with parsing the file.
632 DiagnosticsEngine &Diags = PP.getDiagnostics();
633 if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
634 return;
635
636 Ctx = &C;
637 checkerMgr = std::make_unique<CheckerManager>(*Ctx, Opts, PP, Plugins,
638 CheckerRegistrationFns);
639
640 Mgr = std::make_unique<AnalysisManager>(
641 *Ctx, PP, std::move(PathConsumers), CreateStoreMgr, CreateConstraintMgr,
642 checkerMgr.get(), Opts, std::move(Injector));
643
644 // Explicitly destroy the PathDiagnosticConsumer. This will flush its output.
645 // FIXME: This should be replaced with something that doesn't rely on
646 // side-effects in PathDiagnosticConsumer's destructor. This is required when
647 // used with option -disable-free.
648 const auto DiagFlusherScopeExit =
649 llvm::make_scope_exit([this] { Mgr.reset(); });
650
651 if (Opts.ShouldIgnoreBisonGeneratedFiles &&
652 fileContainsString("/* A Bison parser, made by", C)) {
653 reportAnalyzerProgress("Skipping bison-generated file\n");
654 return;
655 }
656
657 if (Opts.ShouldIgnoreFlexGeneratedFiles &&
658 fileContainsString("/* A lexical scanner generated by flex", C)) {
659 reportAnalyzerProgress("Skipping flex-generated file\n");
660 return;
661 }
662
663 // Don't analyze if the user explicitly asked for no checks to be performed
664 // on this file.
665 if (Opts.DisableAllCheckers) {
666 reportAnalyzerProgress("All checks are disabled using a supplied option\n");
667 return;
668 }
669
670 // Otherwise, just run the analysis.
671 runAnalysisOnTranslationUnit(C);
672
673 // Count how many basic blocks we have not covered.
674 NumBlocksInAnalyzedFunctions = FunctionSummaries.getTotalNumBasicBlocks();
675 NumVisitedBlocksInAnalyzedFunctions =
676 FunctionSummaries.getTotalNumVisitedBasicBlocks();
677 if (NumBlocksInAnalyzedFunctions > 0)
678 PercentReachableBlocks =
679 (FunctionSummaries.getTotalNumVisitedBasicBlocks() * 100) /
680 NumBlocksInAnalyzedFunctions;
681
682 if (!Opts.DumpEntryPointStatsToCSV.empty()) {
683 EntryPointStat::dumpStatsAsCSV(Opts.DumpEntryPointStatsToCSV);
684 }
685}
686
687AnalysisConsumer::AnalysisMode
688AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode Mode) {
689 if (!Opts.AnalyzeSpecificFunction.empty() &&
693 return AM_None;
694 }
695
696 // Unless -analyze-all is specified, treat decls differently depending on
697 // where they came from:
698 // - Main source file: run both path-sensitive and non-path-sensitive checks.
699 // - Header files: run non-path-sensitive checks only.
700 // - System headers: don't run any checks.
701 if (Opts.AnalyzeAll)
702 return Mode;
703
704 const SourceManager &SM = Ctx->getSourceManager();
705
706 const SourceLocation Loc = [&SM](Decl *D) -> SourceLocation {
707 const Stmt *Body = D->getBody();
708 SourceLocation SL = Body ? Body->getBeginLoc() : D->getLocation();
709 return SM.getExpansionLoc(SL);
710 }(D);
711
712 // Ignore system headers.
713 if (Loc.isInvalid() || SM.isInSystemHeader(Loc))
714 return AM_None;
715
716 // Disable path sensitive analysis in user-headers.
717 if (!Mgr->isInCodeFile(Loc))
718 return Mode & ~AM_Path;
719
720 return Mode;
721}
722
723static UnsignedEPStat PathRunningTime("PathRunningTime");
724
725void AnalysisConsumer::HandleCode(Decl *D, AnalysisMode Mode,
727 SetOfConstDecls *VisitedCallees) {
728 llvm::TimeTraceScope TCS(timeTraceScopeDeclName("HandleCode", D),
729 [D]() { return timeTraceScopeDeclMetadata(D); });
730 if (!D->hasBody())
731 return;
732 Mode = getModeForDecl(D, Mode);
733 if (Mode == AM_None)
734 return;
735
736 // Clear the AnalysisManager of old AnalysisDeclContexts.
737 Mgr->ClearContexts();
738 // Ignore autosynthesized code.
739 if (Mgr->getAnalysisDeclContext(D)->isBodyAutosynthesized())
740 return;
741
742 CFG *DeclCFG = Mgr->getCFG(D);
743 if (DeclCFG)
744 MaxCFGSize.updateMax(DeclCFG->size());
745
746 DisplayFunction(D, Mode, IMode);
747 BugReporter BR(*Mgr);
749
750 if (Mode & AM_Syntax) {
751 llvm::TimeRecord CheckerStartTime;
752 if (SyntaxCheckTimer) {
753 CheckerStartTime = SyntaxCheckTimer->getTotalTime();
754 SyntaxCheckTimer->startTimer();
755 }
756 checkerMgr->runCheckersOnASTBody(D, *Mgr, BR);
757 ++NumFunctionsAnalyzedSyntaxOnly;
758 if (SyntaxCheckTimer) {
759 SyntaxCheckTimer->stopTimer();
760 llvm::TimeRecord CheckerEndTime = SyntaxCheckTimer->getTotalTime();
761 CheckerEndTime -= CheckerStartTime;
762 DisplayTime(CheckerEndTime);
763 if (AnalyzerTimers && ShouldClearTimersToPreventDisplayingThem) {
764 AnalyzerTimers->clear();
765 }
766 }
767 }
768
769 BR.FlushReports();
770
771 if ((Mode & AM_Path) && checkerMgr->hasPathSensitiveCheckers()) {
772 RunPathSensitiveChecks(D, IMode, VisitedCallees);
774 if (IMode != ExprEngine::Inline_Minimal)
775 NumFunctionsAnalyzed++;
776 }
777}
778
779//===----------------------------------------------------------------------===//
780// Path-sensitive checking.
781//===----------------------------------------------------------------------===//
782
783void AnalysisConsumer::RunPathSensitiveChecks(Decl *D,
785 SetOfConstDecls *VisitedCallees) {
786 // Construct the analysis engine. First check if the CFG is valid.
787 // FIXME: Inter-procedural analysis will need to handle invalid CFGs.
788 if (!Mgr->getCFG(D))
789 return;
790
791 // See if the LiveVariables analysis scales.
792 if (!Mgr->getAnalysisDeclContext(D)->getAnalysis<RelaxedLiveVariables>())
793 return;
794
795 ExprEngine Eng(CTU, *Mgr, VisitedCallees, &FunctionSummaries, IMode);
796
797 // Execute the worklist algorithm.
798 llvm::TimeRecord ExprEngineStartTime;
799 if (ExprEngineTimer) {
800 ExprEngineStartTime = ExprEngineTimer->getTotalTime();
801 ExprEngineTimer->startTimer();
802 }
803 Eng.ExecuteWorkList(Mgr->getAnalysisDeclContextManager().getStackFrame(D),
804 Mgr->options.MaxNodesPerTopLevelFunction);
805 if (ExprEngineTimer) {
806 ExprEngineTimer->stopTimer();
807 llvm::TimeRecord ExprEngineEndTime = ExprEngineTimer->getTotalTime();
808 ExprEngineEndTime -= ExprEngineStartTime;
809 PathRunningTime.set(static_cast<unsigned>(
810 std::lround(ExprEngineEndTime.getWallTime() * 1000)));
811 DisplayTime(ExprEngineEndTime);
812 if (AnalyzerTimers && ShouldClearTimersToPreventDisplayingThem) {
813 AnalyzerTimers->clear();
814 }
815 }
816
817 if (!Mgr->options.DumpExplodedGraphTo.empty())
818 Eng.DumpGraph(Mgr->options.TrimGraph, Mgr->options.DumpExplodedGraphTo);
819
820 // Visualize the exploded graph.
821 if (Mgr->options.visualizeExplodedGraphWithGraphViz)
822 Eng.ViewGraph(Mgr->options.TrimGraph);
823
824 flushReports(BugReporterTimer.get(), Eng.getBugReporter());
825 if (AnalyzerTimers && ShouldClearTimersToPreventDisplayingThem) {
826 AnalyzerTimers->clear();
827 }
828}
829
830//===----------------------------------------------------------------------===//
831// AnalysisConsumer creation.
832//===----------------------------------------------------------------------===//
833
834std::unique_ptr<AnalysisASTConsumer>
836 // Disable the effects of '-Werror' when using the AnalysisConsumer.
838
839 AnalyzerOptions &analyzerOpts = CI.getAnalyzerOpts();
840 bool hasModelPath = analyzerOpts.Config.count("model-path") > 0;
841
842 return std::make_unique<AnalysisConsumer>(
843 CI, CI.getFrontendOpts().OutputFile, analyzerOpts,
845 hasModelPath ? std::make_unique<ModelInjector>(CI) : nullptr);
846}
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...
#define SM(sm)
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 ...
Definition ASTContext.h:220
SourceManager & getSourceManager()
Definition ASTContext.h:833
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
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 size() const
Return the total number of CFGBlocks within the CFG This is simply a renaming of the getNumBlockIDs()...
Definition CFG.h:1415
void addToCallGraph(Decl *D)
Populate the call graph with the functions in the given declaration.
Definition CallGraph.h:63
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
AnalyzerOptions & getAnalyzerOpts()
Preprocessor & getPreprocessor() const
Return the current preprocessor.
ASTContext & getASTContext() const
FrontendOptions & getFrontendOpts()
CompilerInvocation & getInvocation()
Helper class for holding the data necessary to invoke the compiler.
FrontendOptions & getFrontendOpts()
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
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:1087
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:1093
SourceLocation getLocation() const
Definition DeclBase.h:439
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:431
bool hasErrorOccurred() const
Definition Diagnostic.h:872
void setWarningsAsErrors(bool Val)
When set to true, any warnings reported are issued as errors.
Definition Diagnostic.h:702
bool hasFatalErrorOccurred() const
Definition Diagnostic.h:879
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
An input file for the front end.
llvm::MemoryBufferRef getBuffer() const
StringRef getFile() const
std::string OutputFile
The output file, if any.
std::vector< std::string > Plugins
The list of plugins to load.
SmallVector< FrontendInputFile, 0 > Inputs
The input files and their types.
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2314
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3191
StringRef getName() const
Return the actual identifier string.
This represents a decl that may have a name.
Definition Decl.h:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
bool isThisDeclarationADefinition() const
Returns whether this specific method is a definition.
Definition DeclObjC.h:534
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
Definition Stmt.cpp:346
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1358
static std::optional< std::string > getLookupName(const Decl *D)
Get a name to identify a decl.
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(llvm::StringRef CPPFileName, ASTContext &Ctx)
static void takeSnapshot(const Decl *EntryPoint)
InliningModes
The modes of inlining, which override the default analysis-wide settings.
Definition ExprEngine.h:129
@ Inline_Minimal
Do minimal inlining of callees.
Definition ExprEngine.h:134
@ Inline_Regular
Follow the default settings for inlining callees.
Definition ExprEngine.h:131
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)
Definition Address.h:330
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
#define lround(__x)
Definition tgmath.h:1021