cc1_main.cpp revision 202379
1//===-- cc1_main.cpp - Clang CC1 Driver -----------------------------------===//
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/Driver/Arg.h"
18#include "clang/Driver/ArgList.h"
19#include "clang/Driver/CC1Options.h"
20#include "clang/Driver/DriverDiagnostic.h"
21#include "clang/Driver/OptTable.h"
22#include "clang/Frontend/CompilerInstance.h"
23#include "clang/Frontend/CompilerInvocation.h"
24#include "clang/Frontend/FrontendActions.h"
25#include "clang/Frontend/FrontendDiagnostic.h"
26#include "clang/Frontend/FrontendPluginRegistry.h"
27#include "clang/Frontend/TextDiagnosticBuffer.h"
28#include "clang/Frontend/TextDiagnosticPrinter.h"
29#include "llvm/LLVMContext.h"
30#include "llvm/ADT/OwningPtr.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/ManagedStatic.h"
33#include "llvm/Support/PrettyStackTrace.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/System/DynamicLibrary.h"
36#include "llvm/System/Signals.h"
37#include "llvm/Target/TargetSelect.h"
38#include <cstdio>
39using namespace clang;
40
41//===----------------------------------------------------------------------===//
42// Main driver
43//===----------------------------------------------------------------------===//
44
45void LLVMErrorHandler(void *UserData, const std::string &Message) {
46  Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
47
48  Diags.Report(diag::err_fe_error_backend) << Message;
49
50  // We cannot recover from llvm errors.
51  exit(1);
52}
53
54static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
55  using namespace clang::frontend;
56
57  switch (CI.getFrontendOpts().ProgramAction) {
58  default:
59    llvm_unreachable("Invalid program action!");
60
61  case ASTDump:                return new ASTDumpAction();
62  case ASTPrint:               return new ASTPrintAction();
63  case ASTPrintXML:            return new ASTPrintXMLAction();
64  case ASTView:                return new ASTViewAction();
65  case DumpRawTokens:          return new DumpRawTokensAction();
66  case DumpRecordLayouts:      return new DumpRecordAction();
67  case DumpTokens:             return new DumpTokensAction();
68  case EmitAssembly:           return new EmitAssemblyAction();
69  case EmitBC:                 return new EmitBCAction();
70  case EmitHTML:               return new HTMLPrintAction();
71  case EmitLLVM:               return new EmitLLVMAction();
72  case EmitLLVMOnly:           return new EmitLLVMOnlyAction();
73  case FixIt:                  return new FixItAction();
74  case GeneratePCH:            return new GeneratePCHAction();
75  case GeneratePTH:            return new GeneratePTHAction();
76  case InheritanceView:        return new InheritanceViewAction();
77  case ParseNoop:              return new ParseOnlyAction();
78  case ParsePrintCallbacks:    return new PrintParseAction();
79  case ParseSyntaxOnly:        return new SyntaxOnlyAction();
80
81  case PluginAction: {
82    if (CI.getFrontendOpts().ActionName == "help") {
83      llvm::errs() << "clang -cc1 plugins:\n";
84      for (FrontendPluginRegistry::iterator it =
85             FrontendPluginRegistry::begin(),
86             ie = FrontendPluginRegistry::end();
87           it != ie; ++it)
88        llvm::errs() << "  " << it->getName() << " - " << it->getDesc() << "\n";
89      return 0;
90    }
91
92    for (FrontendPluginRegistry::iterator it =
93           FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
94         it != ie; ++it) {
95      if (it->getName() == CI.getFrontendOpts().ActionName)
96        return it->instantiate();
97    }
98
99    CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
100      << CI.getFrontendOpts().ActionName;
101    return 0;
102  }
103
104  case PrintDeclContext:       return new DeclContextPrintAction();
105  case PrintPreprocessedInput: return new PrintPreprocessedAction();
106  case RewriteMacros:          return new RewriteMacrosAction();
107  case RewriteObjC:            return new RewriteObjCAction();
108  case RewriteTest:            return new RewriteTestAction();
109  case RunAnalysis:            return new AnalysisAction();
110  case RunPreprocessorOnly:    return new PreprocessOnlyAction();
111  }
112}
113
114// FIXME: Define the need for this testing away.
115static int cc1_test(Diagnostic &Diags,
116                    const char **ArgBegin, const char **ArgEnd) {
117  using namespace clang::driver;
118
119  llvm::errs() << "cc1 argv:";
120  for (const char **i = ArgBegin; i != ArgEnd; ++i)
121    llvm::errs() << " \"" << *i << '"';
122  llvm::errs() << "\n";
123
124  // Parse the arguments.
125  OptTable *Opts = createCC1OptTable();
126  unsigned MissingArgIndex, MissingArgCount;
127  InputArgList *Args = Opts->ParseArgs(ArgBegin, ArgEnd,
128                                       MissingArgIndex, MissingArgCount);
129
130  // Check for missing argument error.
131  if (MissingArgCount)
132    Diags.Report(clang::diag::err_drv_missing_argument)
133      << Args->getArgString(MissingArgIndex) << MissingArgCount;
134
135  // Dump the parsed arguments.
136  llvm::errs() << "cc1 parsed options:\n";
137  for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
138       it != ie; ++it)
139    (*it)->dump();
140
141  // Create a compiler invocation.
142  llvm::errs() << "cc1 creating invocation.\n";
143  CompilerInvocation Invocation;
144  CompilerInvocation::CreateFromArgs(Invocation, ArgBegin, ArgEnd, Diags);
145
146  // Convert the invocation back to argument strings.
147  std::vector<std::string> InvocationArgs;
148  Invocation.toArgs(InvocationArgs);
149
150  // Dump the converted arguments.
151  llvm::SmallVector<const char*, 32> Invocation2Args;
152  llvm::errs() << "invocation argv :";
153  for (unsigned i = 0, e = InvocationArgs.size(); i != e; ++i) {
154    Invocation2Args.push_back(InvocationArgs[i].c_str());
155    llvm::errs() << " \"" << InvocationArgs[i] << '"';
156  }
157  llvm::errs() << "\n";
158
159  // Convert those arguments to another invocation, and check that we got the
160  // same thing.
161  CompilerInvocation Invocation2;
162  CompilerInvocation::CreateFromArgs(Invocation2, Invocation2Args.begin(),
163                                     Invocation2Args.end(), Diags);
164
165  // FIXME: Implement CompilerInvocation comparison.
166  if (true) {
167    //llvm::errs() << "warning: Invocations differ!\n";
168
169    std::vector<std::string> Invocation2Args;
170    Invocation2.toArgs(Invocation2Args);
171    llvm::errs() << "invocation2 argv:";
172    for (unsigned i = 0, e = Invocation2Args.size(); i != e; ++i)
173      llvm::errs() << " \"" << Invocation2Args[i] << '"';
174    llvm::errs() << "\n";
175  }
176
177  return 0;
178}
179
180int cc1_main(const char **ArgBegin, const char **ArgEnd,
181             const char *Argv0, void *MainAddr) {
182  CompilerInstance Clang(&llvm::getGlobalContext(), false);
183
184  // Run clang -cc1 test.
185  if (ArgBegin != ArgEnd && llvm::StringRef(ArgBegin[0]) == "-cc1test") {
186    TextDiagnosticPrinter DiagClient(llvm::errs(), DiagnosticOptions());
187    Diagnostic Diags(&DiagClient);
188    return cc1_test(Diags, ArgBegin + 1, ArgEnd);
189  }
190
191  // Initialize targets first, so that --version shows registered targets.
192  llvm::InitializeAllTargets();
193  llvm::InitializeAllAsmPrinters();
194
195  // Buffer diagnostics from argument parsing so that we can output them using a
196  // well formed diagnostic object.
197  TextDiagnosticBuffer DiagsBuffer;
198  Diagnostic Diags(&DiagsBuffer);
199  CompilerInvocation::CreateFromArgs(Clang.getInvocation(), ArgBegin, ArgEnd,
200                                     Diags);
201
202  // Infer the builtin include path if unspecified.
203  if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
204      Clang.getHeaderSearchOpts().ResourceDir.empty())
205    Clang.getHeaderSearchOpts().ResourceDir =
206      CompilerInvocation::GetResourcesPath(Argv0, MainAddr);
207
208  // Honor -help.
209  if (Clang.getFrontendOpts().ShowHelp) {
210    llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1OptTable());
211    Opts->PrintHelp(llvm::outs(), "clang -cc1",
212                    "LLVM 'Clang' Compiler: http://clang.llvm.org");
213    return 0;
214  }
215
216  // Honor -version.
217  //
218  // FIXME: Use a better -version message?
219  if (Clang.getFrontendOpts().ShowVersion) {
220    llvm::cl::PrintVersionMessage();
221    return 0;
222  }
223
224  // Create the actual diagnostics engine.
225  Clang.createDiagnostics(ArgEnd - ArgBegin, const_cast<char**>(ArgBegin));
226  if (!Clang.hasDiagnostics())
227    return 1;
228
229  // Set an error handler, so that any LLVM backend diagnostics go through our
230  // error handler.
231  llvm::llvm_install_error_handler(LLVMErrorHandler,
232                                   static_cast<void*>(&Clang.getDiagnostics()));
233
234  DiagsBuffer.FlushDiagnostics(Clang.getDiagnostics());
235
236  // Load any requested plugins.
237  for (unsigned i = 0,
238         e = Clang.getFrontendOpts().Plugins.size(); i != e; ++i) {
239    const std::string &Path = Clang.getFrontendOpts().Plugins[i];
240    std::string Error;
241    if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Path.c_str(), &Error))
242      Diags.Report(diag::err_fe_unable_to_load_plugin) << Path << Error;
243  }
244
245  // If there were errors in processing arguments, don't do anything else.
246  bool Success = false;
247  if (!Clang.getDiagnostics().getNumErrors()) {
248    // Create and execute the frontend action.
249    llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(Clang));
250    if (Act)
251      Success = Clang.ExecuteAction(*Act);
252  }
253
254  // Managed static deconstruction. Useful for making things like
255  // -time-passes usable.
256  llvm::llvm_shutdown();
257
258  return !Success;
259}
260