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