clang 24.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
16#include "clang/Config/config.h"
29#include "clang/ScalableStaticAnalysis/SSAFForceLinker.h" // IWYU pragma: keep
33#include "llvm/Option/OptTable.h"
34#include "llvm/Support/BuryPointer.h"
35#include "llvm/Support/DynamicLibrary.h"
36#include "llvm/Support/ErrorHandling.h"
37
38#if CLANG_ENABLE_CIR
39#include "mlir/IR/AsmState.h"
40#include "mlir/IR/MLIRContext.h"
41#include "mlir/Pass/PassManager.h"
44#endif
45
46using namespace clang;
47using namespace llvm::opt;
48
49namespace clang {
50
51static std::unique_ptr<FrontendAction>
53 using namespace clang::frontend;
54 StringRef Action("unknown");
55 (void)Action;
56
57 unsigned UseCIR = CI.getFrontendOpts().UseClangIRPipeline;
59 bool EmitsCIR = Act == EmitCIR;
60
61 if (!UseCIR && EmitsCIR)
62 llvm::report_fatal_error("-emit-cir and only valid when using -fclangir");
63
64 switch (CI.getFrontendOpts().ProgramAction) {
65 case ASTDeclList: return std::make_unique<ASTDeclListAction>();
66 case ASTDump: return std::make_unique<ASTDumpAction>();
67 case ASTPrint: return std::make_unique<ASTPrintAction>();
68 case ASTView: return std::make_unique<ASTViewAction>();
70 return std::make_unique<DumpCompilerOptionsAction>();
71 case DumpRawTokens: return std::make_unique<DumpRawTokensAction>();
72 case DumpTokens: return std::make_unique<DumpTokensAction>();
73 case EmitAssembly:
74#if CLANG_ENABLE_CIR
75 if (UseCIR)
76 return std::make_unique<cir::EmitAssemblyAction>();
77#endif
78 return std::make_unique<EmitAssemblyAction>();
79 case EmitBC:
80#if CLANG_ENABLE_CIR
81 if (UseCIR)
82 return std::make_unique<cir::EmitBCAction>();
83#endif
84 return std::make_unique<EmitBCAction>();
85 case EmitCIR:
86#if CLANG_ENABLE_CIR
87 return std::make_unique<cir::EmitCIRAction>();
88#else
89 CI.getDiagnostics().Report(diag::err_fe_cir_not_built);
90 return nullptr;
91#endif
92 case EmitHTML: return std::make_unique<HTMLPrintAction>();
93 case EmitLLVM: {
94#if CLANG_ENABLE_CIR
95 if (UseCIR)
96 return std::make_unique<cir::EmitLLVMAction>();
97#endif
98 return std::make_unique<EmitLLVMAction>();
99 }
100 case EmitLLVMOnly: return std::make_unique<EmitLLVMOnlyAction>();
101 case EmitCodeGenOnly: return std::make_unique<EmitCodeGenOnlyAction>();
102 case EmitObj:
103#if CLANG_ENABLE_CIR
104 if (UseCIR)
105 return std::make_unique<cir::EmitObjAction>();
106#endif
107 return std::make_unique<EmitObjAction>();
108 case ExtractAPI:
109 return std::make_unique<ExtractAPIAction>();
110 case FixIt: return std::make_unique<FixItAction>();
111 case GenerateModule:
112 return std::make_unique<GenerateModuleFromModuleMapAction>();
114 return std::make_unique<GenerateModuleInterfaceAction>();
116 return std::make_unique<GenerateReducedModuleInterfaceAction>();
118 return std::make_unique<GenerateHeaderUnitAction>();
119 case GeneratePCH: return std::make_unique<GeneratePCHAction>();
121 return std::make_unique<GenerateInterfaceStubsAction>();
122 case InitOnly: return std::make_unique<InitOnlyAction>();
123 case ParseSyntaxOnly: return std::make_unique<SyntaxOnlyAction>();
124 case ModuleFileInfo: return std::make_unique<DumpModuleInfoAction>();
125 case VerifyPCH:
126 return std::make_unique<VerifyPCHAction>();
127
128 case PluginAction: {
129 for (const FrontendPluginRegistry::entry &Plugin :
130 FrontendPluginRegistry::entries()) {
131 if (Plugin.getName() == CI.getFrontendOpts().ActionName) {
132 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
133 if ((P->getActionType() != PluginASTAction::ReplaceAction &&
134 P->getActionType() != PluginASTAction::CmdlineAfterMainAction) ||
135 !P->ParseArgs(
136 CI,
137 CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
138 return nullptr;
139 return std::move(P);
140 }
141 }
142
143 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
145 return nullptr;
146 }
147
148 case PrintPreamble: return std::make_unique<PrintPreambleAction>();
152 return std::make_unique<RewriteIncludesAction>();
153 return std::make_unique<PrintPreprocessedAction>();
154 }
155
156 case RewriteMacros: return std::make_unique<RewriteMacrosAction>();
157 case RewriteTest: return std::make_unique<RewriteTestAction>();
158#if CLANG_ENABLE_OBJC_REWRITER
159 case RewriteObjC: return std::make_unique<RewriteObjCAction>();
160#else
161 case RewriteObjC: Action = "RewriteObjC"; break;
162#endif
163#if CLANG_ENABLE_STATIC_ANALYZER
164 case RunAnalysis: return std::make_unique<ento::AnalysisAction>();
165#else
166 case RunAnalysis: Action = "RunAnalysis"; break;
167#endif
168 case RunPreprocessorOnly: return std::make_unique<PreprocessOnlyAction>();
170 return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
171 }
172
173#if !CLANG_ENABLE_STATIC_ANALYZER || !CLANG_ENABLE_OBJC_REWRITER
174 CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
175 return 0;
176#else
177 llvm_unreachable("Invalid program action!");
178#endif
179}
180
181std::unique_ptr<FrontendAction>
183 // Create the underlying action.
184 std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
185 if (!Act)
186 return nullptr;
187
188 const FrontendOptions &FEOpts = CI.getFrontendOpts();
189
190 if (CI.getLangOpts().HLSL)
191 Act = std::make_unique<HLSLFrontendAction>(std::move(Act));
192
193 if (FEOpts.FixAndRecompile) {
194 Act = std::make_unique<FixItRecompile>(std::move(Act));
195 }
196
197 // Wrap the base FE action in an extract api action to generate
198 // symbol graph as a biproduct of compilation (enabled with
199 // --emit-symbol-graph option)
200 if (FEOpts.EmitSymbolGraph) {
201 if (FEOpts.SymbolGraphOutputDir.empty()) {
202 CI.getDiagnostics().Report(diag::warn_missing_symbol_graph_dir);
204 }
205 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
206 Act = std::make_unique<WrappingExtractAPIAction>(std::move(Act));
207 }
208
209 // If there are any AST files to merge, create a frontend action
210 // adaptor to perform the merge.
211 if (!FEOpts.ASTMergeFiles.empty())
212 Act = std::make_unique<ASTMergeAction>(std::move(Act),
213 FEOpts.ASTMergeFiles);
214
215 if (!CI.getSSAFOpts().TUSummaryFile.empty()) {
216 Act = std::make_unique<ssaf::TUSummaryExtractorFrontendAction>(
217 std::move(Act));
218 }
219 // Enter the source-transformation action when the transformation option is
220 // set, and also when only an output option (--ssaf-src-edit-file= /
221 // --ssaf-transformation-report-file=) is set — the action's
222 // reportOrphanOptionMisuse then diagnoses that as a reverse orphan rather
223 // than silently ignoring the option.
224 if (!CI.getSSAFOpts().SourceTransformation.empty() ||
225 !CI.getSSAFOpts().SrcEditFile.empty() ||
227 Act = std::make_unique<ssaf::SourceTransformationFrontendAction>(
228 std::move(Act));
229 }
230 return Act;
231}
232
234 unsigned NumErrorsBefore = Clang->getDiagnostics().getNumErrors();
235
236 // Honor -help.
237 if (Clang->getFrontendOpts().ShowHelp) {
238 getDriverOptTable().printHelp(
239 llvm::outs(), "clang -cc1 [options] file...",
240 "LLVM 'Clang' Compiler: http://clang.llvm.org",
241 /*ShowHidden=*/false, /*ShowAllAliases=*/false,
242 llvm::opt::Visibility(options::CC1Option));
243 return true;
244 }
245
246 // Honor -version.
247 //
248 // FIXME: Use a better -version message?
249 if (Clang->getFrontendOpts().ShowVersion) {
250 llvm::cl::PrintVersionMessage();
251 return true;
252 }
253
254 Clang->LoadRequestedPlugins();
255
256 // Honor -mllvm.
257 //
258 // FIXME: Remove this, one day.
259 // This should happen AFTER plugins have been loaded!
260 if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
261 unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
262 auto Args = std::make_unique<const char*[]>(NumArgs + 2);
263 Args[0] = "clang (LLVM option parsing)";
264 for (unsigned i = 0; i != NumArgs; ++i)
265 Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
266 Args[NumArgs + 1] = nullptr;
267 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(), /*Overview=*/"",
268 /*Errs=*/nullptr,
269 /*VFS=*/&Clang->getVirtualFileSystem());
270 }
271
272#if CLANG_ENABLE_STATIC_ANALYZER
273 // These should happen AFTER plugins have been loaded!
274
275 AnalyzerOptions &AnOpts = Clang->getAnalyzerOpts();
276
277 // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
278 if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
280 ento::printCheckerHelp(llvm::outs(), *Clang);
281 return true;
282 }
283
284 // Honor -analyzer-checker-option-help.
287 ento::printCheckerConfigList(llvm::outs(), *Clang);
288 return true;
289 }
290
291 // Honor -analyzer-list-enabled-checkers.
292 if (AnOpts.ShowEnabledCheckerList) {
293 ento::printEnabledCheckerList(llvm::outs(), *Clang);
294 return true;
295 }
296
297 // Honor -analyzer-config-help.
298 if (AnOpts.ShowConfigOptionsList) {
299 ento::printAnalyzerConfigList(llvm::outs());
300 return true;
301 }
302#endif
303
304#if CLANG_ENABLE_CIR
305 if (!Clang->getFrontendOpts().MLIRArgs.empty()) {
306 mlir::registerCIRPasses();
307 mlir::registerMLIRContextCLOptions();
308 mlir::registerPassManagerCLOptions();
309 mlir::registerAsmPrinterCLOptions();
310 unsigned NumArgs = Clang->getFrontendOpts().MLIRArgs.size();
311 auto Args = std::make_unique<const char *[]>(NumArgs + 2);
312 Args[0] = "clang (MLIR option parsing)";
313 for (unsigned i = 0; i != NumArgs; ++i)
314 Args[i + 1] = Clang->getFrontendOpts().MLIRArgs[i].c_str();
315 Args[NumArgs + 1] = nullptr;
316 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(),
317 /*Description=*/"", /*Errs=*/nullptr,
318 &Clang->getVirtualFileSystem());
319 }
320#endif
321
322 // If there were errors in the above, don't do anything else.
323 // This intentionally ignores errors emitted before this function to
324 // accommodate lenient callers that decided to make progress despite errors.
325 if (Clang->getDiagnostics().getNumErrors() != NumErrorsBefore)
326 return false;
327
328 // Create and execute the frontend action.
329 std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
330 if (!Act)
331 return false;
332 bool Success = Clang->ExecuteAction(*Act);
333 if (Clang->getFrontendOpts().DisableFree)
334 llvm::BuryPointer(std::move(Act));
335 return Success;
336}
337
338} // namespace clang
This file defines the ExtractAPIAction and WrappingExtractAPIAction frontend actions.
This file pulls in all built-in SSAF extractor and format registrations by referencing their anchor s...
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()
ssaf::SSAFOptions & getSSAFOpts()
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:907
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.
std::string SrcEditFile
Path of the source-edit output file produced by the source transformation.
Definition SSAFOptions.h:52
std::string TransformationReportFile
Path of the transformation-report output file produced by the source transformation.
Definition SSAFOptions.h:57
std::string SourceTransformation
Name of the SSAF source transformation to run.
Definition SSAFOptions.h:38
std::string TUSummaryFile
The TU summary output file with the file extension representing the serialization format.
Definition SSAFOptions.h:27
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.
@ 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.
Top level wrappers for InstallAPI frontend operations.
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...
const llvm::opt::OptTable & getDriverOptTable()