clang 22.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"
24#include "llvm/ADT/IntrusiveRefCntPtr.h"
25#include "llvm/ADT/ArrayRef.h"
26#include <memory>
27#include <string>
28
29namespace llvm {
30
31class Triple;
32
33namespace opt {
34
35class ArgList;
36
37} // namespace opt
38
39namespace vfs {
40
41class FileSystem;
42
43} // namespace vfs
44
45} // namespace llvm
46
47namespace clang {
48
52class TargetOptions;
53
54// This lets us create the DiagnosticsEngine with a properly-filled-out
55// DiagnosticOptions instance.
56std::unique_ptr<DiagnosticOptions>
58
59/// Fill out Opts based on the options given in Args.
60///
61/// Args must have been created from the OptTable returned by
62/// createCC1OptTable().
63///
64/// When errors are encountered, return false and, if Diags is non-null,
65/// report the error(s).
66bool ParseDiagnosticArgs(DiagnosticOptions &Opts, llvm::opt::ArgList &Args,
67 DiagnosticsEngine *Diags = nullptr,
68 bool DefaultDiagColor = true);
69
70unsigned getOptimizationLevel(const llvm::opt::ArgList &Args, InputKind IK,
71 DiagnosticsEngine &Diags);
72
73unsigned getOptimizationLevelSize(const llvm::opt::ArgList &Args);
74
75/// The base class of CompilerInvocation. It keeps individual option objects
76/// behind reference-counted pointers, which is useful for clients that want to
77/// keep select option objects alive (even after CompilerInvocation gets
78/// destroyed) without making a copy.
80protected:
81 /// Options controlling the language variant.
82 std::shared_ptr<LangOptions> LangOpts;
83
84 /// Options controlling the target.
85 std::shared_ptr<TargetOptions> TargetOpts;
86
87 /// Options controlling the diagnostic engine.
88 std::shared_ptr<DiagnosticOptions> DiagnosticOpts;
89
90 /// Options controlling the \#include directive.
91 std::shared_ptr<HeaderSearchOptions> HSOpts;
92
93 /// Options controlling the preprocessor (aside from \#include handling).
94 std::shared_ptr<PreprocessorOptions> PPOpts;
95
96 /// Options controlling the static analyzer.
97 std::shared_ptr<AnalyzerOptions> AnalyzerOpts;
98
99 std::shared_ptr<MigratorOptions> MigratorOpts;
100
101 /// Options controlling API notes.
102 std::shared_ptr<APINotesOptions> APINotesOpts;
103
104 /// Options controlling IRgen and the backend.
105 std::shared_ptr<CodeGenOptions> CodeGenOpts;
106
107 /// Options controlling file system operations.
108 std::shared_ptr<FileSystemOptions> FSOpts;
109
110 /// Options controlling the frontend itself.
111 std::shared_ptr<FrontendOptions> FrontendOpts;
112
113 /// Options controlling dependency output.
114 std::shared_ptr<DependencyOutputOptions> DependencyOutputOpts;
115
116 /// Options controlling preprocessed output.
117 std::shared_ptr<PreprocessorOutputOptions> PreprocessorOutputOpts;
118
119 /// Dummy tag type whose instance can be passed into the constructor to
120 /// prevent creation of the reference-counted option objects.
122
132
133public:
134 /// Const getters.
135 /// @{
136 const LangOptions &getLangOpts() const { return *LangOpts; }
137 const TargetOptions &getTargetOpts() const { return *TargetOpts; }
141 const AnalyzerOptions &getAnalyzerOpts() const { return *AnalyzerOpts; }
142 const MigratorOptions &getMigratorOpts() const { return *MigratorOpts; }
143 const APINotesOptions &getAPINotesOpts() const { return *APINotesOpts; }
144 const CodeGenOptions &getCodeGenOpts() const { return *CodeGenOpts; }
145 const FileSystemOptions &getFileSystemOpts() const { return *FSOpts; }
146 const FrontendOptions &getFrontendOpts() const { return *FrontendOpts; }
153 /// @}
154
155 /// Visitation.
156 /// @{
157 /// Visits paths stored in the invocation. The callback may return true to
158 /// short-circuit the visitation, or return false to continue visiting.
159 void visitPaths(llvm::function_ref<bool(StringRef)> Callback) const;
160 /// @}
161
162 /// Command line generation.
163 /// @{
164 using StringAllocator = llvm::function_ref<const char *(const Twine &)>;
165 /// Generate cc1-compatible command line arguments from this instance.
166 ///
167 /// \param [out] Args - The generated arguments. Note that the caller is
168 /// responsible for inserting the path to the clang executable and "-cc1" if
169 /// desired.
170 /// \param SA - A function that given a Twine can allocate storage for a given
171 /// command line argument and return a pointer to the newly allocated string.
172 /// The returned pointer is what gets appended to Args.
174 StringAllocator SA) const {
175 generateCC1CommandLine([&](const Twine &Arg) {
176 // No need to allocate static string literals.
177 Args.push_back(Arg.isSingleStringLiteral()
178 ? Arg.getSingleStringRef().data()
179 : SA(Arg));
180 });
181 }
182
183 using ArgumentConsumer = llvm::function_ref<void(const Twine &)>;
184 /// Generate cc1-compatible command line arguments from this instance.
185 ///
186 /// \param Consumer - Callback that gets invoked for every single generated
187 /// command line argument.
188 void generateCC1CommandLine(ArgumentConsumer Consumer) const;
189
190 /// Generate cc1-compatible command line arguments from this instance,
191 /// wrapping the result as a std::vector<std::string>.
192 ///
193 /// This is a (less-efficient) wrapper over generateCC1CommandLine().
194 std::vector<std::string> getCC1CommandLine() const;
195
196protected:
197 /// Visits paths stored in the invocation. This is generally unsafe to call
198 /// directly, and each sub-class need to ensure calling this doesn't violate
199 /// its invariants.
200 void visitPathsImpl(llvm::function_ref<bool(std::string &)> Predicate);
201
202private:
203 /// Generate command line options from DiagnosticOptions.
204 static void GenerateDiagnosticArgs(const DiagnosticOptions &Opts,
205 ArgumentConsumer Consumer,
206 bool DefaultDiagColor);
207
208 /// Generate command line options from LangOptions.
209 static void GenerateLangArgs(const LangOptions &Opts,
210 ArgumentConsumer Consumer, const llvm::Triple &T,
211 InputKind IK);
212
213 // Generate command line options from CodeGenOptions.
214 static void GenerateCodeGenArgs(const CodeGenOptions &Opts,
215 ArgumentConsumer Consumer,
216 const llvm::Triple &T,
217 const std::string &OutputFile,
218 const LangOptions *LangOpts);
219 /// @}
220};
221
223
224/// Helper class for holding the data necessary to invoke the compiler.
225///
226/// This class is designed to represent an abstract "invocation" of the
227/// compiler, including data such as the include paths, the code generation
228/// options, the warning flags, and so on.
230public:
239 return *this;
240 }
242
245
246 /// Const getters.
247 /// @{
248 // Note: These need to be pulled in manually. Otherwise, they get hidden by
249 // the mutable getters with the same names.
263 /// @}
264
265 /// Mutable getters.
266 /// @{
284 /// @}
285
286 /// Create a compiler invocation from a list of input options.
287 /// \returns true on success.
288 ///
289 /// \returns false if an error was encountered while parsing the arguments
290 /// and attempts to recover and continue parsing the rest of the arguments.
291 /// The recovery is best-effort and only guarantees that \p Res will end up in
292 /// one of the vaild-to-access (albeit arbitrary) states.
293 ///
294 /// \param [out] Res - The resulting invocation.
295 /// \param [in] CommandLineArgs - Array of argument strings, this must not
296 /// contain "-cc1".
297 static bool CreateFromArgs(CompilerInvocation &Res,
298 ArrayRef<const char *> CommandLineArgs,
299 DiagnosticsEngine &Diags,
300 const char *Argv0 = nullptr);
301
302 /// Populate \p Opts with the default set of pointer authentication-related
303 /// options given \p LangOpts and \p Triple.
304 ///
305 /// Note: This is intended to be used by tools which must be aware of
306 /// pointer authentication-related code generation, e.g. lldb.
308 const LangOptions &LangOpts,
309 const llvm::Triple &Triple);
310
311 /// Retrieve a module hash string that is suitable for uniquely
312 /// identifying the conditions under which the module was built.
313 std::string getModuleHash() const;
314
315 /// Check that \p Args can be parsed and re-serialized without change,
316 /// emiting diagnostics for any differences.
317 ///
318 /// This check is only suitable for command-lines that are expected to already
319 /// be canonical.
320 ///
321 /// \return false if there are any errors.
323 DiagnosticsEngine &Diags,
324 const char *Argv0 = nullptr);
325
326 /// Reset all of the options that are not considered when building a
327 /// module.
329
330 /// Disable implicit modules and canonicalize options that are only used by
331 /// implicit modules.
333
334private:
335 static bool CreateFromArgsImpl(CompilerInvocation &Res,
336 ArrayRef<const char *> CommandLineArgs,
337 DiagnosticsEngine &Diags, const char *Argv0);
338
339 /// Parse command line options that map to LangOptions.
340 static bool ParseLangArgs(LangOptions &Opts, llvm::opt::ArgList &Args,
341 InputKind IK, const llvm::Triple &T,
342 std::vector<std::string> &Includes,
343 DiagnosticsEngine &Diags);
344
345 /// Parse command line options that map to CodeGenOptions.
346 static bool ParseCodeGenArgs(CodeGenOptions &Opts, llvm::opt::ArgList &Args,
347 InputKind IK, DiagnosticsEngine &Diags,
348 const llvm::Triple &T,
349 const std::string &OutputFile,
350 const LangOptions &LangOptsRef);
351};
352
353/// Same as \c CompilerInvocation, but with copy-on-write optimization.
395
396IntrusiveRefCntPtr<llvm::vfs::FileSystem>
397createVFSFromCompilerInvocation(const CompilerInvocation &CI,
398 DiagnosticsEngine &Diags);
399
400IntrusiveRefCntPtr<llvm::vfs::FileSystem> createVFSFromCompilerInvocation(
401 const CompilerInvocation &CI, DiagnosticsEngine &Diags,
402 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS);
403
404IntrusiveRefCntPtr<llvm::vfs::FileSystem>
406 DiagnosticsEngine &Diags,
407 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS);
408
409} // namespace clang
410
411#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
const CodeGenOptions & getCodeGenOpts() const
void visitPathsImpl(llvm::function_ref< bool(std::string &)> Predicate)
Visits paths stored in the invocation.
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
void visitPaths(llvm::function_ref< bool(StringRef)> Callback) const
Visitation.
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.
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()
void resetNonModularOptions()
Reset all of the options that are not considered when building a module.
FrontendOptions & getFrontendOpts()
std::string getModuleHash() const
Retrieve a module hash string that is suitable for uniquely identifying the conditions under which th...
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()
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()
CowCompilerInvocation(const CompilerInvocation &X)
DiagnosticOptions & getMutDiagnosticOpts()
CowCompilerInvocation(const CowCompilerInvocation &X)
DependencyOutputOptions & getMutDependencyOutputOpts()
CowCompilerInvocation & operator=(const CowCompilerInvocation &X)
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.
The JSON file list parser is used to communicate input to InstallAPI.
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...