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