xref: /llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp (revision d24184591fb7223fe6fea724be901ee501bf1cc3)
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/ARCMigrate/ARCMTActions.h"
15 #include "clang/CodeGen/CodeGenAction.h"
16 #include "clang/Config/config.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Frontend/CompilerInstance.h"
19 #include "clang/Frontend/CompilerInvocation.h"
20 #include "clang/Frontend/FrontendActions.h"
21 #include "clang/Frontend/FrontendDiagnostic.h"
22 #include "clang/Frontend/FrontendPluginRegistry.h"
23 #include "clang/Frontend/Utils.h"
24 #include "clang/FrontendTool/Utils.h"
25 #include "clang/Rewrite/Frontend/FrontendActions.h"
26 #include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
27 #include "llvm/Option/OptTable.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/BuryPointer.h"
30 #include "llvm/Support/DynamicLibrary.h"
31 #include "llvm/Support/ErrorHandling.h"
32 using namespace clang;
33 using namespace llvm::opt;
34 
35 namespace clang {
36 
37 static std::unique_ptr<FrontendAction>
38 CreateFrontendBaseAction(CompilerInstance &CI) {
39   using namespace clang::frontend;
40   StringRef Action("unknown");
41   (void)Action;
42 
43   switch (CI.getFrontendOpts().ProgramAction) {
44   case ASTDeclList:            return std::make_unique<ASTDeclListAction>();
45   case ASTDump:                return std::make_unique<ASTDumpAction>();
46   case ASTPrint:               return std::make_unique<ASTPrintAction>();
47   case ASTView:                return std::make_unique<ASTViewAction>();
48   case DumpCompilerOptions:
49     return std::make_unique<DumpCompilerOptionsAction>();
50   case DumpRawTokens:          return std::make_unique<DumpRawTokensAction>();
51   case DumpTokens:             return std::make_unique<DumpTokensAction>();
52   case EmitAssembly:           return std::make_unique<EmitAssemblyAction>();
53   case EmitBC:                 return std::make_unique<EmitBCAction>();
54   case EmitHTML:               return std::make_unique<HTMLPrintAction>();
55   case EmitLLVM:               return std::make_unique<EmitLLVMAction>();
56   case EmitLLVMOnly:           return std::make_unique<EmitLLVMOnlyAction>();
57   case EmitCodeGenOnly:        return std::make_unique<EmitCodeGenOnlyAction>();
58   case EmitObj:                return std::make_unique<EmitObjAction>();
59   case FixIt:                  return std::make_unique<FixItAction>();
60   case GenerateModule:
61     return std::make_unique<GenerateModuleFromModuleMapAction>();
62   case GenerateModuleInterface:
63     return std::make_unique<GenerateModuleInterfaceAction>();
64   case GenerateHeaderModule:
65     return std::make_unique<GenerateHeaderModuleAction>();
66   case GeneratePCH:            return std::make_unique<GeneratePCHAction>();
67   case GenerateInterfaceYAMLExpV1:
68     return std::make_unique<GenerateInterfaceYAMLExpV1Action>();
69   case GenerateInterfaceTBEExpV1:
70     return std::make_unique<GenerateInterfaceTBEExpV1Action>();
71   case GenerateInterfaceIfsExpV1:
72     return std::make_unique<GenerateInterfaceIfsExpV1Action>();
73   case InitOnly:               return std::make_unique<InitOnlyAction>();
74   case ParseSyntaxOnly:        return std::make_unique<SyntaxOnlyAction>();
75   case ModuleFileInfo:         return std::make_unique<DumpModuleInfoAction>();
76   case VerifyPCH:              return std::make_unique<VerifyPCHAction>();
77   case TemplightDump:          return std::make_unique<TemplightDumpAction>();
78 
79   case PluginAction: {
80     for (FrontendPluginRegistry::iterator it =
81            FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
82          it != ie; ++it) {
83       if (it->getName() == CI.getFrontendOpts().ActionName) {
84         std::unique_ptr<PluginASTAction> P(it->instantiate());
85         if ((P->getActionType() != PluginASTAction::ReplaceAction &&
86              P->getActionType() != PluginASTAction::Cmdline) ||
87             !P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()]))
88           return nullptr;
89         return std::move(P);
90       }
91     }
92 
93     CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
94       << CI.getFrontendOpts().ActionName;
95     return nullptr;
96   }
97 
98   case PrintPreamble:          return std::make_unique<PrintPreambleAction>();
99   case PrintPreprocessedInput: {
100     if (CI.getPreprocessorOutputOpts().RewriteIncludes ||
101         CI.getPreprocessorOutputOpts().RewriteImports)
102       return std::make_unique<RewriteIncludesAction>();
103     return std::make_unique<PrintPreprocessedAction>();
104   }
105 
106   case RewriteMacros:          return std::make_unique<RewriteMacrosAction>();
107   case RewriteTest:            return std::make_unique<RewriteTestAction>();
108 #if CLANG_ENABLE_OBJC_REWRITER
109   case RewriteObjC:            return std::make_unique<RewriteObjCAction>();
110 #else
111   case RewriteObjC:            Action = "RewriteObjC"; break;
112 #endif
113 #if CLANG_ENABLE_ARCMT
114   case MigrateSource:
115     return std::make_unique<arcmt::MigrateSourceAction>();
116 #else
117   case MigrateSource:          Action = "MigrateSource"; break;
118 #endif
119 #if CLANG_ENABLE_STATIC_ANALYZER
120   case RunAnalysis:            return std::make_unique<ento::AnalysisAction>();
121 #else
122   case RunAnalysis:            Action = "RunAnalysis"; break;
123 #endif
124   case RunPreprocessorOnly:    return std::make_unique<PreprocessOnlyAction>();
125   case PrintDependencyDirectivesSourceMinimizerOutput:
126     return std::make_unique<PrintDependencyDirectivesSourceMinimizerAction>();
127   }
128 
129 #if !CLANG_ENABLE_ARCMT || !CLANG_ENABLE_STATIC_ANALYZER \
130   || !CLANG_ENABLE_OBJC_REWRITER
131   CI.getDiagnostics().Report(diag::err_fe_action_not_available) << Action;
132   return 0;
133 #else
134   llvm_unreachable("Invalid program action!");
135 #endif
136 }
137 
138 std::unique_ptr<FrontendAction>
139 CreateFrontendAction(CompilerInstance &CI) {
140   // Create the underlying action.
141   std::unique_ptr<FrontendAction> Act = CreateFrontendBaseAction(CI);
142   if (!Act)
143     return nullptr;
144 
145   const FrontendOptions &FEOpts = CI.getFrontendOpts();
146 
147   if (FEOpts.FixAndRecompile) {
148     Act = std::make_unique<FixItRecompile>(std::move(Act));
149   }
150 
151 #if CLANG_ENABLE_ARCMT
152   if (CI.getFrontendOpts().ProgramAction != frontend::MigrateSource &&
153       CI.getFrontendOpts().ProgramAction != frontend::GeneratePCH) {
154     // Potentially wrap the base FE action in an ARC Migrate Tool action.
155     switch (FEOpts.ARCMTAction) {
156     case FrontendOptions::ARCMT_None:
157       break;
158     case FrontendOptions::ARCMT_Check:
159       Act = std::make_unique<arcmt::CheckAction>(std::move(Act));
160       break;
161     case FrontendOptions::ARCMT_Modify:
162       Act = std::make_unique<arcmt::ModifyAction>(std::move(Act));
163       break;
164     case FrontendOptions::ARCMT_Migrate:
165       Act = std::make_unique<arcmt::MigrateAction>(std::move(Act),
166                                      FEOpts.MTMigrateDir,
167                                      FEOpts.ARCMTMigrateReportOut,
168                                      FEOpts.ARCMTMigrateEmitARCErrors);
169       break;
170     }
171 
172     if (FEOpts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
173       Act = std::make_unique<arcmt::ObjCMigrateAction>(std::move(Act),
174                                                         FEOpts.MTMigrateDir,
175                                                         FEOpts.ObjCMTAction);
176     }
177   }
178 #endif
179 
180   // If there are any AST files to merge, create a frontend action
181   // adaptor to perform the merge.
182   if (!FEOpts.ASTMergeFiles.empty())
183     Act = std::make_unique<ASTMergeAction>(std::move(Act),
184                                             FEOpts.ASTMergeFiles);
185 
186   return Act;
187 }
188 
189 bool ExecuteCompilerInvocation(CompilerInstance *Clang) {
190   // Honor -help.
191   if (Clang->getFrontendOpts().ShowHelp) {
192     std::unique_ptr<OptTable> Opts = driver::createDriverOptTable();
193     Opts->PrintHelp(llvm::outs(), "clang -cc1 [options] file...",
194                     "LLVM 'Clang' Compiler: http://clang.llvm.org",
195                     /*Include=*/driver::options::CC1Option,
196                     /*Exclude=*/0, /*ShowAllAliases=*/false);
197     return true;
198   }
199 
200   // Honor -version.
201   //
202   // FIXME: Use a better -version message?
203   if (Clang->getFrontendOpts().ShowVersion) {
204     llvm::cl::PrintVersionMessage();
205     return true;
206   }
207 
208   // Load any requested plugins.
209   for (unsigned i = 0,
210          e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
211     const std::string &Path = Clang->getFrontendOpts().Plugins[i];
212     std::string Error;
213     if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
214       Clang->getDiagnostics().Report(diag::err_fe_unable_to_load_plugin)
215         << Path << Error;
216   }
217 
218   // Check if any of the loaded plugins replaces the main AST action
219   for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
220                                         ie = FrontendPluginRegistry::end();
221        it != ie; ++it) {
222     std::unique_ptr<PluginASTAction> P(it->instantiate());
223     if (P->getActionType() == PluginASTAction::ReplaceAction) {
224       Clang->getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
225       Clang->getFrontendOpts().ActionName = it->getName();
226       break;
227     }
228   }
229 
230   // Honor -mllvm.
231   //
232   // FIXME: Remove this, one day.
233   // This should happen AFTER plugins have been loaded!
234   if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
235     unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
236     auto Args = std::make_unique<const char*[]>(NumArgs + 2);
237     Args[0] = "clang (LLVM option parsing)";
238     for (unsigned i = 0; i != NumArgs; ++i)
239       Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
240     Args[NumArgs + 1] = nullptr;
241     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
242   }
243 
244 #if CLANG_ENABLE_STATIC_ANALYZER
245   // These should happen AFTER plugins have been loaded!
246 
247   AnalyzerOptions &AnOpts = *Clang->getAnalyzerOpts();
248   // Honor -analyzer-checker-help and -analyzer-checker-help-hidden.
249   if (AnOpts.ShowCheckerHelp || AnOpts.ShowCheckerHelpAlpha ||
250       AnOpts.ShowCheckerHelpDeveloper) {
251     ento::printCheckerHelp(llvm::outs(),
252                            Clang->getFrontendOpts().Plugins,
253                            AnOpts,
254                            Clang->getDiagnostics(),
255                            Clang->getLangOpts());
256     return true;
257   }
258 
259   // Honor -analyzer-checker-option-help.
260   if (AnOpts.ShowCheckerOptionList || AnOpts.ShowCheckerOptionAlphaList ||
261       AnOpts.ShowCheckerOptionDeveloperList) {
262     ento::printCheckerConfigList(llvm::outs(),
263                                  Clang->getFrontendOpts().Plugins,
264                                  *Clang->getAnalyzerOpts(),
265                                  Clang->getDiagnostics(),
266                                  Clang->getLangOpts());
267     return true;
268   }
269 
270   // Honor -analyzer-list-enabled-checkers.
271   if (AnOpts.ShowEnabledCheckerList) {
272     ento::printEnabledCheckerList(llvm::outs(),
273                                   Clang->getFrontendOpts().Plugins,
274                                   AnOpts,
275                                   Clang->getDiagnostics(),
276                                   Clang->getLangOpts());
277   }
278 
279   // Honor -analyzer-config-help.
280   if (AnOpts.ShowConfigOptionsList) {
281     ento::printAnalyzerConfigList(llvm::outs());
282     return true;
283   }
284 #endif
285 
286   // If there were errors in processing arguments, don't do anything else.
287   if (Clang->getDiagnostics().hasErrorOccurred())
288     return false;
289   // Create and execute the frontend action.
290   std::unique_ptr<FrontendAction> Act(CreateFrontendAction(*Clang));
291   if (!Act)
292     return false;
293   bool Success = Clang->ExecuteAction(*Act);
294   if (Clang->getFrontendOpts().DisableFree)
295     llvm::BuryPointer(std::move(Act));
296   return Success;
297 }
298 
299 } // namespace clang
300