clang 24.0.0git
CompilerInvocation.h
Go to the documentation of this file.
1//===- CompilerInvocation.h - Compiler Invocation Helper Data ---*- 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#ifndef LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
10#define LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
11
16#include "clang/Basic/LLVM.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/IntrusiveRefCntPtr.h"
25#include "llvm/ADT/ScopeExit.h"
26#include "llvm/Support/VirtualFileSystemFwd.h"
27
28#include <memory>
29#include <string>
30
31namespace llvm {
32
33class Triple;
34
35namespace opt {
36
37class ArgList;
38
39} // namespace opt
40
41} // namespace llvm
42
43namespace clang {
44
45class AnalyzerOptions;
49class TargetOptions;
50
51namespace ssaf {
52class SSAFOptions;
53} // namespace ssaf
54
55// This lets us create the DiagnosticsEngine with a properly-filled-out
56// DiagnosticOptions instance.
57std::unique_ptr<DiagnosticOptions>
59
60/// Fill out Opts based on the options given in Args.
61///
62/// Args must have been created from the OptTable returned by
63/// createCC1OptTable().
64///
65/// When errors are encountered, return false and, if Diags is non-null,
66/// report the error(s).
67bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args,
68 DiagnosticsEngine *Diags = nullptr,
69 bool DefaultDiagColor = true);
70
71unsigned getOptimizationLevel(const llvm::opt::ArgList &Args, InputKind IK,
72 DiagnosticsEngine &Diags);
73
74unsigned getOptimizationLevelSize(const llvm::opt::ArgList &Args);
75
76/// The base class of CompilerInvocation. It keeps individual option objects
77/// behind reference-counted pointers, which is useful for clients that want to
78/// keep select option objects alive (even after CompilerInvocation gets
79/// destroyed) without making a copy.
81protected:
82 /// Options controlling the language variant.
83 std::shared_ptr<LangOptions> LangOpts;
84
85 /// Options controlling the target.
86 std::shared_ptr<TargetOptions> TargetOpts;
87
88 /// Options controlling the diagnostic engine.
89 std::shared_ptr<DiagnosticOptions> DiagnosticOpts;
90
91 /// Options controlling the \#include directive.
92 std::shared_ptr<HeaderSearchOptions> HSOpts;
93
94 /// Options controlling the preprocessor (aside from \#include handling).
95 std::shared_ptr<PreprocessorOptions> PPOpts;
96
97 /// Options controlling the static analyzer.
98 std::shared_ptr<AnalyzerOptions> AnalyzerOpts;
99
100 std::shared_ptr<MigratorOptions> MigratorOpts;
101
102 /// Options controlling API notes.
103 std::shared_ptr<APINotesOptions> APINotesOpts;
104
105 /// Options controlling IRgen and the backend.
106 std::shared_ptr<CodeGenOptions> CodeGenOpts;
107
108 /// Options controlling file system operations.
109 std::shared_ptr<FileSystemOptions> FSOpts;
110
111 /// Options controlling the frontend itself.
112 std::shared_ptr<FrontendOptions> FrontendOpts;
113
114 /// Options controlling dependency output.
115 std::shared_ptr<DependencyOutputOptions> DependencyOutputOpts;
116
117 /// Options controlling preprocessed output.
118 std::shared_ptr<PreprocessorOutputOptions> PreprocessorOutputOpts;
119
120 /// Options controlling the Scalable Static Analysis Framework (SSAF).
121 std::shared_ptr<ssaf::SSAFOptions> SSAFOpts;
122
123 /// Dummy tag type whose instance can be passed into the constructor to
124 /// prevent creation of the reference-counted option objects.
126
127 /// Tag for the shallow-copy constructor below.
129
139
140public:
141 /// Const getters.
142 /// @{
143 const LangOptions &getLangOpts() const { return *LangOpts; }
144 const TargetOptions &getTargetOpts() const { return *TargetOpts; }
148 const AnalyzerOptions &getAnalyzerOpts() const { return *AnalyzerOpts; }
149 const MigratorOptions &getMigratorOpts() const { return *MigratorOpts; }
150 const APINotesOptions &getAPINotesOpts() const { return *APINotesOpts; }
151 const CodeGenOptions &getCodeGenOpts() const { return *CodeGenOpts; }
152 const FileSystemOptions &getFileSystemOpts() const { return *FSOpts; }
153 const FrontendOptions &getFrontendOpts() const { return *FrontendOpts; }
160 const ssaf::SSAFOptions &getSSAFOpts() const { return *SSAFOpts; }
161 /// @}
162
163 /// Command line generation.
164 /// @{
165 using StringAllocator = llvm::function_ref<const char *(const Twine &)>;
166 /// Generate cc1-compatible command line arguments from this instance.
167 ///
168 /// \param [out] Args - The generated arguments. Note that the caller is
169 /// responsible for inserting the path to the clang executable and "-cc1" if
170 /// desired.
171 /// \param SA - A function that given a Twine can allocate storage for a given
172 /// command line argument and return a pointer to the newly allocated string.
173 /// The returned pointer is what gets appended to Args.
175 StringAllocator SA) const {
176 generateCC1CommandLine([&](const Twine &Arg) {
177 // No need to allocate static string literals.
178 Args.push_back(Arg.isSingleStringLiteral()
179 ? Arg.getSingleStringRef().data()
180 : SA(Arg));
181 });
182 }
183
184 using ArgumentConsumer = llvm::function_ref<void(const Twine &)>;
185 /// Generate cc1-compatible command line arguments from this instance.
186 ///
187 /// \param Consumer - Callback that gets invoked for every single generated
188 /// command line argument.
189 void generateCC1CommandLine(ArgumentConsumer Consumer) const;
190
191 /// Generate cc1-compatible command line arguments from this instance,
192 /// wrapping the result as a std::vector<std::string>.
193 ///
194 /// This is a (less-efficient) wrapper over generateCC1CommandLine().
195 std::vector<std::string> getCC1CommandLine() const;
196
197private:
198 /// Generate command line options from DiagnosticOptions.
199 static void GenerateDiagnosticArgs(const DiagnosticOptions &Opts,
200 ArgumentConsumer Consumer,
201 bool DefaultDiagColor);
202
203 /// Generate command line options from LangOptions.
204 static void GenerateLangArgs(const LangOptions &Opts,
205 ArgumentConsumer Consumer, const llvm::Triple &T,
206 InputKind IK);
207
208 // Generate command line options from CodeGenOptions.
209 static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
210 ArgumentConsumer Consumer,
211 const llvm::Triple &T,
212 const std::string &OutputFile,
213 const LangOptions *LangOpts);
214 /// @}
215};
216
218
219/// Helper class for holding the data necessary to invoke the compiler.
220///
221/// This class is designed to represent an abstract "invocation" of the
222/// compiler, including data such as the include paths, the code generation
223/// options, the warning flags, and so on.
225public:
234 return *this;
235 }
237
240
241 /// Move-construct/move-assign from a \c CowCompilerInvocation. Steals the
242 /// (potentially copy-on-written) option group pointers without deep-copying;
243 /// \p X is left empty. Useful to receive results of mutating a temporary
244 /// Cow alias back into a \c CompilerInvocation.
245 /// @{
248 /// @}
249
250 /// Const getters.
251 /// @{
252 // Note: These need to be pulled in manually. Otherwise, they get hidden by
253 // the mutable getters with the same names.
268 /// @}
269
270 /// Mutable getters.
271 /// @{
290 /// @}
291
292 /// Invokes the \a Fn with CowCompilerInvocation representing \c this.
293 /// The \a Fn must not directly modify \c this.
294 /// The provided \c CowCompilerInvocation must not escape \a Fn.
295 template <class R>
296 R withCowRef(llvm::function_ref<R(CowCompilerInvocation &)> Fn);
297 template <class R>
298 R withCowRef(llvm::function_ref<R(const CowCompilerInvocation &)> Fn) const;
299
300 /// Create a compiler invocation from a list of input options.
301 /// \returns true on success.
302 ///
303 /// \returns false if an error was encountered while parsing the arguments
304 /// and attempts to recover and continue parsing the rest of the arguments.
305 /// The recovery is best-effort and only guarantees that \p Res will end up in
306 /// one of the vaild-to-access (albeit arbitrary) states.
307 ///
308 /// \param [out] Res - The resulting invocation.
309 /// \param [in] CommandLineArgs - Array of argument strings, this must not
310 /// contain "-cc1".
311 static bool CreateFromArgs(CompilerInvocation &Res,
312 ArrayRef<const char *> CommandLineArgs,
313 DiagnosticsEngine &Diags,
314 const char *Argv0 = nullptr);
315
316 /// Populate \p Opts with the default set of pointer authentication-related
317 /// options given \p LangOpts and \p Triple.
318 ///
319 /// Note: This is intended to be used by tools which must be aware of
320 /// pointer authentication-related code generation, e.g. lldb.
322 const LangOptions &LangOpts,
323 const llvm::Triple &Triple);
324
325 /// Compute the context hash - a string that uniquely identifies compiler
326 /// settings.
327 /// This is currently used mainly for distinguishing different variants of the
328 /// same implicitly-built Clang module.
329 std::string computeContextHash() const;
330
331 /// Check that \p Args can be parsed and re-serialized without change,
332 /// emiting diagnostics for any differences.
333 ///
334 /// This check is only suitable for command-lines that are expected to already
335 /// be canonical.
336 ///
337 /// \return false if there are any errors.
339 DiagnosticsEngine &Diags,
340 const char *Argv0 = nullptr);
341
342 /// Reset all of the options that are not considered when building a
343 /// module.
345
346 /// Disable implicit modules and canonicalize options that are only used by
347 /// implicit modules.
349
350private:
351 static bool CreateFromArgsImpl(CompilerInvocation &Res,
352 ArrayRef<const char *> CommandLineArgs,
353 DiagnosticsEngine &Diags, const char *Argv0);
354
355 /// Parse command line options that map to LangOptions.
356 static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
357 InputKind IK, const llvm::Triple &T,
358 std::vector<std::string> &Includes,
359 DiagnosticsEngine &Diags);
360
361 /// Parse command line options that map to CodeGenOptions.
362 static bool ParseCodeGenArgs(CodeGenOptions &Opts, llvm::opt::ArgList &Args,
363 InputKind IK, DiagnosticsEngine &Diags,
364 const llvm::Triple &T,
365 const std::string &OutputFile,
366 const LangOptions &LangOptsRef);
367};
368
369/// Same as \c CompilerInvocation, but with copy-on-write optimization.
371public:
383
388
391
392 /// Construct a CowCompilerInvocation that aliases the option storage of \p
393 /// X without deep-copying. Subsequent mutations through getMut*Opts() will
394 /// copy-on-write per group as usual, leaving \p X unaffected. The caller
395 /// must guarantee that \p X is not mutated for the lifetime of the
396 /// constructed invocation.
401
402 // Const getters are inherited from the base class.
403
404 /// Mutable getters.
405 /// @{
420 /// @}
421
422 /// The result of mutable visitation.
424 /// Whether to replace the given StringRef with the modified std::string &.
425 bool Replace = false;
426 /// Whether to short-circuit the visitation.
427 bool Terminate = false;
428 };
429
430 /// Visits paths stored in the invocation, allowing the callback to mutate
431 /// them via the out-param. This upholds the same copy-on-write semantics as
432 /// the mutable getters.
433 void visitMutPaths(
434 llvm::function_ref<VisitMutResult(StringRef, std::string &)> Cb);
435
436 /// The result of const visitation.
438 /// Whether to short-circuit the visitation.
439 bool Terminate = false;
440
441 operator VisitMutResult() const { return {/*Replace=*/false, Terminate}; }
442 };
443
444 /// Visits paths stored in the invocation.
445 void visitPaths(llvm::function_ref<VisitConstResult(StringRef)> Cb) const;
446};
447
448template <class R>
450 llvm::function_ref<R(CowCompilerInvocation &)> Fn) {
451 // We use moves to avoid bumping the ref-count of the shared_ptr that holds
452 // individual options. Since we expect \a Fn to actually modify \c CowRef,
453 // this prevents temporary copies.
454 CowCompilerInvocation CowRef = std::move(*this);
455 llvm::scope_exit Mutate([&]() { *this = std::move(CowRef); });
456 return Fn(CowRef);
457}
458
459template <class R>
461 llvm::function_ref<R(const CowCompilerInvocation &)> Fn) const {
462 // We use the shallow constructor. Since \a Fn cannot modify \c CowRef, no
463 // copies will be created, despite the bump to the ref-count of the shared_ptr
464 // that holds individual options.
466 return Fn(CowRef);
467}
468
471
472inline CompilerInvocation &
477
480 DiagnosticsEngine &Diags);
481
483 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
485
488 DiagnosticsEngine &Diags,
490
491} // namespace clang
492
493#endif // LLVM_CLANG_FRONTEND_COMPILERINVOCATION_H
Defines the clang::FileSystemOptions interface.
#define X(type, name)
Definition Value.h:97
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
Tracks various options which control how API notes are found and handled.
Stores options for the analyzer from the command line.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
std::shared_ptr< DiagnosticOptions > DiagnosticOpts
Options controlling the diagnostic engine.
std::shared_ptr< AnalyzerOptions > AnalyzerOpts
Options controlling the static analyzer.
std::shared_ptr< MigratorOptions > MigratorOpts
std::shared_ptr< PreprocessorOutputOptions > PreprocessorOutputOpts
Options controlling preprocessed output.
std::shared_ptr< APINotesOptions > APINotesOpts
Options controlling API notes.
std::shared_ptr< TargetOptions > TargetOpts
Options controlling the target.
const FrontendOptions & getFrontendOpts() const
std::shared_ptr< ssaf::SSAFOptions > SSAFOpts
Options controlling the Scalable Static Analysis Framework (SSAF).
const CodeGenOptions & getCodeGenOpts() const
CompilerInvocationBase(CompilerInvocationBase &&X)=default
llvm::function_ref< const char *(const Twine &)> StringAllocator
Command line generation.
const FileSystemOptions & getFileSystemOpts() const
std::shared_ptr< PreprocessorOptions > PPOpts
Options controlling the preprocessor (aside from #include handling).
const PreprocessorOutputOptions & getPreprocessorOutputOpts() const
const ssaf::SSAFOptions & getSSAFOpts() const
std::vector< std::string > getCC1CommandLine() const
Generate cc1-compatible command line arguments from this instance, wrapping the result as a std::vect...
std::shared_ptr< FileSystemOptions > FSOpts
Options controlling file system operations.
const AnalyzerOptions & getAnalyzerOpts() const
const MigratorOptions & getMigratorOpts() const
void generateCC1CommandLine(llvm::SmallVectorImpl< const char * > &Args, StringAllocator SA) const
Generate cc1-compatible command line arguments from this instance.
CompilerInvocationBase & deep_copy_assign(const CompilerInvocationBase &X)
const DependencyOutputOptions & getDependencyOutputOpts() const
CompilerInvocationBase & shallow_copy_assign(const CompilerInvocationBase &X)
CompilerInvocationBase(const CompilerInvocationBase &X)=delete
const TargetOptions & getTargetOpts() const
CompilerInvocationBase & operator=(CompilerInvocationBase &&X)=default
std::shared_ptr< CodeGenOptions > CodeGenOpts
Options controlling IRgen and the backend.
CompilerInvocationBase & operator=(const CompilerInvocationBase &X)=delete
std::shared_ptr< LangOptions > LangOpts
Options controlling the language variant.
const APINotesOptions & getAPINotesOpts() const
const HeaderSearchOptions & getHeaderSearchOpts() const
std::shared_ptr< HeaderSearchOptions > HSOpts
Options controlling the #include directive.
const PreprocessorOptions & getPreprocessorOpts() const
const DiagnosticOptions & getDiagnosticOpts() const
const LangOptions & getLangOpts() const
Const getters.
std::shared_ptr< FrontendOptions > FrontendOpts
Options controlling the frontend itself.
llvm::function_ref< void(const Twine &)> ArgumentConsumer
std::shared_ptr< DependencyOutputOptions > DependencyOutputOpts
Options controlling dependency output.
Helper class for holding the data necessary to invoke the compiler.
PreprocessorOptions & getPreprocessorOpts()
void clearImplicitModuleBuildOptions()
Disable implicit modules and canonicalize options that are only used by implicit modules.
MigratorOptions & getMigratorOpts()
AnalyzerOptions & getAnalyzerOpts()
APINotesOptions & getAPINotesOpts()
static bool CreateFromArgs(CompilerInvocation &Res, ArrayRef< const char * > CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Create a compiler invocation from a list of input options.
ssaf::SSAFOptions & getSSAFOpts()
LangOptions & getLangOpts()
Mutable getters.
static bool checkCC1RoundTrip(ArrayRef< const char * > Args, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Check that Args can be parsed and re-serialized without change, emiting diagnostics for any differenc...
DependencyOutputOptions & getDependencyOutputOpts()
R withCowRef(llvm::function_ref< R(CowCompilerInvocation &)> Fn)
Invokes the Fn with CowCompilerInvocation representing this.
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
FrontendOptions & getFrontendOpts()
CompilerInvocation(const CompilerInvocation &X)
FileSystemOptions & getFileSystemOpts()
CompilerInvocation(CompilerInvocation &&)=default
CompilerInvocation & operator=(const CompilerInvocation &X)
static void setDefaultPointerAuthOptions(PointerAuthOptions &Opts, const LangOptions &LangOpts, const llvm::Triple &Triple)
Populate Opts with the default set of pointer authentication-related options given LangOpts and Tripl...
CodeGenOptions & getCodeGenOpts()
std::string computeContextHash() const
Compute the context hash - a string that uniquely identifies compiler settings.
HeaderSearchOptions & getHeaderSearchOpts()
DiagnosticOptions & getDiagnosticOpts()
PreprocessorOutputOptions & getPreprocessorOutputOpts()
Same as CompilerInvocation, but with copy-on-write optimization.
LangOptions & getMutLangOpts()
Mutable getters.
HeaderSearchOptions & getMutHeaderSearchOpts()
CowCompilerInvocation(CowCompilerInvocation &&)=default
PreprocessorOptions & getMutPreprocessorOpts()
PreprocessorOutputOptions & getMutPreprocessorOutputOpts()
FileSystemOptions & getMutFileSystemOpts()
void visitMutPaths(llvm::function_ref< VisitMutResult(StringRef, std::string &)> Cb)
Visits paths stored in the invocation, allowing the callback to mutate them via the out-param.
CowCompilerInvocation(const CompilerInvocation &X)
DiagnosticOptions & getMutDiagnosticOpts()
CowCompilerInvocation(const CowCompilerInvocation &X)
DependencyOutputOptions & getMutDependencyOutputOpts()
CowCompilerInvocation(ShallowConstructor, const CompilerInvocation &X)
Construct a CowCompilerInvocation that aliases the option storage of X without deep-copying.
void visitPaths(llvm::function_ref< VisitConstResult(StringRef)> Cb) const
Visits paths stored in the invocation.
CowCompilerInvocation & operator=(const CowCompilerInvocation &X)
ssaf::SSAFOptions & getMutSSAFOpts()
CowCompilerInvocation(CompilerInvocation &&X)
DependencyOutputOptions - Options for controlling the compiler dependency file generation.
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
Keeps track of options that affect how file operations are performed.
FrontendOptions - Options for controlling the behavior of the frontend.
HeaderSearchOptions - Helper class for storing options related to the initialization of the HeaderSea...
The kind of a file that we've been handed as an input.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
PreprocessorOptions - This class is used for passing the various options used in preprocessor initial...
PreprocessorOutputOptions - Options for controlling the C preprocessor output (e.g....
Options for controlling the target.
Top level wrappers for InstallAPI frontend operations.
bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args, DiagnosticsEngine *Diags=nullptr, bool DefaultDiagColor=true)
Fill out Opts based on the options given in Args.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromOverlayFiles(ArrayRef< std::string > VFSOverlayFiles, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< llvm::vfs::FileSystem > BaseFS)
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
unsigned getOptimizationLevel(const llvm::opt::ArgList &Args, InputKind IK, DiagnosticsEngine &Diags)
const FunctionProtoType * T
IntrusiveRefCntPtr< llvm::vfs::FileSystem > createVFSFromCompilerInvocation(const CompilerInvocation &CI, DiagnosticsEngine &Diags)
unsigned getOptimizationLevelSize(const llvm::opt::ArgList &Args)
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
Dummy tag type whose instance can be passed into the constructor to prevent creation of the reference...
Tag for the shallow-copy constructor below.
bool Terminate
Whether to short-circuit the visitation.
bool Replace
Whether to replace the given StringRef with the modified std::string &.
bool Terminate
Whether to short-circuit the visitation.