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