cc1as_main.cpp revision ad3dfbe463cb72f2b99a8b5ff3cab92ccfbaa9ea
1//===-- cc1as_main.cpp - Clang Assembler  ---------------------------------===//
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 -cc1as functionality, which implements
11// the direct interface to the LLVM MC based assembler.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Basic/Diagnostic.h"
16#include "clang/Driver/Arg.h"
17#include "clang/Driver/ArgList.h"
18#include "clang/Driver/DriverDiagnostic.h"
19#include "clang/Driver/CC1AsOptions.h"
20#include "clang/Driver/OptTable.h"
21#include "clang/Driver/Options.h"
22#include "clang/Frontend/DiagnosticOptions.h"
23#include "clang/Frontend/FrontendDiagnostic.h"
24#include "clang/Frontend/TextDiagnosticPrinter.h"
25#include "llvm/ADT/OwningPtr.h"
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/ADT/Triple.h"
28#include "llvm/MC/MCParser/MCAsmParser.h"
29#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCCodeEmitter.h"
31#include "llvm/MC/MCContext.h"
32#include "llvm/MC/MCStreamer.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/FormattedStream.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Support/ManagedStatic.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/PrettyStackTrace.h"
39#include "llvm/Support/SourceMgr.h"
40#include "llvm/Support/Timer.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/Support/Host.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/Signals.h"
45#include "llvm/Support/system_error.h"
46#include "llvm/Target/TargetAsmBackend.h"
47#include "llvm/Target/TargetAsmInfo.h"
48#include "llvm/Target/TargetAsmParser.h"
49#include "llvm/Target/TargetData.h"
50#include "llvm/Target/TargetLowering.h"
51#include "llvm/Target/TargetLoweringObjectFile.h"
52#include "llvm/Target/TargetMachine.h"
53#include "llvm/Target/TargetRegistry.h"
54#include "llvm/Target/TargetSelect.h"
55using namespace clang;
56using namespace clang::driver;
57using namespace llvm;
58
59namespace {
60
61/// \brief Helper class for representing a single invocation of the assembler.
62struct AssemblerInvocation {
63  /// @name Target Options
64  /// @{
65
66  std::string Triple;
67
68  /// @}
69  /// @name Language Options
70  /// @{
71
72  std::vector<std::string> IncludePaths;
73  unsigned NoInitialTextSection : 1;
74
75  /// @}
76  /// @name Frontend Options
77  /// @{
78
79  std::string InputFile;
80  std::vector<std::string> LLVMArgs;
81  std::string OutputPath;
82  enum FileType {
83    FT_Asm,  ///< Assembly (.s) output, transliterate mode.
84    FT_Null, ///< No output, for timing purposes.
85    FT_Obj   ///< Object file output.
86  };
87  FileType OutputType;
88  unsigned ShowHelp : 1;
89  unsigned ShowVersion : 1;
90
91  /// @}
92  /// @name Transliterate Options
93  /// @{
94
95  unsigned OutputAsmVariant;
96  unsigned ShowEncoding : 1;
97  unsigned ShowInst : 1;
98
99  /// @}
100  /// @name Assembler Options
101  /// @{
102
103  unsigned RelaxAll : 1;
104  unsigned NoExecStack : 1;
105
106  /// @}
107
108public:
109  AssemblerInvocation() {
110    Triple = "";
111    NoInitialTextSection = 0;
112    InputFile = "-";
113    OutputPath = "-";
114    OutputType = FT_Asm;
115    OutputAsmVariant = 0;
116    ShowInst = 0;
117    ShowEncoding = 0;
118    RelaxAll = 0;
119    NoExecStack = 0;
120  }
121
122  static void CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
123                             const char **ArgEnd, Diagnostic &Diags);
124};
125
126}
127
128void AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
129                                         const char **ArgBegin,
130                                         const char **ArgEnd,
131                                         Diagnostic &Diags) {
132  using namespace clang::driver::cc1asoptions;
133  // Parse the arguments.
134  OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
135  unsigned MissingArgIndex, MissingArgCount;
136  OwningPtr<InputArgList> Args(
137    OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
138
139  // Check for missing argument error.
140  if (MissingArgCount)
141    Diags.Report(diag::err_drv_missing_argument)
142      << Args->getArgString(MissingArgIndex) << MissingArgCount;
143
144  // Issue errors on unknown arguments.
145  for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
146         ie = Args->filtered_end(); it != ie; ++it)
147    Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
148
149  // Construct the invocation.
150
151  // Target Options
152  Opts.Triple = Triple::normalize(Args->getLastArgValue(OPT_triple));
153  if (Opts.Triple.empty()) // Use the host triple if unspecified.
154    Opts.Triple = sys::getHostTriple();
155
156  // Language Options
157  Opts.IncludePaths = Args->getAllArgValues(OPT_I);
158  Opts.NoInitialTextSection = Args->hasArg(OPT_n);
159
160  // Frontend Options
161  if (Args->hasArg(OPT_INPUT)) {
162    bool First = true;
163    for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
164           ie = Args->filtered_end(); it != ie; ++it, First=false) {
165      const Arg *A = it;
166      if (First)
167        Opts.InputFile = A->getValue(*Args);
168      else
169        Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
170    }
171  }
172  Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
173  Opts.OutputPath = Args->getLastArgValue(OPT_o);
174  if (Arg *A = Args->getLastArg(OPT_filetype)) {
175    StringRef Name = A->getValue(*Args);
176    unsigned OutputType = StringSwitch<unsigned>(Name)
177      .Case("asm", FT_Asm)
178      .Case("null", FT_Null)
179      .Case("obj", FT_Obj)
180      .Default(~0U);
181    if (OutputType == ~0U)
182      Diags.Report(diag::err_drv_invalid_value)
183        << A->getAsString(*Args) << Name;
184    else
185      Opts.OutputType = FileType(OutputType);
186  }
187  Opts.ShowHelp = Args->hasArg(OPT_help);
188  Opts.ShowVersion = Args->hasArg(OPT_version);
189
190  // Transliterate Options
191  Opts.OutputAsmVariant = Args->getLastArgIntValue(OPT_output_asm_variant,
192                                                   0, Diags);
193  Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
194  Opts.ShowInst = Args->hasArg(OPT_show_inst);
195
196  // Assemble Options
197  Opts.RelaxAll = Args->hasArg(OPT_relax_all);
198  Opts.NoExecStack =  Args->hasArg(OPT_no_exec_stack);
199}
200
201static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
202                                              Diagnostic &Diags,
203                                              bool Binary) {
204  if (Opts.OutputPath.empty())
205    Opts.OutputPath = "-";
206
207  // Make sure that the Out file gets unlinked from the disk if we get a
208  // SIGINT.
209  if (Opts.OutputPath != "-")
210    sys::RemoveFileOnSignal(sys::Path(Opts.OutputPath));
211
212  std::string Error;
213  raw_fd_ostream *Out =
214    new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
215                       (Binary ? raw_fd_ostream::F_Binary : 0));
216  if (!Error.empty()) {
217    Diags.Report(diag::err_fe_unable_to_open_output)
218      << Opts.OutputPath << Error;
219    return 0;
220  }
221
222  return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
223}
224
225static bool ExecuteAssembler(AssemblerInvocation &Opts, Diagnostic &Diags) {
226  // Get the target specific parser.
227  std::string Error;
228  const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
229  if (!TheTarget) {
230    Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
231    return false;
232  }
233
234  OwningPtr<MemoryBuffer> BufferPtr;
235  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
236    Error = ec.message();
237    Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
238    return false;
239  }
240  MemoryBuffer *Buffer = BufferPtr.take();
241
242  SourceMgr SrcMgr;
243
244  // Tell SrcMgr about this buffer, which is what the parser will pick up.
245  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
246
247  // Record the location of the include directories so that the lexer can find
248  // it later.
249  SrcMgr.setIncludeDirs(Opts.IncludePaths);
250
251  OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(Opts.Triple));
252  assert(MAI && "Unable to create target asm info!");
253
254  bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
255  formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
256  if (!Out)
257    return false;
258
259  // FIXME: We shouldn't need to do this (and link in codegen).
260  OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(Opts.Triple, ""));
261  if (!TM) {
262    Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
263    return false;
264  }
265
266  const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
267  MCContext Ctx(*MAI, tai);
268
269  OwningPtr<MCStreamer> Str;
270
271  const TargetLoweringObjectFile &TLOF =
272    TM->getTargetLowering()->getObjFileLowering();
273  const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
274
275  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
276  if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
277    MCInstPrinter *IP =
278      TheTarget->createMCInstPrinter(*TM, Opts.OutputAsmVariant, *MAI);
279    MCCodeEmitter *CE = 0;
280    TargetAsmBackend *TAB = 0;
281    if (Opts.ShowEncoding) {
282      CE = TheTarget->createCodeEmitter(*TM, Ctx);
283      TAB = TheTarget->createAsmBackend(Opts.Triple);
284    }
285    Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
286                                           /*useLoc*/ true, IP, CE, TAB,
287                                           Opts.ShowInst));
288  } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
289    Str.reset(createNullStreamer(Ctx));
290  } else {
291    assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
292           "Invalid file type!");
293    MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
294    TargetAsmBackend *TAB = TheTarget->createAsmBackend(Opts.Triple);
295    Str.reset(TheTarget->createObjectStreamer(Opts.Triple, Ctx, *TAB, *Out,
296                                              CE, Opts.RelaxAll,
297                                              Opts.NoExecStack));
298    Str.get()->InitSections();
299  }
300
301  OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
302                                                  *Str.get(), *MAI));
303  OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
304  if (!TAP) {
305    Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
306    return false;
307  }
308
309  Parser->setTargetParser(*TAP.get());
310
311  bool Success = !Parser->Run(Opts.NoInitialTextSection);
312
313  // Close the output.
314  delete Out;
315
316  // Delete output on errors.
317  if (!Success && Opts.OutputPath != "-")
318    sys::Path(Opts.OutputPath).eraseFromDisk();
319
320  return Success;
321}
322
323static void LLVMErrorHandler(void *UserData, const std::string &Message) {
324  Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
325
326  Diags.Report(diag::err_fe_error_backend) << Message;
327
328  // We cannot recover from llvm errors.
329  exit(1);
330}
331
332int cc1as_main(const char **ArgBegin, const char **ArgEnd,
333               const char *Argv0, void *MainAddr) {
334  // Print a stack trace if we signal out.
335  sys::PrintStackTraceOnErrorSignal();
336  PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
337  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
338
339  // Initialize targets and assembly printers/parsers.
340  InitializeAllTargetInfos();
341  // FIXME: We shouldn't need to initialize the Target(Machine)s.
342  InitializeAllTargets();
343  InitializeAllAsmPrinters();
344  InitializeAllAsmParsers();
345
346  // Construct our diagnostic client.
347  TextDiagnosticPrinter *DiagClient
348    = new TextDiagnosticPrinter(errs(), DiagnosticOptions());
349  DiagClient->setPrefix("clang -cc1as");
350  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
351  Diagnostic Diags(DiagID, DiagClient);
352
353  // Set an error handler, so that any LLVM backend diagnostics go through our
354  // error handler.
355  ScopedFatalErrorHandler FatalErrorHandler
356    (LLVMErrorHandler, static_cast<void*>(&Diags));
357
358  // Parse the arguments.
359  AssemblerInvocation Asm;
360  AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags);
361
362  // Honor -help.
363  if (Asm.ShowHelp) {
364    llvm::OwningPtr<driver::OptTable> Opts(driver::createCC1AsOptTable());
365    Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
366    return 0;
367  }
368
369  // Honor -version.
370  //
371  // FIXME: Use a better -version message?
372  if (Asm.ShowVersion) {
373    llvm::cl::PrintVersionMessage();
374    return 0;
375  }
376
377  // Honor -mllvm.
378  //
379  // FIXME: Remove this, one day.
380  if (!Asm.LLVMArgs.empty()) {
381    unsigned NumArgs = Asm.LLVMArgs.size();
382    const char **Args = new const char*[NumArgs + 2];
383    Args[0] = "clang (LLVM option parsing)";
384    for (unsigned i = 0; i != NumArgs; ++i)
385      Args[i + 1] = Asm.LLVMArgs[i].c_str();
386    Args[NumArgs + 1] = 0;
387    llvm::cl::ParseCommandLineOptions(NumArgs + 1, const_cast<char **>(Args));
388  }
389
390  // Execute the invocation, unless there were parsing errors.
391  bool Success = false;
392  if (!Diags.hasErrorOccurred())
393    Success = ExecuteAssembler(Asm, Diags);
394
395  // If any timers were active but haven't been destroyed yet, print their
396  // results now.
397  TimerGroup::printAll(errs());
398
399  return !Success;
400}
401