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