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>();
64 case DumpCompilerOptions:
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 llvm_unreachable("CIR suppport not built into clang");
85#endif
86 case EmitHTML: return std::make_unique<HTMLPrintAction>();
87 case EmitLLVM: {
88#if CLANG_ENABLE_CIR
89 if (UseCIR)
90 return std::make_unique<cir::EmitLLVMAction>();
91#endif
92 return std::make_unique<EmitLLVMAction>();
93 }
94 case EmitLLVMOnly: return std::make_unique<EmitLLVMOnlyAction>();
95 case EmitCodeGenOnly: return std::make_unique<EmitCodeGenOnlyAction>();
96 case EmitObj:
97#if CLANG_ENABLE_CIR
98 if (UseCIR)
99 return std::make_unique<cir::EmitObjAction>();
100#endif
101 return std::make_unique<EmitObjAction>();
102 case ExtractAPI:
103 return std::make_unique<ExtractAPIAction>();
104 case FixIt: return std::make_unique<FixItAction>();
105 case GenerateModule:
106 return std::make_unique<GenerateModuleFromModuleMapAction>();
107 case GenerateModuleInterface:
108 return std::make_unique<GenerateModuleInterfaceAction>();
109 case GenerateReducedModuleInterface:
110 return std::make_unique<GenerateReducedModuleInterfaceAction>();
111 case GenerateHeaderUnit:
112 return std::make_unique<GenerateHeaderUnitAction>();
113 case GeneratePCH: return std::make_unique<GeneratePCHAction>();
114 case GenerateInterfaceStubs:
115 return std::make_unique<GenerateInterfaceStubsAction>();
116 case InitOnly: return std::make_unique<InitOnlyAction>();
117 case ParseSyntaxOnly: return std::make_unique<SyntaxOnlyAction>();
118 case ModuleFileInfo: return std::make_unique<DumpModuleInfoAction>();
119 case VerifyPCH: return std::make_unique<VerifyPCHAction>();
120 case TemplightDump: return std::make_unique<TemplightDumpAction>();
121
122 case PluginAction: {
123 for (const FrontendPluginRegistry::entry &Plugin :
124 FrontendPluginRegistry::entries()) {
125 if (Plugin.getName() == CI.getFrontendOpts().ActionName) {
126 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
127 if ((P->getActionType() != PluginASTAction::ReplaceAction &&
128 P->getActionType() != PluginASTAction::CmdlineAfterMainAction) ||
129 !P->ParseArgs(
130 CI,
131 CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
132 return nullptr;
133 return std::move(P);
134 }
135 }
136
137 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
139 return nullptr;
140 }
141
142 case PrintPreamble: return std::make_unique<PrintPreambleAction>();
143 case PrintPreprocessedInput: {
146 return std::make_unique<RewriteIncludesAction>();
147 return std::make_unique<PrintPreprocessedAction>();
148 }
149
150 case RewriteMacros: return std::make_unique<RewriteMacrosAction>();
151 case RewriteTest: return std::make_unique<RewriteTestAction>();
152#if CLANG_ENABLE_OBJC_REWRITER
153 case RewriteObjC: return std::make_unique<RewriteObjCAction>();
154#else
155 case RewriteObjC: Action = "RewriteObjC"; break;
156#endif
157#if CLANG_ENABLE_STATIC_ANALYZER
158 case RunAnalysis: return std::make_unique<ento::AnalysisAction>();
159#else
160 case RunAnalysis: Action = "RunAnalysis"; break;
161#endif
162 case RunPreprocessorOnly: return std::make_unique<PreprocessOnlyAction>();
163 case PrintDependencyDirectivesSourceMinimizerOutput:
164 return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
165 }
166
167#if !CLANG_ENABLE_STATIC_ANALYZER || !CLANG_ENABLE_OBJC_REWRITER
168 CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
169 return 0;
170#else
171 llvm_unreachable("Invalid program action!");
172#endif
173}
174
175std::unique_ptr<FrontendAction>
177 // Create the underlying action.
178 std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
179 if (!Act)
180 return nullptr;
181
182 const FrontendOptions &FEOpts = CI.getFrontendOpts();
183
184 if (CI.getLangOpts().HLSL)
185 Act = std::make_unique<HLSLFrontendAction>(std::move(Act));
186
187 if (FEOpts.FixAndRecompile) {
188 Act = std::make_unique<FixItRecompile>(std::move(Act));
189 }
190
191 // Wrap the base FE action in an extract api action to generate
192 // symbol graph as a biproduct of compilation (enabled with
193 // --emit-symbol-graph option)
194 if (FEOpts.EmitSymbolGraph) {
195 if (FEOpts.SymbolGraphOutputDir.empty()) {
196 CI.getDiagnostics().Report(diag::warn_missing_symbol_graph_dir);
198 }
199 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
200 Act = std::make_unique<WrappingExtractAPIAction>(std::move(Act));
201 }
202
203 // If there are any AST files to merge, create a frontend action
204 // adaptor to perform the merge.
205 if (!FEOpts.ASTMergeFiles.empty())
206 Act = std::make_unique<ASTMergeAction>(std::move(Act),
207 FEOpts.ASTMergeFiles);
208
209 return Act;
210}
211
213 // Honor -help.
214 if (Clang->getFrontendOpts().ShowHelp) {
215 driver::getDriverOptTable().printHelp(
216 llvm::outs(), "clang -cc1 [options] file...",
217 "LLVM 'Clang' Compiler: http://clang.llvm.org",
218 /*ShowHidden=*/false, /*ShowAllAliases=*/false,
219 llvm::opt::Visibility(driver::options::CC1Option));
220 return true;
221 }
222
223 // Honor -version.
224 //
225 // FIXME: Use a better -version message?
226 if (Clang->getFrontendOpts().ShowVersion) {
227 llvm::cl::PrintVersionMessage();
228 return true;
229 }
230
231 Clang->LoadRequestedPlugins();
232
233 // Honor -mllvm.
234 //
235 // FIXME: Remove this, one day.
236 // This should happen AFTER plugins have been loaded!
237 if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
238 unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
239 auto Args = std::make_unique<const char*[]>(NumArgs + 2);
240 Args[0] = "clang (LLVM option parsing)";
241 for (unsigned i = 0; i != NumArgs; ++i)
242 Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
243 Args[NumArgs + 1] = nullptr;
244 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
245 }
246
247#if CLANG_ENABLE_STATIC_ANALYZER
248 // These should happen AFTER plugins have been loaded!
249
250 AnalyzerOptions &AnOpts = Clang->getAnalyzerOpts();
251
252 // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
253 if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
255 ento::printCheckerHelp(llvm::outs(), *Clang);
256 return true;
257 }
258
259 // Honor -analyzer-checker-option-help.
262 ento::printCheckerConfigList(llvm::outs(), *Clang);
263 return true;
264 }
265
266 // Honor -analyzer-list-enabled-checkers.
267 if (AnOpts.ShowEnabledCheckerList) {
268 ento::printEnabledCheckerList(llvm::outs(), *Clang);
269 return true;
270 }
271
272 // Honor -analyzer-config-help.
273 if (AnOpts.ShowConfigOptionsList) {
274 ento::printAnalyzerConfigList(llvm::outs());
275 return true;
276 }
277#endif
278
279#if CLANG_ENABLE_CIR
280 if (!Clang->getFrontendOpts().MLIRArgs.empty()) {
281 mlir::registerCIRPasses();
282 mlir::registerMLIRContextCLOptions();
283 mlir::registerPassManagerCLOptions();
284 mlir::registerAsmPrinterCLOptions();
285 unsigned NumArgs = Clang->getFrontendOpts().MLIRArgs.size();
286 auto Args = std::make_unique<const char *[]>(NumArgs + 2);
287 Args[0] = "clang (MLIR option parsing)";
288 for (unsigned i = 0; i != NumArgs; ++i)
289 Args[i + 1] = Clang->getFrontendOpts().MLIRArgs[i].c_str();
290 Args[NumArgs + 1] = nullptr;
291 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
292 }
293#endif
294
295 // If there were errors in processing arguments, don't do anything else.
296 if (Clang->getDiagnostics().hasErrorOccurred())
297 return false;
298 // Create and execute the frontend action.
299 std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
300 if (!Act)
301 return false;
302 bool Success = Clang->ExecuteAction(*Act);
303 if (Clang->getFrontendOpts().DisableFree)
304 llvm::BuryPointer(std::move(Act));
305 return Success;
306}
307
308} // namespace clang
StringRef P
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()
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
LangOptions & getLangOpts()
CodeGenOptions & getCodeGenOpts()
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1529
bool hasErrorOccurred() const
Definition: Diagnostic.h:871
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::string SymbolGraphOutputDir
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)
The JSON file list parser is used to communicate input to InstallAPI.
static std::unique_ptr< FrontendAction > CreateFrontendBaseAction(CompilerInstance &CI)
@ Success
Annotation was successful.
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...