cc1_main.cpp revision f56a488a6bdfe56ca814f37d384afa67c67f9dd5
1//===-- cc1_main.cpp - Clang CC1 Compiler Frontend ------------------------===//
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 is the entry point to the clang -cc1 functionality, which implements the
11// core compiler functionality along with a number of additional tools for
12// demonstration and testing purposes.
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Checker/FrontendActions.h"
18#include "clang/CodeGen/CodeGenAction.h"
19#include "clang/Driver/Arg.h"
20#include "clang/Driver/ArgList.h"
21#include "clang/Driver/CC1Options.h"
22#include "clang/Driver/DriverDiagnostic.h"
23#include "clang/Driver/OptTable.h"
24#include "clang/Frontend/CompilerInstance.h"
25#include "clang/Frontend/CompilerInvocation.h"
26#include "clang/Frontend/FrontendActions.h"
27#include "clang/Frontend/FrontendDiagnostic.h"
28#include "clang/Frontend/FrontendPluginRegistry.h"
29#include "clang/Frontend/TextDiagnosticBuffer.h"
30#include "clang/Frontend/TextDiagnosticPrinter.h"
31#include "clang/Rewrite/FrontendActions.h"
32#include "llvm/LLVMContext.h"
33#include "llvm/ADT/OwningPtr.h"
34#include "llvm/ADT/Statistic.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/ManagedStatic.h"
37#include "llvm/Support/Timer.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/System/DynamicLibrary.h"
40#include "llvm/Target/TargetSelect.h"
41#include <cstdio>
42using namespace clang;
43
44//===----------------------------------------------------------------------===//
45// Main driver
46//===----------------------------------------------------------------------===//
47
48static void LLVMErrorHandler(void *UserData, const std::string &Message) {
49  Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
50
51  Diags.Report(diag::err_fe_error_backend) << Message;
52
53  // We cannot recover from llvm errors.
54  exit(1);
55}
56
57static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
58  using namespace clang::frontend;
59
60  switch (CI.getFrontendOpts().ProgramAction) {
61  default:
62    llvm_unreachable("Invalid program action!");
63
64  case ASTDump:                return new ASTDumpAction();
65  case ASTPrint:               return new ASTPrintAction();
66  case ASTPrintXML:            return new ASTPrintXMLAction();
67  case ASTView:                return new ASTViewAction();
68  case BoostCon:               return new BoostConAction();
69  case DumpRawTokens:          return new DumpRawTokensAction();
70  case DumpTokens:             return new DumpTokensAction();
71  case EmitAssembly:           return new EmitAssemblyAction();
72  case EmitBC:                 return new EmitBCAction();
73  case EmitHTML:               return new HTMLPrintAction();
74  case EmitLLVM:               return new EmitLLVMAction();
75  case EmitLLVMOnly:           return new EmitLLVMOnlyAction();
76  case EmitCodeGenOnly:        return new EmitCodeGenOnlyAction();
77  case EmitObj:                return new EmitObjAction();
78  case FixIt:                  return new FixItAction();
79  case GeneratePCH:            return new GeneratePCHAction();
80  case GeneratePTH:            return new GeneratePTHAction();
81  case InheritanceView:        return new InheritanceViewAction();
82  case InitOnly:               return new InitOnlyAction();
83  case ParseSyntaxOnly:        return new SyntaxOnlyAction();
84
85  case PluginAction: {
86    for (FrontendPluginRegistry::iterator it =
87           FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
88         it != ie; ++it) {
89      if (it->getName() == CI.getFrontendOpts().ActionName) {
90        llvm::OwningPtr<PluginASTAction> P(it->instantiate());
91        if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
92          return 0;
93        return P.take();
94      }
95    }
96
97    CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
98      << CI.getFrontendOpts().ActionName;
99    return 0;
100  }
101
102  case PrintDeclContext:       return new DeclContextPrintAction();
103  case PrintPreamble:          return new PrintPreambleAction();
104  case PrintPreprocessedInput: return new PrintPreprocessedAction();
105  case RewriteMacros:          return new RewriteMacrosAction();
106  case RewriteObjC:            return new RewriteObjCAction();
107  case RewriteTest:            return new RewriteTestAction();
108  case RunAnalysis:            return new AnalysisAction();
109  case RunPreprocessorOnly:    return new PreprocessOnlyAction();
110  }
111}
112
113static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
114  // Create the underlying action.
115  FrontendAction *Act = CreateFrontendBaseAction(CI);
116  if (!Act)
117    return 0;
118
119  // If there are any AST files to merge, create a frontend action
120  // adaptor to perform the merge.
121  if (!CI.getFrontendOpts().ASTMergeFiles.empty())
122    Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
123                             CI.getFrontendOpts().ASTMergeFiles.size());
124
125  return Act;
126}
127
128// FIXME: Define the need for this testing away.
129static int cc1_test(Diagnostic &Diags,
130                    const char **ArgBegin, const char **ArgEnd) {
131  using namespace clang::driver;
132
133  llvm::errs() << "cc1 argv:";
134  for (const char **i = ArgBegin; i != ArgEnd; ++i)
135    llvm::errs() << " \"" << *i << '"';
136  llvm::errs() << "\n";
137
138  // Parse the arguments.
139  OptTable *Opts = createCC1OptTable();
140  unsigned MissingArgIndex, MissingArgCount;
141  InputArgList *Args = Opts->ParseArgs(ArgBegin, ArgEnd,
142                                       MissingArgIndex, MissingArgCount);
143
144  // Check for missing argument error.
145  if (MissingArgCount)
146    Diags.Report(clang::diag::err_drv_missing_argument)
147      << Args->getArgString(MissingArgIndex) << MissingArgCount;
148
149  // Dump the parsed arguments.
150  llvm::errs() << "cc1 parsed options:\n";
151  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
152       it != ie; ++it)
153    (*it)->dump();
154
155  // Create a compiler invocation.
156  llvm::errs() << "cc1 creating invocation.\n";
157  CompilerInvocation Invocation;
158  CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd, Diags);
159
160  // Convert the invocation back to argument strings.
161  std::vector<std::string> InvocationArgs;
162  Invocation.toArgs(InvocationArgs);
163
164  // Dump the converted arguments.
165  llvm::SmallVector<const char*, 32> Invocation2Args;
166  llvm::errs() << "invocation argv :";
167  for (unsigned i = 0, e = InvocationArgs.size(); i != e; ++i) {
168    Invocation2Args.push_back(InvocationArgs[i].c_str());
169    llvm::errs() << " \"" << InvocationArgs[i] << '"';
170  }
171  llvm::errs() << "\n";
172
173  // Convert those arguments to another invocation, and check that we got the
174  // same thing.
175  CompilerInvocation Invocation2;
176  CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.begin(),
177                                     Invocation2Args.end(), Diags);
178
179  // FIXME: Implement CompilerInvocation comparison.
180  if (true) {
181    //llvm::errs() << "warning: Invocations differ!\n";
182
183    std::vector<std::string> Invocation2Args;
184    Invocation2.toArgs(Invocation2Args);
185    llvm::errs() << "invocation2 argv:";
186    for (unsigned i = 0, e = Invocation2Args.size(); i != e; ++i)
187      llvm::errs() << " \"" << Invocation2Args[i] << '"';
188    llvm::errs() << "\n";
189  }
190
191  return 0;
192}
193
194int cc1_main(const char **ArgBegin, const char **ArgEnd,
195             const char *Argv0, void *MainAddr) {
196  llvm::OwningPtr<CompilerInstance> Clang(new CompilerInstance());
197
198  Clang->setLLVMContext(new llvm::LLVMContext());
199
200  // Run clang -cc1 test.
201  if (ArgBegin != ArgEnd && llvm::StringRef(ArgBegin[0]) == "-cc1test") {
202    TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());
203    Diagnostic Diags(&DiagClient);
204    return cc1_test(Diags, ArgBegin + 1, ArgEnd);
205  }
206
207  // Initialize targets first, so that --version shows registered targets.
208  llvm::InitializeAllTargets();
209  llvm::InitializeAllAsmPrinters();
210  llvm::InitializeAllAsmParsers();
211
212  // Buffer diagnostics from argument parsing so that we can output them using a
213  // well formed diagnostic object.
214  TextDiagnosticBuffer DiagsBuffer;
215  Diagnostic Diags(&DiagsBuffer);
216  CompilerInvocation::CreateFromArgs(Clang->getInvocation(), ArgBegin, ArgEnd,
217                                     Diags);
218
219  // Infer the builtin include path if unspecified.
220  if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
221      Clang->getHeaderSearchOpts().ResourceDir.empty())
222    Clang->getHeaderSearchOpts().ResourceDir =
223      CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
224
225  // Honor -help.
226  if (Clang->getFrontendOpts().ShowHelp) {
227    llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable());
228    Opts->PrintHelp(llvm::outs(), "clang -cc1",
229                    "LLVM 'Clang' Compiler: http://clang.llvm.org");
230    return 0;
231  }
232
233  // Honor -version.
234  //
235  // FIXME: Use a better -version message?
236  if (Clang->getFrontendOpts().ShowVersion) {
237    llvm::cl::PrintVersionMessage();
238    return 0;
239  }
240
241  // Honor -mllvm.
242  //
243  // FIXME: Remove this, one day.
244  if (!Clang->getFrontendOpts().LLVMArgs.empty()) {
245    unsigned NumArgs = Clang->getFrontendOpts().LLVMArgs.size();
246    const char **Args = new const char*[NumArgs + 2];
247    Args[0] = "clang (LLVM option parsing)";
248    for (unsigned i = 0; i != NumArgs; ++i)
249      Args[i + 1] = Clang->getFrontendOpts().LLVMArgs[i].c_str();
250    Args[NumArgs + 1] = 0;
251    llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
252  }
253
254  // Create the actual diagnostics engine.
255  Clang->createDiagnostics(ArgEnd - ArgBegin, const_cast<char**>(ArgBegin));
256  if (!Clang->hasDiagnostics())
257    return 1;
258
259  // Set an error handler, so that any LLVM backend diagnostics go through our
260  // error handler.
261  llvm::install_fatal_error_handler(LLVMErrorHandler,
262                                  static_cast<void*>(&Clang->getDiagnostics()));
263
264  DiagsBuffer.FlushDiagnostics(Clang->getDiagnostics());
265
266  // Load any requested plugins.
267  for (unsigned i = 0,
268         e = Clang->getFrontendOpts().Plugins.size(); i != e; ++i) {
269    const std::string &Path = Clang->getFrontendOpts().Plugins[i];
270    std::string Error;
271    if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
272      Diags.Report(diag::err_fe_unable_to_load_plugin) << Path << Error;
273  }
274
275  // If there were errors in processing arguments, don't do anything else.
276  bool Success = false;
277  if (!Clang->getDiagnostics().getNumErrors()) {
278    // Create and execute the frontend action.
279    llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*Clang));
280    if (Act) {
281      Success = Clang->ExecuteAction(*Act);
282      if (Clang->getFrontendOpts().DisableFree)
283        Act.take();
284    }
285  }
286
287  // If any timers were active but haven't been destroyed yet, print their
288  // results now.  This happens in -disable-free mode.
289  llvm::TimerGroup::printAll(llvm::errs());
290
291  // When running with -disable-free, don't do any destruction or shutdown.
292  if (Clang->getFrontendOpts().DisableFree) {
293    if (Clang->getFrontendOpts().ShowStats)
294      llvm::PrintStatistics();
295    Clang.take();
296    return !Success;
297  }
298
299  // Managed static deconstruction. Useful for making things like
300  // -time-passes usable.
301  llvm::llvm_shutdown();
302
303  return !Success;
304}
305