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