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
14#include "clang/Basic/DiagnosticFrontend.h"
15#include "clang/CodeGen/CodeGenAction.h"
16#include "clang/Config/config.h"
17#include "clang/ExtractAPI/FrontendActions.h"
18#include "clang/Frontend/CompilerInstance.h"
19#include "clang/Frontend/CompilerInvocation.h"
20#include "clang/Frontend/FrontendActions.h"
21#include "clang/Frontend/FrontendPluginRegistry.h"
22#include "clang/Frontend/SSAFOptions.h"
23#include "clang/Frontend/Utils.h"
24#include "clang/FrontendTool/Utils.h"
25#include "clang/Options/Options.h"
26#include "clang/Rewrite/Frontend/FrontendActions.h"
27#include "clang/ScalableStaticAnalysis/Frontend/SourceTransformationFrontendAction.h"
28#include "clang/ScalableStaticAnalysis/Frontend/TUSummaryExtractorFrontendAction.h"
29#include "clang/ScalableStaticAnalysis/SSAFForceLinker.h" // IWYU pragma: keep
30#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
31#include "clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h"
32#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
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"
42#include "clang/CIR/Dialect/Passes.h"
43#include "clang/CIR/FrontendAction/CIRGenAction.h"
44#endif
45
46using namespace clang;
47using namespace llvm::opt;
48
49namespace clang {
50
51static std::unique_ptr<FrontendAction>
52CreateFrontendBaseAction(CompilerInstance &CI) {
53 using namespace clang::frontend;
54 StringRef Action("unknown");
55 (void)Action;
56
57 unsigned UseCIR = CI.getFrontendOpts().UseClangIRPipeline;
58 frontend::ActionKind Act = CI.getFrontendOpts().ProgramAction;
59 bool EmitsCIR = Act == EmitCIR;
60
61 if (!UseCIR && EmitsCIR)
62 llvm::report_fatal_error(reason: "-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>();
69 case DumpCompilerOptions:
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(DiagID: 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>();
113 case GenerateModuleInterface:
114 return std::make_unique<GenerateModuleInterfaceAction>();
115 case GenerateReducedModuleInterface:
116 return std::make_unique<GenerateReducedModuleInterfaceAction>();
117 case GenerateHeaderUnit:
118 return std::make_unique<GenerateHeaderUnitAction>();
119 case GeneratePCH: return std::make_unique<GeneratePCHAction>();
120 case GenerateInterfaceStubs:
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 arg: CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())]))
138 return nullptr;
139 return std::move(P);
140 }
141 }
142
143 CI.getDiagnostics().Report(DiagID: diag::err_fe_invalid_plugin_name)
144 << CI.getFrontendOpts().ActionName;
145 return nullptr;
146 }
147
148 case PrintPreamble: return std::make_unique<PrintPreambleAction>();
149 case PrintPreprocessedInput: {
150 if (CI.getPreprocessorOutputOpts().RewriteIncludes ||
151 CI.getPreprocessorOutputOpts().RewriteImports)
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>();
169 case PrintDependencyDirectivesSourceMinimizerOutput:
170 return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
171 }
172
173#if !CLANG_ENABLE_STATIC_ANALYZER || !CLANG_ENABLE_OBJC_REWRITER
174 CI.getDiagnostics().Report(DiagID: 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>
182CreateFrontendAction(CompilerInstance &CI) {
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>(args: std::move(Act));
192
193 if (FEOpts.FixAndRecompile) {
194 Act = std::make_unique<FixItRecompile>(args: 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(DiagID: diag::warn_missing_symbol_graph_dir);
203 CI.getFrontendOpts().SymbolGraphOutputDir = ".";
204 }
205 CI.getCodeGenOpts().ClearASTBeforeBackend = false;
206 Act = std::make_unique<WrappingExtractAPIAction>(args: 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>(args: std::move(Act),
213 args: FEOpts.ASTMergeFiles);
214
215 if (!CI.getSSAFOpts().TUSummaryFile.empty()) {
216 Act = std::make_unique<ssaf::TUSummaryExtractorFrontendAction>(
217 args: 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() ||
226 !CI.getSSAFOpts().TransformationReportFile.empty()) {
227 Act = std::make_unique<ssaf::SourceTransformationFrontendAction>(
228 args: std::move(Act));
229 }
230 return Act;
231}
232
233bool ExecuteCompilerInvocation(CompilerInstance *Clang) {
234 unsigned NumErrorsBefore = Clang->getDiagnostics().getNumErrors();
235
236 // Honor -help.
237 if (Clang->getFrontendOpts().ShowHelp) {
238 getDriverOptTable().printHelp(
239 OS&: llvm::outs(), Usage: "clang -cc1 [options] file...",
240 Title: "LLVM 'Clang' Compiler: http://clang.llvm.org",
241 /*ShowHidden=*/false, /*ShowAllAliases=*/false,
242 VisibilityMask: 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*[]>(num: 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(argc: NumArgs + 1, argv: 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 ||
279 AnOpts.ShowCheckerHelpDeveloper) {
280 ento::printCheckerHelp(OS&: llvm::outs(), CI&: *Clang);
281 return true;
282 }
283
284 // Honor -analyzer-checker-option-help.
285 if (AnOpts.ShowCheckerOptionList || AnOpts.ShowCheckerOptionAlphaList ||
286 AnOpts.ShowCheckerOptionDeveloperList) {
287 ento::printCheckerConfigList(OS&: llvm::outs(), CI&: *Clang);
288 return true;
289 }
290
291 // Honor -analyzer-list-enabled-checkers.
292 if (AnOpts.ShowEnabledCheckerList) {
293 ento::printEnabledCheckerList(OS&: llvm::outs(), CI&: *Clang);
294 return true;
295 }
296
297 // Honor -analyzer-config-help.
298 if (AnOpts.ShowConfigOptionsList) {
299 ento::printAnalyzerConfigList(OS&: 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(CI&: *Clang));
330 if (!Act)
331 return false;
332 bool Success = Clang->ExecuteAction(Act&: *Act);
333 if (Clang->getFrontendOpts().DisableFree)
334 llvm::BuryPointer(Ptr: std::move(Act));
335 return Success;
336}
337
338} // namespace clang
339