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