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/DriverDiagnostic.h"
18 #include "clang/Driver/Options.h"
19 #include "clang/Frontend/FrontendDiagnostic.h"
20 #include "clang/Frontend/TextDiagnosticPrinter.h"
21 #include "clang/Frontend/Utils.h"
22 #include "llvm/ADT/STLExtras.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/MCParser/MCTargetAsmParser.h"
34 #include "llvm/MC/MCRegisterInfo.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSubtargetInfo.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/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Signals.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/TargetRegistry.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/Timer.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <memory>
55 #include <system_error>
56 using namespace clang;
57 using namespace clang::driver;
58 using namespace clang::driver::options;
59 using namespace llvm;
60 using namespace llvm::opt;
61 
62 namespace {
63 
64 /// \brief Helper class for representing a single invocation of the assembler.
65 struct 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   /// The list of symbol definitions.
81   std::vector<std::string> SymbolDefs;
82 
83   /// @}
84   /// @name Language Options
85   /// @{
86 
87   std::vector<std::string> IncludePaths;
88   unsigned NoInitialTextSection : 1;
89   unsigned SaveTemporaryLabels : 1;
90   unsigned GenDwarfForAssembly : 1;
91   unsigned RelaxELFRelocations : 1;
92   unsigned DwarfVersion;
93   std::string DwarfDebugFlags;
94   std::string DwarfDebugProducer;
95   std::string DebugCompilationDir;
96   llvm::DebugCompressionType CompressDebugSections =
97       llvm::DebugCompressionType::None;
98   std::string MainFileName;
99 
100   /// @}
101   /// @name Frontend Options
102   /// @{
103 
104   std::string InputFile;
105   std::vector<std::string> LLVMArgs;
106   std::string OutputPath;
107   enum FileType {
108     FT_Asm,  ///< Assembly (.s) output, transliterate mode.
109     FT_Null, ///< No output, for timing purposes.
110     FT_Obj   ///< Object file output.
111   };
112   FileType OutputType;
113   unsigned ShowHelp : 1;
114   unsigned ShowVersion : 1;
115 
116   /// @}
117   /// @name Transliterate Options
118   /// @{
119 
120   unsigned OutputAsmVariant;
121   unsigned ShowEncoding : 1;
122   unsigned ShowInst : 1;
123 
124   /// @}
125   /// @name Assembler Options
126   /// @{
127 
128   unsigned RelaxAll : 1;
129   unsigned NoExecStack : 1;
130   unsigned FatalWarnings : 1;
131   unsigned IncrementalLinkerCompatible : 1;
132 
133   /// The name of the relocation model to use.
134   std::string RelocationModel;
135 
136   /// @}
137 
138 public:
139   AssemblerInvocation() {
140     Triple = "";
141     NoInitialTextSection = 0;
142     InputFile = "-";
143     OutputPath = "-";
144     OutputType = FT_Asm;
145     OutputAsmVariant = 0;
146     ShowInst = 0;
147     ShowEncoding = 0;
148     RelaxAll = 0;
149     NoExecStack = 0;
150     FatalWarnings = 0;
151     IncrementalLinkerCompatible = 0;
152     DwarfVersion = 0;
153   }
154 
155   static bool CreateFromArgs(AssemblerInvocation &Res,
156                              ArrayRef<const char *> Argv,
157                              DiagnosticsEngine &Diags);
158 };
159 
160 }
161 
162 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
163                                          ArrayRef<const char *> Argv,
164                                          DiagnosticsEngine &Diags) {
165   bool Success = true;
166 
167   // Parse the arguments.
168   std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
169 
170   const unsigned IncludedFlagsBitmask = options::CC1AsOption;
171   unsigned MissingArgIndex, MissingArgCount;
172   InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
173                                         IncludedFlagsBitmask);
174 
175   // Check for missing argument error.
176   if (MissingArgCount) {
177     Diags.Report(diag::err_drv_missing_argument)
178         << Args.getArgString(MissingArgIndex) << MissingArgCount;
179     Success = false;
180   }
181 
182   // Issue errors on unknown arguments.
183   for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
184     Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
185     Success = false;
186   }
187 
188   // Construct the invocation.
189 
190   // Target Options
191   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
192   Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
193   Opts.Features = Args.getAllArgValues(OPT_target_feature);
194 
195   // Use the default target triple if unspecified.
196   if (Opts.Triple.empty())
197     Opts.Triple = llvm::sys::getDefaultTargetTriple();
198 
199   // Language Options
200   Opts.IncludePaths = Args.getAllArgValues(OPT_I);
201   Opts.NoInitialTextSection = Args.hasArg(OPT_n);
202   Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
203   // Any DebugInfoKind implies GenDwarfForAssembly.
204   Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
205 
206   if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
207                                      OPT_compress_debug_sections_EQ)) {
208     if (A->getOption().getID() == OPT_compress_debug_sections) {
209       // TODO: be more clever about the compression type auto-detection
210       Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
211     } else {
212       Opts.CompressDebugSections =
213           llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
214               .Case("none", llvm::DebugCompressionType::None)
215               .Case("zlib", llvm::DebugCompressionType::Z)
216               .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
217               .Default(llvm::DebugCompressionType::None);
218     }
219   }
220 
221   Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
222   Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
223   Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
224   Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
225   Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
226   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
227 
228   // Frontend Options
229   if (Args.hasArg(OPT_INPUT)) {
230     bool First = true;
231     for (const Arg *A : Args.filtered(OPT_INPUT)) {
232       if (First) {
233         Opts.InputFile = A->getValue();
234         First = false;
235       } else {
236         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
237         Success = false;
238       }
239     }
240   }
241   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
242   Opts.OutputPath = Args.getLastArgValue(OPT_o);
243   if (Arg *A = Args.getLastArg(OPT_filetype)) {
244     StringRef Name = A->getValue();
245     unsigned OutputType = StringSwitch<unsigned>(Name)
246       .Case("asm", FT_Asm)
247       .Case("null", FT_Null)
248       .Case("obj", FT_Obj)
249       .Default(~0U);
250     if (OutputType == ~0U) {
251       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
252       Success = false;
253     } else
254       Opts.OutputType = FileType(OutputType);
255   }
256   Opts.ShowHelp = Args.hasArg(OPT_help);
257   Opts.ShowVersion = Args.hasArg(OPT_version);
258 
259   // Transliterate Options
260   Opts.OutputAsmVariant =
261       getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
262   Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
263   Opts.ShowInst = Args.hasArg(OPT_show_inst);
264 
265   // Assemble Options
266   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
267   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
268   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
269   Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
270   Opts.IncrementalLinkerCompatible =
271       Args.hasArg(OPT_mincremental_linker_compatible);
272   Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
273 
274   return Success;
275 }
276 
277 static std::unique_ptr<raw_fd_ostream>
278 getOutputStream(AssemblerInvocation &Opts, DiagnosticsEngine &Diags,
279                 bool Binary) {
280   if (Opts.OutputPath.empty())
281     Opts.OutputPath = "-";
282 
283   // Make sure that the Out file gets unlinked from the disk if we get a
284   // SIGINT.
285   if (Opts.OutputPath != "-")
286     sys::RemoveFileOnSignal(Opts.OutputPath);
287 
288   std::error_code EC;
289   auto Out = llvm::make_unique<raw_fd_ostream>(
290       Opts.OutputPath, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
291   if (EC) {
292     Diags.Report(diag::err_fe_unable_to_open_output) << Opts.OutputPath
293                                                      << EC.message();
294     return nullptr;
295   }
296 
297   return Out;
298 }
299 
300 static bool ExecuteAssembler(AssemblerInvocation &Opts,
301                              DiagnosticsEngine &Diags) {
302   // Get the target specific parser.
303   std::string Error;
304   const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
305   if (!TheTarget)
306     return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
307 
308   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
309       MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
310 
311   if (std::error_code EC = Buffer.getError()) {
312     Error = EC.message();
313     return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
314   }
315 
316   SourceMgr SrcMgr;
317 
318   // Tell SrcMgr about this buffer, which is what the parser will pick up.
319   SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
320 
321   // Record the location of the include directories so that the lexer can find
322   // it later.
323   SrcMgr.setIncludeDirs(Opts.IncludePaths);
324 
325   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
326   assert(MRI && "Unable to create target register info!");
327 
328   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
329   assert(MAI && "Unable to create target asm info!");
330 
331   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
332   // may be created with a combination of default and explicit settings.
333   MAI->setCompressDebugSections(Opts.CompressDebugSections);
334 
335   MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
336 
337   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
338   std::unique_ptr<raw_fd_ostream> FDOS = getOutputStream(Opts, Diags, IsBinary);
339   if (!FDOS)
340     return true;
341 
342   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
343   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
344   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
345 
346   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
347 
348   bool PIC = false;
349   if (Opts.RelocationModel == "static") {
350     PIC = false;
351   } else if (Opts.RelocationModel == "pic") {
352     PIC = true;
353   } else {
354     assert(Opts.RelocationModel == "dynamic-no-pic" &&
355            "Invalid PIC model!");
356     PIC = false;
357   }
358 
359   MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
360   if (Opts.SaveTemporaryLabels)
361     Ctx.setAllowTemporaryLabels(false);
362   if (Opts.GenDwarfForAssembly)
363     Ctx.setGenDwarfForAssembly(true);
364   if (!Opts.DwarfDebugFlags.empty())
365     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
366   if (!Opts.DwarfDebugProducer.empty())
367     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
368   if (!Opts.DebugCompilationDir.empty())
369     Ctx.setCompilationDir(Opts.DebugCompilationDir);
370   if (!Opts.MainFileName.empty())
371     Ctx.setMainFileName(StringRef(Opts.MainFileName));
372   Ctx.setDwarfVersion(Opts.DwarfVersion);
373 
374   // Build up the feature string from the target feature list.
375   std::string FS;
376   if (!Opts.Features.empty()) {
377     FS = Opts.Features[0];
378     for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
379       FS += "," + Opts.Features[i];
380   }
381 
382   std::unique_ptr<MCStreamer> Str;
383 
384   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
385   std::unique_ptr<MCSubtargetInfo> STI(
386       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
387 
388   raw_pwrite_stream *Out = FDOS.get();
389   std::unique_ptr<buffer_ostream> BOS;
390 
391   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
392   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
393     MCInstPrinter *IP = TheTarget->createMCInstPrinter(
394         llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
395     MCCodeEmitter *CE = nullptr;
396     MCAsmBackend *MAB = nullptr;
397     if (Opts.ShowEncoding) {
398       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
399       MCTargetOptions Options;
400       MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple, Opts.CPU, Options);
401     }
402     auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
403     Str.reset(TheTarget->createAsmStreamer(
404         Ctx, std::move(FOut), /*asmverbose*/ true,
405         /*useDwarfDirectory*/ true, IP, CE, MAB, Opts.ShowInst));
406   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
407     Str.reset(createNullStreamer(Ctx));
408   } else {
409     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
410            "Invalid file type!");
411     if (!FDOS->supportsSeeking()) {
412       BOS = make_unique<buffer_ostream>(*FDOS);
413       Out = BOS.get();
414     }
415 
416     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
417     MCTargetOptions Options;
418     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, Opts.Triple,
419                                                       Opts.CPU, Options);
420     Triple T(Opts.Triple);
421     Str.reset(TheTarget->createMCObjectStreamer(
422                 T, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *Out, std::unique_ptr<MCCodeEmitter>(CE), *STI,
423         Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
424         /*DWARFMustBeAtTheEnd*/ true));
425     Str.get()->InitSections(Opts.NoExecStack);
426   }
427 
428   bool Failed = false;
429 
430   std::unique_ptr<MCAsmParser> Parser(
431       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
432 
433   // FIXME: init MCTargetOptions from sanitizer flags here.
434   MCTargetOptions Options;
435   std::unique_ptr<MCTargetAsmParser> TAP(
436       TheTarget->createMCAsmParser(*STI, *Parser, *MCII, Options));
437   if (!TAP)
438     Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
439 
440   // Set values for symbols, if any.
441   for (auto &S : Opts.SymbolDefs) {
442     auto Pair = StringRef(S).split('=');
443     auto Sym = Pair.first;
444     auto Val = Pair.second;
445     int64_t Value;
446     // We have already error checked this in the driver.
447     Val.getAsInteger(0, Value);
448     Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
449   }
450 
451   if (!Failed) {
452     Parser->setTargetParser(*TAP.get());
453     Failed = Parser->Run(Opts.NoInitialTextSection);
454   }
455 
456   // Close Streamer first.
457   // It might have a reference to the output stream.
458   Str.reset();
459   // Close the output stream early.
460   BOS.reset();
461   FDOS.reset();
462 
463   // Delete output file if there were errors.
464   if (Failed && Opts.OutputPath != "-")
465     sys::fs::remove(Opts.OutputPath);
466 
467   return Failed;
468 }
469 
470 static void LLVMErrorHandler(void *UserData, const std::string &Message,
471                              bool GenCrashDiag) {
472   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
473 
474   Diags.Report(diag::err_fe_error_backend) << Message;
475 
476   // We cannot recover from llvm errors.
477   exit(1);
478 }
479 
480 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
481   // Initialize targets and assembly printers/parsers.
482   InitializeAllTargetInfos();
483   InitializeAllTargetMCs();
484   InitializeAllAsmParsers();
485 
486   // Construct our diagnostic client.
487   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
488   TextDiagnosticPrinter *DiagClient
489     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
490   DiagClient->setPrefix("clang -cc1as");
491   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
492   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
493 
494   // Set an error handler, so that any LLVM backend diagnostics go through our
495   // error handler.
496   ScopedFatalErrorHandler FatalErrorHandler
497     (LLVMErrorHandler, static_cast<void*>(&Diags));
498 
499   // Parse the arguments.
500   AssemblerInvocation Asm;
501   if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
502     return 1;
503 
504   if (Asm.ShowHelp) {
505     std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
506     Opts->PrintHelp(llvm::outs(), "clang -cc1as", "Clang Integrated Assembler",
507                     /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
508                     /*ShowAllAliases=*/false);
509     return 0;
510   }
511 
512   // Honor -version.
513   //
514   // FIXME: Use a better -version message?
515   if (Asm.ShowVersion) {
516     llvm::cl::PrintVersionMessage();
517     return 0;
518   }
519 
520   // Honor -mllvm.
521   //
522   // FIXME: Remove this, one day.
523   if (!Asm.LLVMArgs.empty()) {
524     unsigned NumArgs = Asm.LLVMArgs.size();
525     auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
526     Args[0] = "clang (LLVM option parsing)";
527     for (unsigned i = 0; i != NumArgs; ++i)
528       Args[i + 1] = Asm.LLVMArgs[i].c_str();
529     Args[NumArgs + 1] = nullptr;
530     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
531   }
532 
533   // Execute the invocation, unless there were parsing errors.
534   bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
535 
536   // If any timers were active but haven't been destroyed yet, print their
537   // results now.
538   TimerGroup::printAll(errs());
539 
540   return !!Failed;
541 }
542