clang 22.0.0git
ExecuteCompilerInvocation.cpp
Go to the documentation of this file.
1//===--- ExecuteCompilerInvocation.cpp ------------------------------------===//
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 file holds ExecuteCompilerInvocation(). It is split into its own file to
10// minimize the impact of pulling in essentially everything else in Clang.
11//
12//===----------------------------------------------------------------------===//
13
15#include "clang/Config/config.h"
28#include "llvm/Option/OptTable.h"
29#include "llvm/Support/BuryPointer.h"
30#include "llvm/Support/DynamicLibrary.h"
31#include "llvm/Support/ErrorHandling.h"
32
33#if CLANG_ENABLE_CIR
34#include "mlir/IR/AsmState.h"
35#include "mlir/IR/MLIRContext.h"
36#include "mlir/Pass/PassManager.h"
39#endif
40
41using namespace clang;
42using namespace llvm::opt;
43
44namespace clang {
45
46static std::unique_ptr<FrontendAction>
48 using namespace clang::frontend;
49 StringRef Action("unknown");
50 (void)Action;
51
52 unsigned UseCIR = CI.getFrontendOpts().UseClangIRPipeline;
54 bool EmitsCIR = Act == EmitCIR;
55
56 if (!UseCIR && EmitsCIR)
57 llvm::report_fatal_error("-emit-cir and only valid when using -fclangir");
58
59 switch (CI.getFrontendOpts().ProgramAction) {
60 case ASTDeclList: return std::make_unique<ASTDeclListAction>();
61 case ASTDump: return std::make_unique<ASTDumpAction>();
62 case ASTPrint: return std::make_unique<ASTPrintAction>();
63 case ASTView: return std::make_unique<ASTViewAction>();
65 return std::make_unique<DumpCompilerOptionsAction>();
66 case DumpRawTokens: return std::make_unique<DumpRawTokensAction>();
67 case DumpTokens: return std::make_unique<DumpTokensAction>();
68 case EmitAssembly:
69#if CLANG_ENABLE_CIR
70 if (UseCIR)
71 return std::make_unique<cir::EmitAssemblyAction>();
72#endif
73 return std::make_unique<EmitAssemblyAction>();
74 case EmitBC:
75#if CLANG_ENABLE_CIR
76 if (UseCIR)
77 return std::make_unique<cir::EmitBCAction>();
78#endif
79 return std::make_unique<EmitBCAction>();
80 case EmitCIR:
81#if CLANG_ENABLE_CIR
82 return std::make_unique<cir::EmitCIRAction>();
83#else
84 CI.getDiagnostics().Report(diag::err_fe_cir_not_built);
85 return nullptr;
86#endif
87 case EmitHTML: return std::make_unique<HTMLPrintAction>();
88 case EmitLLVM: {
89#if CLANG_ENABLE_CIR
90 if (UseCIR)
91 return std::make_unique<cir::EmitLLVMAction>();
92#endif
93 return std::make_unique<EmitLLVMAction>();
94 }
95 case EmitLLVMOnly: return std::make_unique<EmitLLVMOnlyAction>();
96 case EmitCodeGenOnly: return std::make_unique<EmitCodeGenOnlyAction>();
97 case EmitObj:
98#if CLANG_ENABLE_CIR
99 if (UseCIR)
100 return std::make_unique<cir::EmitObjAction>();
101#endif
102 return std::make_unique<EmitObjAction>();
103 case ExtractAPI:
104 return std::make_unique<ExtractAPIAction>();
105 case FixIt: return std::make_unique<FixItAction>();
106 case GenerateModule:
107 return std::make_unique<GenerateModuleFromModuleMapAction>();
109 return std::make_unique<GenerateModuleInterfaceAction>();
111 return std::make_unique<GenerateReducedModuleInterfaceAction>();
113 return std::make_unique<GenerateHeaderUnitAction>();
114 case GeneratePCH: return std::make_unique<GeneratePCHAction>();
116 return std::make_unique<GenerateInterfaceStubsAction>();
117 case InitOnly: return std::make_unique<InitOnlyAction>();
118 case ParseSyntaxOnly: return std::make_unique<SyntaxOnlyAction>();
119 case ModuleFileInfo: return std::make_unique<DumpModuleInfoAction>();
120 case VerifyPCH: return std::make_unique<VerifyPCHAction>();
121 case TemplightDump: return std::make_unique<TemplightDumpAction>();
122
123 case PluginAction: {
124 for (const FrontendPluginRegistry::entry &Plugin :
125 FrontendPluginRegistry::entries()) {
126 if (Plugin.getName() == CI.getFrontendOpts().ActionName) {
127 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
128 if ((P->getActionType() != PluginASTAction::ReplaceAction &&
129 P->getActionType() != PluginASTAction::CmdlineAfterMainAction) ||
130 !P->ParseArgs(
131 CI,
132 CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
133 return nullptr;
134 return std::move(P);
135 }
136 }
137
138 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
140 return nullptr;
141 }
142
143 case PrintPreamble: return std::make_unique<PrintPreambleAction>();
147 return std::make_unique<RewriteIncludesAction>();
148 return std::make_unique<PrintPreprocessedAction>();
149 }
150
151 case RewriteMacros: return std::make_unique<RewriteMacrosAction>();
152 case RewriteTest: return std::make_unique<RewriteTestAction>();
153#if CLANG_ENABLE_OBJC_REWRITER
154 case RewriteObjC: return std::make_unique<RewriteObjCAction>();
155#else
156 case RewriteObjC: Action = "RewriteObjC"; break;
157#endif
158#if CLANG_ENABLE_STATIC_ANALYZER
159 case RunAnalysis: return std::make_unique<ento::AnalysisAction>();
160#else
161 case RunAnalysis: Action = "RunAnalysis"; break;
162#endif
163 case RunPreprocessorOnly: return std::make_unique<PreprocessOnlyAction>();
165 return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
166 }
167
168#if !CLANG_ENABLE_STATIC_ANALYZER || !CLANG_ENABLE_OBJC_REWRITER
169 CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
170 return 0;
171#else
172 llvm_unreachable("Invalid program action!");
173#endif
174}
175
176std::unique_ptr<FrontendAction>
178 // Create the underlying action.
179 std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
180 if (!Act)
181 return nullptr;
182
183 const FrontendOptions &FEOpts = CI.getFrontendOpts();
184
185 if (CI.getLangOpts().HLSL)
186 Act = std::make_unique<HLSLFrontendAction>(std::move(Act));
187
188 if (FEOpts.FixAndRecompile) {
189 Act = std::make_unique<FixItRecompile>(std::move(Act));
190 }
191
192 // Wrap the base FE action in an extract api action to generate
193 // symbol graph as a biproduct of compilation (enabled with
194 // --emit-symbol-graph option)
195 if (FEOpts.EmitSymbolGraph) {
196 if (FEOpts.SymbolGraphOutputDir.empty()) {
197 CI.getDiagnostics().Report(diag::warn_missing_symbol_graph_dir);
199 }
200 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
201 Act = std::make_unique<WrappingExtractAPIAction>(std::move(Act));
202 }
203
204 // If there are any AST files to merge, create a frontend action
205 // adaptor to perform the merge.
206 if (!FEOpts.ASTMergeFiles.empty())
207 Act = std::make_unique<ASTMergeAction>(std::move(Act),
208 FEOpts.ASTMergeFiles);
209
210 return Act;
211}
212
214 unsigned NumErrorsBefore = Clang->getDiagnostics().getNumErrors();
215
216 // Honor -help.
217 if (Clang->getFrontendOpts().ShowHelp) {
218 driver::getDriverOptTable().printHelp(
219 llvm::outs(), "clang -cc1 [options] file...",
220 "LLVM 'Clang' Compiler: http://clang.llvm.org",
221 /*ShowHidden=*/false, /*ShowAllAliases=*/false,
222 llvm::opt::Visibility(driver::options::CC1Option));
223 return true;
224 }
225
226 // Honor -version.
227 //
228 // FIXME: Use a better -version message?
229 if (Clang->getFrontendOpts().ShowVersion) {
230 llvm::cl::PrintVersionMessage();
231 return true;
232 }
233
234 Clang->LoadRequestedPlugins();
235
236 // Honor -mllvm.
237 //
238 // FIXME: Remove this, one day.
239 // This should happen AFTER plugins have been loaded!
240 if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
241 unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
242 auto Args = std::make_unique<const char*[]>(NumArgs + 2);
243 Args[0] = "clang (LLVM option parsing)";
244 for (unsigned i = 0; i != NumArgs; ++i)
245 Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
246 Args[NumArgs + 1] = nullptr;
247 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(), /*Overview=*/"",
248 /*Errs=*/nullptr,
249 /*VFS=*/&Clang->getVirtualFileSystem());
250 }
251
252#if CLANG_ENABLE_STATIC_ANALYZER
253 // These should happen AFTER plugins have been loaded!
254
255 AnalyzerOptions &AnOpts = Clang->getAnalyzerOpts();
256
257 // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
258 if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
260 ento::printCheckerHelp(llvm::outs(), *Clang);
261 return true;
262 }
263
264 // Honor -analyzer-checker-option-help.
267 ento::printCheckerConfigList(llvm::outs(), *Clang);
268 return true;
269 }
270
271 // Honor -analyzer-list-enabled-checkers.
272 if (AnOpts.ShowEnabledCheckerList) {
273 ento::printEnabledCheckerList(llvm::outs(), *Clang);
274 return true;
275 }
276
277 // Honor -analyzer-config-help.
278 if (AnOpts.ShowConfigOptionsList) {
279 ento::printAnalyzerConfigList(llvm::outs());
280 return true;
281 }
282#endif
283
284#if CLANG_ENABLE_CIR
285 if (!Clang->getFrontendOpts().MLIRArgs.empty()) {
286 mlir::registerCIRPasses();
287 mlir::registerMLIRContextCLOptions();
288 mlir::registerPassManagerCLOptions();
289 mlir::registerAsmPrinterCLOptions();
290 unsigned NumArgs = Clang->getFrontendOpts().MLIRArgs.size();
291 auto Args = std::make_unique<const char *[]>(NumArgs + 2);
292 Args[0] = "clang (MLIR option parsing)";
293 for (unsigned i = 0; i != NumArgs; ++i)
294 Args[i + 1] = Clang->getFrontendOpts().MLIRArgs[i].c_str();
295 Args[NumArgs + 1] = nullptr;
296 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
297 }
298#endif
299
300 // If there were errors in the above, don't do anything else.
301 // This intentionally ignores errors emitted before this function to
302 // accommodate lenient callers that decided to make progress despite errors.
303 if (Clang->getDiagnostics().getNumErrors() != NumErrorsBefore)
304 return false;
305
306 // Create and execute the frontend action.
307 std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
308 if (!Act)
309 return false;
310 bool Success = Clang->ExecuteAction(*Act);
311 if (Clang->getFrontendOpts().DisableFree)
312 llvm::BuryPointer(std::move(Act));
313 return Success;
314}
315
316} // namespace clang
This file defines the ExtractAPIAction and WrappingExtractAPIAction frontend actions.
Stores options for the analyzer from the command line.
unsigned ShowCheckerOptionDeveloperList
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
AnalyzerOptions & getAnalyzerOpts()
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
PreprocessorOutputOptions & getPreprocessorOutputOpts()
void LoadRequestedPlugins()
Load the list of plugins requested in the FrontendOptions.
FrontendOptions & getFrontendOpts()
llvm::vfs::FileSystem & getVirtualFileSystem() const
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
CodeGenOptions & getCodeGenOpts()
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
unsigned getNumErrors() const
Definition Diagnostic.h:885
FrontendOptions - Options for controlling the behavior of the frontend.
unsigned EmitSymbolGraph
Whether to emit symbol graph files as a side effect of compilation.
std::map< std::string, std::vector< std::string > > PluginArgs
Args to pass to the plugins.
std::vector< std::string > MLIRArgs
A list of arguments to forward to MLIR's option processing; this should only be used for debugging an...
std::vector< std::string > LLVMArgs
A list of arguments to forward to LLVM's option processing; this should only be used for debugging an...
unsigned ShowHelp
Show the -help text.
unsigned FixAndRecompile
Apply fixes and recompile.
unsigned UseClangIRPipeline
Use Clang IR pipeline to emit code.
std::string ActionName
The name of the action to run when using a plugin action.
unsigned ShowVersion
Show the -version text.
std::vector< std::string > ASTMergeFiles
The list of AST files to merge.
unsigned DisableFree
Disable memory freeing on exit.
frontend::ActionKind ProgramAction
The frontend action to perform.
@ ReplaceAction
Replace the main action.
@ CmdlineAfterMainAction
Execute the action after the main action if on the command line.
unsigned RewriteIncludes
Preprocess include directives only.
unsigned RewriteImports
Include contents of transitively-imported modules.
const llvm::opt::OptTable & getDriverOptTable()
void printEnabledCheckerList(llvm::raw_ostream &OS, CompilerInstance &CI)
void printCheckerHelp(llvm::raw_ostream &OS, CompilerInstance &CI)
void printAnalyzerConfigList(llvm::raw_ostream &OS)
void printCheckerConfigList(llvm::raw_ostream &OS, CompilerInstance &CI)
@ GenerateHeaderUnit
Generate a C++20 header unit module from a header file.
@ VerifyPCH
Load and verify that a PCH file is usable.
@ PrintPreprocessedInput
-E mode.
@ RewriteTest
Rewriter playground.
@ ParseSyntaxOnly
Parse and perform semantic analysis.
@ TemplightDump
Dump template instantiations.
@ EmitBC
Emit a .bc file.
@ GenerateModuleInterface
Generate pre-compiled module from a standard C++ module interface unit.
@ EmitLLVM
Emit a .ll file.
@ PrintPreamble
Print the "preamble" of the input file.
@ InitOnly
Only execute frontend initialization.
@ ASTView
Parse ASTs and view them in Graphviz.
@ PluginAction
Run a plugin action,.
@ EmitObj
Emit a .o file.
@ DumpRawTokens
Dump out raw tokens.
@ PrintDependencyDirectivesSourceMinimizerOutput
Print the output of the dependency directives source minimizer.
@ RewriteObjC
ObjC->C Rewriter.
@ RunPreprocessorOnly
Just lex, no output.
@ EmitCIR
Emit a .cir file.
@ DumpCompilerOptions
Dump the compiler configuration.
@ RunAnalysis
Run one or more source code analyses.
@ ASTPrint
Parse ASTs and print them.
@ GenerateReducedModuleInterface
Generate reduced module interface for a standard C++ module interface unit.
@ GenerateInterfaceStubs
Generate Interface Stub Files.
@ ASTDump
Parse ASTs and dump them.
@ DumpTokens
Dump out preprocessed tokens.
@ FixIt
Parse and apply any fixits to the source.
@ EmitAssembly
Emit a .s file.
@ EmitCodeGenOnly
Generate machine code, but don't emit anything.
@ RewriteMacros
Expand macros but not #includes.
@ EmitHTML
Translate input source into HTML.
@ GeneratePCH
Generate pre-compiled header.
@ EmitLLVMOnly
Generate LLVM IR, but do not emit anything.
@ GenerateModule
Generate pre-compiled module from a module map.
@ ASTDeclList
Parse ASTs and list Decl nodes.
The JSON file list parser is used to communicate input to InstallAPI.
static std::unique_ptr< FrontendAction > CreateFrontendBaseAction(CompilerInstance &CI)
@ Success
Annotation was successful.
Definition Parser.h:65
bool ExecuteCompilerInvocation(CompilerInstance *Clang)
ExecuteCompilerInvocation - Execute the given actions described by the compiler invocation object in ...
std::unique_ptr< FrontendAction > CreateFrontendAction(CompilerInstance &CI)
Construct the FrontendAction of a compiler invocation based on the options specified for the compiler...