clang 20.0.0git
AnalyzerOptions.h
Go to the documentation of this file.
1//===- AnalyzerOptions.h - Analysis Engine Options --------------*- C++ -*-===//
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// This header defines various options for the static analyzer that are set
10// by the frontend and are consulted throughout the analyzer.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
15#define LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
16
18#include "clang/Basic/LLVM.h"
19#include "llvm/ADT/IntrusiveRefCntPtr.h"
20#include "llvm/ADT/StringMap.h"
21#include "llvm/ADT/StringRef.h"
22#include <string>
23#include <utility>
24#include <vector>
25
26namespace clang {
27
28namespace ento {
29
30class CheckerBase;
31
32} // namespace ento
33
34/// AnalysisConstraints - Set of available constraint models.
36#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) NAME##Model,
37#include "clang/StaticAnalyzer/Core/Analyses.def"
39};
40
41/// AnalysisDiagClients - Set of available diagnostic clients for rendering
42/// analysis results.
44#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) PD_##NAME,
45#include "clang/StaticAnalyzer/Core/Analyses.def"
48};
49
50/// AnalysisPurgeModes - Set of available strategies for dead symbol removal.
52#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) NAME,
53#include "clang/StaticAnalyzer/Core/Analyses.def"
55};
56
57/// AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
59#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) NAME,
60#include "clang/StaticAnalyzer/Core/Analyses.def"
62};
63
64/// Describes the different kinds of C++ member functions which can be
65/// considered for inlining by the analyzer.
66///
67/// These options are cumulative; enabling one kind of member function will
68/// enable all kinds with lower enum values.
70 // Uninitialized = 0,
71
72 /// A dummy mode in which no C++ inlining is enabled.
74
75 /// Refers to regular member function and operator calls.
77
78 /// Refers to constructors (implicit or explicit).
79 ///
80 /// Note that a constructor will not be inlined if the corresponding
81 /// destructor is non-trivial.
83
84 /// Refers to destructors (implicit or explicit).
86};
87
88/// Describes the different modes of inter-procedural analysis.
89enum IPAKind {
90 /// Perform only intra-procedural analysis.
92
93 /// Inline C functions and blocks when their definitions are available.
95
96 /// Inline callees(C, C++, ObjC) when their definitions are available.
98
99 /// Enable inlining of dynamically dispatched methods.
101
102 /// Enable inlining of dynamically dispatched methods, bifurcate paths when
103 /// exact type info is unavailable.
106
108 DFS,
109 BFS,
114};
115
116/// Describes the kinds for high-level analyzer mode.
118 /// Perform shallow but fast analyzes.
120
121 /// Perform deep analyzes.
122 UMK_Deep = 2
124
126
128public:
132
133 static std::optional<PositiveAnalyzerOption> create(unsigned Val) {
134 if (Val == 0)
135 return std::nullopt;
136 return PositiveAnalyzerOption{Val};
137 }
138 static std::optional<PositiveAnalyzerOption> create(StringRef Str) {
139 unsigned Parsed = 0;
140 if (Str.getAsInteger(0, Parsed))
141 return std::nullopt;
142 return PositiveAnalyzerOption::create(Parsed);
143 }
144 operator unsigned() const { return Value; }
145
146private:
147 explicit constexpr PositiveAnalyzerOption(unsigned Value) : Value(Value) {}
148
149 unsigned Value = 1;
150};
151
152/// Stores options for the analyzer from the command line.
153///
154/// Some options are frontend flags (e.g.: -analyzer-output), but some are
155/// analyzer configuration options, which are preceded by -analyzer-config
156/// (e.g.: -analyzer-config notes-as-events=true).
157///
158/// If you'd like to add a new frontend flag, add it to
159/// include/clang/Driver/CC1Options.td, add a new field to store the value of
160/// that flag in this class, and initialize it in
161/// lib/Frontend/CompilerInvocation.cpp.
162///
163/// If you'd like to add a new non-checker configuration, register it in
164/// include/clang/StaticAnalyzer/Core/AnalyzerOptions.def, and refer to the
165/// top of the file for documentation.
166///
167/// If you'd like to add a new checker option, call getChecker*Option()
168/// whenever.
169///
170/// Some of the options are controlled by raw frontend flags for no good reason,
171/// and should be eventually converted into -analyzer-config flags. New analyzer
172/// options should not be implemented as frontend flags. Frontend flags still
173/// make sense for things that do not affect the actual analysis.
174class AnalyzerOptions : public RefCountedBase<AnalyzerOptions> {
175public:
176 using ConfigTable = llvm::StringMap<std::string>;
177
178 /// Retrieves the list of checkers generated from Checkers.td. This doesn't
179 /// contain statically linked but non-generated checkers and plugin checkers!
180 static std::vector<StringRef>
181 getRegisteredCheckers(bool IncludeExperimental = false);
182
183 /// Retrieves the list of packages generated from Checkers.td. This doesn't
184 /// contain statically linked but non-generated packages and plugin packages!
185 static std::vector<StringRef>
186 getRegisteredPackages(bool IncludeExperimental = false);
187
188 /// Convenience function for printing options or checkers and their
189 /// description in a formatted manner. If \p MinLineWidth is set to 0, no line
190 /// breaks are introduced for the description.
191 ///
192 /// Format, depending whether the option name's length is less than
193 /// \p EntryWidth:
194 ///
195 /// <padding>EntryName<padding>Description
196 /// <---------padding--------->Description
197 /// <---------padding--------->Description
198 ///
199 /// <padding>VeryVeryLongEntryName
200 /// <---------padding--------->Description
201 /// <---------padding--------->Description
202 /// ^~~~~~~~~InitialPad
203 /// ^~~~~~~~~~~~~~~~~~EntryWidth
204 /// ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~MinLineWidth
205 static void printFormattedEntry(llvm::raw_ostream &Out,
206 std::pair<StringRef, StringRef> EntryDescPair,
207 size_t InitialPad, size_t EntryWidth,
208 size_t MinLineWidth = 0);
209
210 /// Pairs of checker/package name and enable/disable.
211 std::vector<std::pair<std::string, bool>> CheckersAndPackages;
212
213 /// Vector of checker/package names which will not emit warnings.
214 std::vector<std::string> SilencedCheckersAndPackages;
215
216 /// A key-value table of use-specified configuration values.
217 // TODO: This shouldn't be public.
222
224
225 /// File path to which the exploded graph should be dumped.
227
228 /// Store full compiler invocation for reproducible instructions in the
229 /// generated report.
231
232 /// The maximum number of times the analyzer visits a block.
234
235 /// Disable all analyzer checkers.
236 ///
237 /// This flag allows one to disable analyzer checkers on the code processed by
238 /// the given analysis consumer. Note, the code will get parsed and the
239 /// command-line options will get checked.
240 unsigned DisableAllCheckers : 1;
241
242 unsigned ShowCheckerHelp : 1;
245
249
253 unsigned AnalyzeAll : 1;
256
257 unsigned TrimGraph : 1;
259 unsigned UnoptimizedCFG : 1;
260 unsigned PrintStats : 1;
261
262 /// Do not re-analyze paths leading to exhausted nodes with a different
263 /// strategy. We get better code coverage when retry is enabled.
264 unsigned NoRetryExhausted : 1;
265
266 /// Emit analyzer warnings as errors.
268
269 /// The inlining stack depth limit.
271
272 /// The mode of function selection used during inlining.
274
275 // Create a field for each -analyzer-config option.
276#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
277 SHALLOW_VAL, DEEP_VAL) \
278 ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, SHALLOW_VAL)
279
280#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
281 TYPE NAME;
282
283#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
284#undef ANALYZER_OPTION
285#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
286
287 bool isUnknownAnalyzerConfig(llvm::StringRef Name) {
288 static std::vector<llvm::StringLiteral> AnalyzerConfigCmdFlags = []() {
289 // Create an array of all -analyzer-config command line options.
290 std::vector<llvm::StringLiteral> AnalyzerConfigCmdFlags = {
291#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
292 SHALLOW_VAL, DEEP_VAL) \
293 ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, SHALLOW_VAL)
294
295#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
296 llvm::StringLiteral(CMDFLAG),
297
298#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
299#undef ANALYZER_OPTION
300#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
301 };
302 // FIXME: Sort this at compile-time when we get constexpr sort (C++20).
303 llvm::sort(AnalyzerConfigCmdFlags);
304 return AnalyzerConfigCmdFlags;
305 }();
306
307 return !std::binary_search(AnalyzerConfigCmdFlags.begin(),
308 AnalyzerConfigCmdFlags.end(), Name);
309 }
310
322
323 /// Interprets an option's string value as a boolean. The "true" string is
324 /// interpreted as true and the "false" string is interpreted as false.
325 ///
326 /// If an option value is not provided, returns the given \p DefaultVal.
327 /// @param [in] CheckerName The *full name* of the checker. One may retrieve
328 /// this from the checker object's field \c Name, or through \c
329 /// CheckerManager::getCurrentCheckerName within the checker's registry
330 /// function.
331 /// Checker options are retrieved in the following format:
332 /// `-analyzer-config CheckerName:OptionName=Value.
333 /// @param [in] OptionName Name for option to retrieve.
334 /// @param [in] SearchInParents If set to true and the searched option was not
335 /// specified for the given checker the options for the parent packages will
336 /// be searched as well. The inner packages take precedence over the outer
337 /// ones.
338 bool getCheckerBooleanOption(StringRef CheckerName, StringRef OptionName,
339 bool SearchInParents = false) const;
340
341 bool getCheckerBooleanOption(const ento::CheckerBase *C, StringRef OptionName,
342 bool SearchInParents = false) const;
343
344 /// Interprets an option's string value as an integer value.
345 ///
346 /// If an option value is not provided, returns the given \p DefaultVal.
347 /// @param [in] CheckerName The *full name* of the checker. One may retrieve
348 /// this from the checker object's field \c Name, or through \c
349 /// CheckerManager::getCurrentCheckerName within the checker's registry
350 /// function.
351 /// Checker options are retrieved in the following format:
352 /// `-analyzer-config CheckerName:OptionName=Value.
353 /// @param [in] OptionName Name for option to retrieve.
354 /// @param [in] SearchInParents If set to true and the searched option was not
355 /// specified for the given checker the options for the parent packages will
356 /// be searched as well. The inner packages take precedence over the outer
357 /// ones.
358 int getCheckerIntegerOption(StringRef CheckerName, StringRef OptionName,
359 bool SearchInParents = false) const;
360
361 int getCheckerIntegerOption(const ento::CheckerBase *C, StringRef OptionName,
362 bool SearchInParents = false) const;
363
364 /// Query an option's string value.
365 ///
366 /// If an option value is not provided, returns the given \p DefaultVal.
367 /// @param [in] CheckerName The *full name* of the checker. One may retrieve
368 /// this from the checker object's field \c Name, or through \c
369 /// CheckerManager::getCurrentCheckerName within the checker's registry
370 /// function.
371 /// Checker options are retrieved in the following format:
372 /// `-analyzer-config CheckerName:OptionName=Value.
373 /// @param [in] OptionName Name for option to retrieve.
374 /// @param [in] SearchInParents If set to true and the searched option was not
375 /// specified for the given checker the options for the parent packages will
376 /// be searched as well. The inner packages take precedence over the outer
377 /// ones.
378 StringRef getCheckerStringOption(StringRef CheckerName, StringRef OptionName,
379 bool SearchInParents = false) const;
380
382 StringRef OptionName,
383 bool SearchInParents = false) const;
384
387
388 /// Returns the inter-procedural analysis mode.
389 IPAKind getIPAMode() const;
390
391 /// Returns the option controlling which C++ member functions will be
392 /// considered for inlining.
393 ///
394 /// This is controlled by the 'c++-inlining' config option.
395 ///
396 /// \sa CXXMemberInliningMode
398
401 ShouldDisplayMacroExpansions,
402 ShouldSerializeStats,
403 // The stable report filename option is deprecated because
404 // file names are now always stable. Now the old option acts as
405 // an alias to the new verbose filename option because this
406 // closely mimics the behavior under the old option.
407 ShouldWriteStableReportFilename || ShouldWriteVerboseReportFilename,
409 ShouldApplyFixIts,
410 ShouldDisplayCheckerNameForText};
411 }
412};
413
415
416//===----------------------------------------------------------------------===//
417// We'll use AnalyzerOptions in the frontend, but we can't link the frontend
418// with clangStaticAnalyzerCore, because clangStaticAnalyzerCore depends on
419// clangFrontend.
420//
421// For this reason, implement some methods in this header file.
422//===----------------------------------------------------------------------===//
423
424inline std::vector<StringRef>
425AnalyzerOptions::getRegisteredCheckers(bool IncludeExperimental) {
426 static constexpr llvm::StringLiteral StaticAnalyzerCheckerNames[] = {
427#define GET_CHECKERS
428#define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \
429 llvm::StringLiteral(FULLNAME),
430#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
431#undef CHECKER
432#undef GET_CHECKERS
433 };
434 std::vector<StringRef> Checkers;
435 for (StringRef CheckerName : StaticAnalyzerCheckerNames) {
436 if (!CheckerName.starts_with("debug.") &&
437 (IncludeExperimental || !CheckerName.starts_with("alpha.")))
438 Checkers.push_back(CheckerName);
439 }
440 return Checkers;
441}
442
443inline std::vector<StringRef>
444AnalyzerOptions::getRegisteredPackages(bool IncludeExperimental) {
445 static constexpr llvm::StringLiteral StaticAnalyzerPackageNames[] = {
446#define GET_PACKAGES
447#define PACKAGE(FULLNAME) llvm::StringLiteral(FULLNAME),
448#include "clang/StaticAnalyzer/Checkers/Checkers.inc"
449#undef PACKAGE
450#undef GET_PACKAGES
451 };
452 std::vector<StringRef> Packages;
453 for (StringRef PackageName : StaticAnalyzerPackageNames) {
454 if (PackageName != "debug" &&
455 (IncludeExperimental || PackageName != "alpha"))
456 Packages.push_back(PackageName);
457 }
458 return Packages;
459}
460
461} // namespace clang
462
463#endif // LLVM_CLANG_STATICANALYZER_CORE_ANALYZEROPTIONS_H
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Stores options for the analyzer from the command line.
static std::vector< StringRef > getRegisteredPackages(bool IncludeExperimental=false)
Retrieves the list of packages generated from Checkers.td.
std::vector< std::pair< std::string, bool > > CheckersAndPackages
Pairs of checker/package name and enable/disable.
unsigned ShowCheckerOptionDeveloperList
unsigned DisableAllCheckers
Disable all analyzer checkers.
std::vector< std::string > SilencedCheckersAndPackages
Vector of checker/package names which will not emit warnings.
unsigned NoRetryExhausted
Do not re-analyze paths leading to exhausted nodes with a different strategy.
AnalysisDiagClients AnalysisDiagOpt
bool mayInlineCXXMemberFunction(CXXInlineableMemberKind K) const
Returns the option controlling which C++ member functions will be considered for inlining.
AnalysisConstraints AnalysisConstraintsOpt
unsigned visualizeExplodedGraphWithGraphViz
bool AnalyzerWerror
Emit analyzer warnings as errors.
unsigned AnalyzerNoteAnalysisEntryPoints
ConfigTable Config
A key-value table of use-specified configuration values.
bool getCheckerBooleanOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Interprets an option's string value as a boolean.
unsigned maxBlockVisitOnPath
The maximum number of times the analyzer visits a block.
std::string AnalyzeSpecificFunction
IPAKind getIPAMode() const
Returns the inter-procedural analysis mode.
std::string DumpExplodedGraphTo
File path to which the exploded graph should be dumped.
unsigned ShouldEmitErrorsOnInvalidConfigValue
ento::PathDiagnosticConsumerOptions getDiagOpts() const
CTUPhase1InliningKind getCTUPhase1Inlining() const
AnalysisPurgeMode AnalysisPurgeOpt
bool isUnknownAnalyzerConfig(llvm::StringRef Name)
static std::vector< StringRef > getRegisteredCheckers(bool IncludeExperimental=false)
Retrieves the list of checkers generated from Checkers.td.
unsigned InlineMaxStackDepth
The inlining stack depth limit.
llvm::StringMap< std::string > ConfigTable
int getCheckerIntegerOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Interprets an option's string value as an integer value.
static void printFormattedEntry(llvm::raw_ostream &Out, std::pair< StringRef, StringRef > EntryDescPair, size_t InitialPad, size_t EntryWidth, size_t MinLineWidth=0)
Convenience function for printing options or checkers and their description in a formatted manner.
ExplorationStrategyKind getExplorationStrategy() const
StringRef getCheckerStringOption(StringRef CheckerName, StringRef OptionName, bool SearchInParents=false) const
Query an option's string value.
std::string FullCompilerInvocation
Store full compiler invocation for reproducible instructions in the generated report.
AnalysisInliningMode InliningMode
The mode of function selection used during inlining.
static std::optional< PositiveAnalyzerOption > create(StringRef Str)
PositiveAnalyzerOption & operator=(const PositiveAnalyzerOption &)=default
static std::optional< PositiveAnalyzerOption > create(unsigned Val)
PositiveAnalyzerOption(const PositiveAnalyzerOption &)=default
The JSON file list parser is used to communicate input to InstallAPI.
UserModeKind
Describes the kinds for high-level analyzer mode.
@ UMK_Deep
Perform deep analyzes.
@ UMK_Shallow
Perform shallow but fast analyzes.
IPAKind
Describes the different modes of inter-procedural analysis.
@ IPAK_Inlining
Inline callees(C, C++, ObjC) when their definitions are available.
@ IPAK_BasicInlining
Inline C functions and blocks when their definitions are available.
@ IPAK_None
Perform only intra-procedural analysis.
@ IPAK_DynamicDispatch
Enable inlining of dynamically dispatched methods.
@ IPAK_DynamicDispatchBifurcate
Enable inlining of dynamically dispatched methods, bifurcate paths when exact type info is unavailabl...
AnalysisConstraints
AnalysisConstraints - Set of available constraint models.
@ NumConstraints
CXXInlineableMemberKind
Describes the different kinds of C++ member functions which can be considered for inlining by the ana...
@ CIMK_Destructors
Refers to destructors (implicit or explicit).
@ CIMK_MemberFunctions
Refers to regular member function and operator calls.
@ CIMK_Constructors
Refers to constructors (implicit or explicit).
@ CIMK_None
A dummy mode in which no C++ inlining is enabled.
AnalysisPurgeMode
AnalysisPurgeModes - Set of available strategies for dead symbol removal.
@ NumPurgeModes
CTUPhase1InliningKind
AnalysisDiagClients
AnalysisDiagClients - Set of available diagnostic clients for rendering analysis results.
@ NUM_ANALYSIS_DIAG_CLIENTS
AnalysisInliningMode
AnalysisInlineFunctionSelection - Set of inlining function selection heuristics.
@ NumInliningModes
@ None
The alignment was not explicit in code.
ExplorationStrategyKind
#define false
Definition: stdbool.h:26
These options tweak the behavior of path diangostic consumers.