cc1as_main.cpp revision b1e25a1bc03292dc538d336573e0be1490223171
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/Basic/DiagnosticOptions.h"
17#include "clang/Driver/CC1AsOptions.h"
18#include "clang/Driver/DriverDiagnostic.h"
19#include "clang/Driver/Options.h"
20#include "clang/Frontend/FrontendDiagnostic.h"
21#include "clang/Frontend/TextDiagnosticPrinter.h"
22#include "clang/Frontend/Utils.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/ADT/StringSwitch.h"
25#include "llvm/ADT/Triple.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/MC/MCAsmBackend.h"
28#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCCodeEmitter.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCInstrInfo.h"
32#include "llvm/MC/MCObjectFileInfo.h"
33#include "llvm/MC/MCParser/MCAsmParser.h"
34#include "llvm/MC/MCRegisterInfo.h"
35#include "llvm/MC/MCStreamer.h"
36#include "llvm/MC/MCSubtargetInfo.h"
37#include "llvm/MC/MCTargetAsmParser.h"
38#include "llvm/Option/Arg.h"
39#include "llvm/Option/ArgList.h"
40#include "llvm/Option/OptTable.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/FormattedStream.h"
44#include "llvm/Support/Host.h"
45#include "llvm/Support/ManagedStatic.h"
46#include "llvm/Support/MemoryBuffer.h"
47#include "llvm/Support/Path.h"
48#include "llvm/Support/PathV1.h"
49#include "llvm/Support/PrettyStackTrace.h"
50#include "llvm/Support/Signals.h"
51#include "llvm/Support/SourceMgr.h"
52#include "llvm/Support/TargetRegistry.h"
53#include "llvm/Support/TargetSelect.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/Support/system_error.h"
57using namespace clang;
58using namespace clang::driver;
59using namespace llvm;
60using namespace llvm::opt;
61
62namespace {
63
64/// \brief Helper class for representing a single invocation of the assembler.
65struct AssemblerInvocation {
66  /// @name Target Options
67  /// @{
68
69  /// The name of the target triple to assemble for.
70  std::string Triple;
71
72  /// If given, the name of the target CPU to determine which instructions
73  /// are legal.
74  std::string CPU;
75
76  /// The list of target specific features to enable or disable -- this should
77  /// be a list of strings starting with '+' or '-'.
78  std::vector<std::string> Features;
79
80  /// @}
81  /// @name Language Options
82  /// @{
83
84  std::vector<std::string> IncludePaths;
85  unsigned NoInitialTextSection : 1;
86  unsigned SaveTemporaryLabels : 1;
87  unsigned GenDwarfForAssembly : 1;
88  std::string DwarfDebugFlags;
89  std::string DwarfDebugProducer;
90  std::string DebugCompilationDir;
91  std::string MainFileName;
92
93  /// @}
94  /// @name Frontend Options
95  /// @{
96
97  std::string InputFile;
98  std::vector<std::string> LLVMArgs;
99  std::string OutputPath;
100  enum FileType {
101    FT_Asm,  ///< Assembly (.s) output, transliterate mode.
102    FT_Null, ///< No output, for timing purposes.
103    FT_Obj   ///< Object file output.
104  };
105  FileType OutputType;
106  unsigned ShowHelp : 1;
107  unsigned ShowVersion : 1;
108
109  /// @}
110  /// @name Transliterate Options
111  /// @{
112
113  unsigned OutputAsmVariant;
114  unsigned ShowEncoding : 1;
115  unsigned ShowInst : 1;
116
117  /// @}
118  /// @name Assembler Options
119  /// @{
120
121  unsigned RelaxAll : 1;
122  unsigned NoExecStack : 1;
123
124  /// @}
125
126public:
127  AssemblerInvocation() {
128    Triple = "";
129    NoInitialTextSection = 0;
130    InputFile = "-";
131    OutputPath = "-";
132    OutputType = FT_Asm;
133    OutputAsmVariant = 0;
134    ShowInst = 0;
135    ShowEncoding = 0;
136    RelaxAll = 0;
137    NoExecStack = 0;
138  }
139
140  static bool CreateFromArgs(AssemblerInvocation &Res, const char **ArgBegin,
141                             const char **ArgEnd, DiagnosticsEngine &Diags);
142};
143
144}
145
146bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
147                                         const char **ArgBegin,
148                                         const char **ArgEnd,
149                                         DiagnosticsEngine &Diags) {
150  using namespace clang::driver::cc1asoptions;
151  bool Success = true;
152
153  // Parse the arguments.
154  OwningPtr<OptTable> OptTbl(createCC1AsOptTable());
155  unsigned MissingArgIndex, MissingArgCount;
156  OwningPtr<InputArgList> Args(
157    OptTbl->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
158
159  // Check for missing argument error.
160  if (MissingArgCount) {
161    Diags.Report(diag::err_drv_missing_argument)
162      << Args->getArgString(MissingArgIndex) << MissingArgCount;
163    Success = false;
164  }
165
166  // Issue errors on unknown arguments.
167  for (arg_iterator it = Args->filtered_begin(cc1asoptions::OPT_UNKNOWN),
168         ie = Args->filtered_end(); it != ie; ++it) {
169    Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
170    Success = false;
171  }
172
173  // Construct the invocation.
174
175  // Target Options
176  Opts.Triple = llvm::Triple::normalize(Args->getLastArgValue(OPT_triple));
177  Opts.CPU = Args->getLastArgValue(OPT_target_cpu);
178  Opts.Features = Args->getAllArgValues(OPT_target_feature);
179
180  // Use the default target triple if unspecified.
181  if (Opts.Triple.empty())
182    Opts.Triple = llvm::sys::getDefaultTargetTriple();
183
184  // Language Options
185  Opts.IncludePaths = Args->getAllArgValues(OPT_I);
186  Opts.NoInitialTextSection = Args->hasArg(OPT_n);
187  Opts.SaveTemporaryLabels = Args->hasArg(OPT_L);
188  Opts.GenDwarfForAssembly = Args->hasArg(OPT_g);
189  Opts.DwarfDebugFlags = Args->getLastArgValue(OPT_dwarf_debug_flags);
190  Opts.DwarfDebugProducer = Args->getLastArgValue(OPT_dwarf_debug_producer);
191  Opts.DebugCompilationDir = Args->getLastArgValue(OPT_fdebug_compilation_dir);
192  Opts.MainFileName = Args->getLastArgValue(OPT_main_file_name);
193
194  // Frontend Options
195  if (Args->hasArg(OPT_INPUT)) {
196    bool First = true;
197    for (arg_iterator it = Args->filtered_begin(OPT_INPUT),
198           ie = Args->filtered_end(); it != ie; ++it, First=false) {
199      const Arg *A = it;
200      if (First)
201        Opts.InputFile = A->getValue();
202      else {
203        Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(*Args);
204        Success = false;
205      }
206    }
207  }
208  Opts.LLVMArgs = Args->getAllArgValues(OPT_mllvm);
209  if (Args->hasArg(OPT_fatal_warnings))
210    Opts.LLVMArgs.push_back("-fatal-assembler-warnings");
211  Opts.OutputPath = Args->getLastArgValue(OPT_o);
212  if (Arg *A = Args->getLastArg(OPT_filetype)) {
213    StringRef Name = A->getValue();
214    unsigned OutputType = StringSwitch<unsigned>(Name)
215      .Case("asm", FT_Asm)
216      .Case("null", FT_Null)
217      .Case("obj", FT_Obj)
218      .Default(~0U);
219    if (OutputType == ~0U) {
220      Diags.Report(diag::err_drv_invalid_value)
221        << A->getAsString(*Args) << Name;
222      Success = false;
223    } else
224      Opts.OutputType = FileType(OutputType);
225  }
226  Opts.ShowHelp = Args->hasArg(OPT_help);
227  Opts.ShowVersion = Args->hasArg(OPT_version);
228
229  // Transliterate Options
230  Opts.OutputAsmVariant =
231      getLastArgIntValue(*Args.get(), OPT_output_asm_variant, 0, Diags);
232  Opts.ShowEncoding = Args->hasArg(OPT_show_encoding);
233  Opts.ShowInst = Args->hasArg(OPT_show_inst);
234
235  // Assemble Options
236  Opts.RelaxAll = Args->hasArg(OPT_relax_all);
237  Opts.NoExecStack =  Args->hasArg(OPT_no_exec_stack);
238
239  return Success;
240}
241
242static formatted_raw_ostream *GetOutputStream(AssemblerInvocation &Opts,
243                                              DiagnosticsEngine &Diags,
244                                              bool Binary) {
245  if (Opts.OutputPath.empty())
246    Opts.OutputPath = "-";
247
248  // Make sure that the Out file gets unlinked from the disk if we get a
249  // SIGINT.
250  if (Opts.OutputPath != "-")
251    sys::RemoveFileOnSignal(Opts.OutputPath);
252
253  std::string Error;
254  raw_fd_ostream *Out =
255    new raw_fd_ostream(Opts.OutputPath.c_str(), Error,
256                       (Binary ? raw_fd_ostream::F_Binary : 0));
257  if (!Error.empty()) {
258    Diags.Report(diag::err_fe_unable_to_open_output)
259      << Opts.OutputPath << Error;
260    return 0;
261  }
262
263  return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
264}
265
266static bool ExecuteAssembler(AssemblerInvocation &Opts,
267                             DiagnosticsEngine &Diags) {
268  // Get the target specific parser.
269  std::string Error;
270  const Target *TheTarget(TargetRegistry::lookupTarget(Opts.Triple, Error));
271  if (!TheTarget) {
272    Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
273    return false;
274  }
275
276  OwningPtr<MemoryBuffer> BufferPtr;
277  if (error_code ec = MemoryBuffer::getFileOrSTDIN(Opts.InputFile, BufferPtr)) {
278    Error = ec.message();
279    Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
280    return false;
281  }
282  MemoryBuffer *Buffer = BufferPtr.take();
283
284  SourceMgr SrcMgr;
285
286  // Tell SrcMgr about this buffer, which is what the parser will pick up.
287  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
288
289  // Record the location of the include directories so that the lexer can find
290  // it later.
291  SrcMgr.setIncludeDirs(Opts.IncludePaths);
292
293  OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
294  assert(MRI && "Unable to create target register info!");
295
296  OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
297  assert(MAI && "Unable to create target asm info!");
298
299  bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
300  formatted_raw_ostream *Out = GetOutputStream(Opts, Diags, IsBinary);
301  if (!Out)
302    return false;
303
304  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
305  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
306  OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
307  MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
308  // FIXME: Assembler behavior can change with -static.
309  MOFI->InitMCObjectFileInfo(Opts.Triple,
310                             Reloc::Default, CodeModel::Default, Ctx);
311  if (Opts.SaveTemporaryLabels)
312    Ctx.setAllowTemporaryLabels(false);
313  if (Opts.GenDwarfForAssembly)
314    Ctx.setGenDwarfForAssembly(true);
315  if (!Opts.DwarfDebugFlags.empty())
316    Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
317  if (!Opts.DwarfDebugProducer.empty())
318    Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
319  if (!Opts.DebugCompilationDir.empty())
320    Ctx.setCompilationDir(Opts.DebugCompilationDir);
321  if (!Opts.MainFileName.empty())
322    Ctx.setMainFileName(StringRef(Opts.MainFileName));
323
324  // Build up the feature string from the target feature list.
325  std::string FS;
326  if (!Opts.Features.empty()) {
327    FS = Opts.Features[0];
328    for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
329      FS += "," + Opts.Features[i];
330  }
331
332  OwningPtr<MCStreamer> Str;
333
334  OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
335  OwningPtr<MCSubtargetInfo>
336    STI(TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
337
338  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
339  if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
340    MCInstPrinter *IP =
341      TheTarget->createMCInstPrinter(Opts.OutputAsmVariant, *MAI, *MCII, *MRI,
342                                     *STI);
343    MCCodeEmitter *CE = 0;
344    MCAsmBackend *MAB = 0;
345    if (Opts.ShowEncoding) {
346      CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
347      MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU);
348    }
349    Str.reset(TheTarget->createAsmStreamer(Ctx, *Out, /*asmverbose*/true,
350                                           /*useLoc*/ true,
351                                           /*useCFI*/ true,
352                                           /*useDwarfDirectory*/ true,
353                                           IP, CE, MAB,
354                                           Opts.ShowInst));
355  } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
356    Str.reset(createNullStreamer(Ctx));
357  } else {
358    assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
359           "Invalid file type!");
360    MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
361    MCAsmBackend *MAB = TheTarget->createMCAsmBackend(Opts.Triple, Opts.CPU);
362    Str.reset(TheTarget->createMCObjectStreamer(Opts.Triple, Ctx, *MAB, *Out,
363                                                CE, Opts.RelaxAll,
364                                                Opts.NoExecStack));
365    Str.get()->InitSections();
366  }
367
368  OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
369                                                  *Str.get(), *MAI));
370  OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
371  if (!TAP) {
372    Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
373    return false;
374  }
375
376  Parser->setTargetParser(*TAP.get());
377
378  bool Success = !Parser->Run(Opts.NoInitialTextSection);
379
380  // Close the output.
381  delete Out;
382
383  // Delete output on errors.
384  if (!Success && Opts.OutputPath != "-")
385    sys::Path(Opts.OutputPath).eraseFromDisk();
386
387  return Success;
388}
389
390static void LLVMErrorHandler(void *UserData, const std::string &Message,
391                             bool GenCrashDiag) {
392  DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
393
394  Diags.Report(diag::err_fe_error_backend) << Message;
395
396  // We cannot recover from llvm errors.
397  exit(1);
398}
399
400int cc1as_main(const char **ArgBegin, const char **ArgEnd,
401               const char *Argv0, void *MainAddr) {
402  // Print a stack trace if we signal out.
403  sys::PrintStackTraceOnErrorSignal();
404  PrettyStackTraceProgram X(ArgEnd - ArgBegin, ArgBegin);
405  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
406
407  // Initialize targets and assembly printers/parsers.
408  InitializeAllTargetInfos();
409  InitializeAllTargetMCs();
410  InitializeAllAsmParsers();
411
412  // Construct our diagnostic client.
413  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
414  TextDiagnosticPrinter *DiagClient
415    = new TextDiagnosticPrinter(errs(), &*DiagOpts);
416  DiagClient->setPrefix("clang -cc1as");
417  IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
418  DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
419
420  // Set an error handler, so that any LLVM backend diagnostics go through our
421  // error handler.
422  ScopedFatalErrorHandler FatalErrorHandler
423    (LLVMErrorHandler, static_cast<void*>(&Diags));
424
425  // Parse the arguments.
426  AssemblerInvocation Asm;
427  if (!AssemblerInvocation::CreateFromArgs(Asm, ArgBegin, ArgEnd, Diags))
428    return 1;
429
430  // Honor -help.
431  if (Asm.ShowHelp) {
432    OwningPtr<OptTable> Opts(driver::createCC1AsOptTable());
433    Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler");
434    return 0;
435  }
436
437  // Honor -version.
438  //
439  // FIXME: Use a better -version message?
440  if (Asm.ShowVersion) {
441    llvm::cl::PrintVersionMessage();
442    return 0;
443  }
444
445  // Honor -mllvm.
446  //
447  // FIXME: Remove this, one day.
448  if (!Asm.LLVMArgs.empty()) {
449    unsigned NumArgs = Asm.LLVMArgs.size();
450    const char **Args = new const char*[NumArgs + 2];
451    Args[0] = "clang (LLVM option parsing)";
452    for (unsigned i = 0; i != NumArgs; ++i)
453      Args[i + 1] = Asm.LLVMArgs[i].c_str();
454    Args[NumArgs + 1] = 0;
455    llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args);
456  }
457
458  // Execute the invocation, unless there were parsing errors.
459  bool Success = false;
460  if (!Diags.hasErrorOccurred())
461    Success = ExecuteAssembler(Asm, Diags);
462
463  // If any timers were active but haven't been destroyed yet, print their
464  // results now.
465  TimerGroup::printAll(errs());
466
467  return !Success;
468}
469