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