xref: /freebsd/contrib/llvm-project/clang/tools/driver/cc1as_main.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 //===-- cc1as_main.cpp - Clang Assembler  ---------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the entry point to the clang -cc1as functionality, which implements
10 // the direct interface to the LLVM MC based assembler.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/DiagnosticOptions.h"
16 #include "clang/Driver/DriverDiagnostic.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Frontend/TextDiagnosticPrinter.h"
20 #include "clang/Frontend/Utils.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/MC/MCAsmBackend.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCCodeEmitter.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCObjectWriter.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/MCSectionMachO.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSubtargetInfo.h"
38 #include "llvm/MC/MCTargetOptions.h"
39 #include "llvm/Option/Arg.h"
40 #include "llvm/Option/ArgList.h"
41 #include "llvm/Option/OptTable.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/Process.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 clang::driver::options;
61 using namespace llvm;
62 using namespace llvm::opt;
63 
64 namespace {
65 
66 /// Helper class for representing a single invocation of the assembler.
67 struct AssemblerInvocation {
68   /// @name Target Options
69   /// @{
70 
71   /// The name of the target triple to assemble for.
72   std::string Triple;
73 
74   /// If given, the name of the target CPU to determine which instructions
75   /// are legal.
76   std::string CPU;
77 
78   /// The list of target specific features to enable or disable -- this should
79   /// be a list of strings starting with '+' or '-'.
80   std::vector<std::string> Features;
81 
82   /// The list of symbol definitions.
83   std::vector<std::string> SymbolDefs;
84 
85   /// @}
86   /// @name Language Options
87   /// @{
88 
89   std::vector<std::string> IncludePaths;
90   unsigned NoInitialTextSection : 1;
91   unsigned SaveTemporaryLabels : 1;
92   unsigned GenDwarfForAssembly : 1;
93   unsigned RelaxELFRelocations : 1;
94   unsigned DwarfVersion;
95   std::string DwarfDebugFlags;
96   std::string DwarfDebugProducer;
97   std::string DebugCompilationDir;
98   std::map<const std::string, const std::string> DebugPrefixMap;
99   llvm::DebugCompressionType CompressDebugSections =
100       llvm::DebugCompressionType::None;
101   std::string MainFileName;
102   std::string SplitDwarfOutput;
103 
104   /// @}
105   /// @name Frontend Options
106   /// @{
107 
108   std::string InputFile;
109   std::vector<std::string> LLVMArgs;
110   std::string OutputPath;
111   enum FileType {
112     FT_Asm,  ///< Assembly (.s) output, transliterate mode.
113     FT_Null, ///< No output, for timing purposes.
114     FT_Obj   ///< Object file output.
115   };
116   FileType OutputType;
117   unsigned ShowHelp : 1;
118   unsigned ShowVersion : 1;
119 
120   /// @}
121   /// @name Transliterate Options
122   /// @{
123 
124   unsigned OutputAsmVariant;
125   unsigned ShowEncoding : 1;
126   unsigned ShowInst : 1;
127 
128   /// @}
129   /// @name Assembler Options
130   /// @{
131 
132   unsigned RelaxAll : 1;
133   unsigned NoExecStack : 1;
134   unsigned FatalWarnings : 1;
135   unsigned NoWarn : 1;
136   unsigned IncrementalLinkerCompatible : 1;
137   unsigned EmbedBitcode : 1;
138 
139   /// The name of the relocation model to use.
140   std::string RelocationModel;
141 
142   /// The ABI targeted by the backend. Specified using -target-abi. Empty
143   /// otherwise.
144   std::string TargetABI;
145 
146   /// @}
147 
148 public:
149   AssemblerInvocation() {
150     Triple = "";
151     NoInitialTextSection = 0;
152     InputFile = "-";
153     OutputPath = "-";
154     OutputType = FT_Asm;
155     OutputAsmVariant = 0;
156     ShowInst = 0;
157     ShowEncoding = 0;
158     RelaxAll = 0;
159     NoExecStack = 0;
160     FatalWarnings = 0;
161     NoWarn = 0;
162     IncrementalLinkerCompatible = 0;
163     DwarfVersion = 0;
164     EmbedBitcode = 0;
165   }
166 
167   static bool CreateFromArgs(AssemblerInvocation &Res,
168                              ArrayRef<const char *> Argv,
169                              DiagnosticsEngine &Diags);
170 };
171 
172 }
173 
174 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
175                                          ArrayRef<const char *> Argv,
176                                          DiagnosticsEngine &Diags) {
177   bool Success = true;
178 
179   // Parse the arguments.
180   const OptTable &OptTbl = getDriverOptTable();
181 
182   const unsigned IncludedFlagsBitmask = options::CC1AsOption;
183   unsigned MissingArgIndex, MissingArgCount;
184   InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount,
185                                        IncludedFlagsBitmask);
186 
187   // Check for missing argument error.
188   if (MissingArgCount) {
189     Diags.Report(diag::err_drv_missing_argument)
190         << Args.getArgString(MissingArgIndex) << MissingArgCount;
191     Success = false;
192   }
193 
194   // Issue errors on unknown arguments.
195   for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
196     auto ArgString = A->getAsString(Args);
197     std::string Nearest;
198     if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
199       Diags.Report(diag::err_drv_unknown_argument) << ArgString;
200     else
201       Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
202           << ArgString << Nearest;
203     Success = false;
204   }
205 
206   // Construct the invocation.
207 
208   // Target Options
209   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
210   Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));
211   Opts.Features = Args.getAllArgValues(OPT_target_feature);
212 
213   // Use the default target triple if unspecified.
214   if (Opts.Triple.empty())
215     Opts.Triple = llvm::sys::getDefaultTargetTriple();
216 
217   // Language Options
218   Opts.IncludePaths = Args.getAllArgValues(OPT_I);
219   Opts.NoInitialTextSection = Args.hasArg(OPT_n);
220   Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
221   // Any DebugInfoKind implies GenDwarfForAssembly.
222   Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
223 
224   if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
225                                      OPT_compress_debug_sections_EQ)) {
226     if (A->getOption().getID() == OPT_compress_debug_sections) {
227       // TODO: be more clever about the compression type auto-detection
228       Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
229     } else {
230       Opts.CompressDebugSections =
231           llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
232               .Case("none", llvm::DebugCompressionType::None)
233               .Case("zlib", llvm::DebugCompressionType::Z)
234               .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
235               .Default(llvm::DebugCompressionType::None);
236     }
237   }
238 
239   Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
240   Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
241   Opts.DwarfDebugFlags =
242       std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
243   Opts.DwarfDebugProducer =
244       std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));
245   Opts.DebugCompilationDir =
246       std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir));
247   Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
248 
249   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
250     auto Split = StringRef(Arg).split('=');
251     Opts.DebugPrefixMap.insert(
252         {std::string(Split.first), std::string(Split.second)});
253   }
254 
255   // Frontend Options
256   if (Args.hasArg(OPT_INPUT)) {
257     bool First = true;
258     for (const Arg *A : Args.filtered(OPT_INPUT)) {
259       if (First) {
260         Opts.InputFile = A->getValue();
261         First = false;
262       } else {
263         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
264         Success = false;
265       }
266     }
267   }
268   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
269   Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));
270   Opts.SplitDwarfOutput =
271       std::string(Args.getLastArgValue(OPT_split_dwarf_output));
272   if (Arg *A = Args.getLastArg(OPT_filetype)) {
273     StringRef Name = A->getValue();
274     unsigned OutputType = StringSwitch<unsigned>(Name)
275       .Case("asm", FT_Asm)
276       .Case("null", FT_Null)
277       .Case("obj", FT_Obj)
278       .Default(~0U);
279     if (OutputType == ~0U) {
280       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
281       Success = false;
282     } else
283       Opts.OutputType = FileType(OutputType);
284   }
285   Opts.ShowHelp = Args.hasArg(OPT_help);
286   Opts.ShowVersion = Args.hasArg(OPT_version);
287 
288   // Transliterate Options
289   Opts.OutputAsmVariant =
290       getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
291   Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
292   Opts.ShowInst = Args.hasArg(OPT_show_inst);
293 
294   // Assemble Options
295   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
296   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
297   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
298   Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
299   Opts.RelocationModel =
300       std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));
301   Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));
302   Opts.IncrementalLinkerCompatible =
303       Args.hasArg(OPT_mincremental_linker_compatible);
304   Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
305 
306   // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
307   // EmbedBitcode behaves the same for all embed options for assembly files.
308   if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
309     Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
310                             .Case("all", 1)
311                             .Case("bitcode", 1)
312                             .Case("marker", 1)
313                             .Default(0);
314   }
315 
316   return Success;
317 }
318 
319 static std::unique_ptr<raw_fd_ostream>
320 getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
321   // Make sure that the Out file gets unlinked from the disk if we get a
322   // SIGINT.
323   if (Path != "-")
324     sys::RemoveFileOnSignal(Path);
325 
326   std::error_code EC;
327   auto Out = std::make_unique<raw_fd_ostream>(
328       Path, EC, (Binary ? sys::fs::OF_None : sys::fs::OF_Text));
329   if (EC) {
330     Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
331     return nullptr;
332   }
333 
334   return Out;
335 }
336 
337 static bool ExecuteAssembler(AssemblerInvocation &Opts,
338                              DiagnosticsEngine &Diags) {
339   // Get the target specific parser.
340   std::string Error;
341   const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
342   if (!TheTarget)
343     return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
344 
345   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
346       MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
347 
348   if (std::error_code EC = Buffer.getError()) {
349     Error = EC.message();
350     return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
351   }
352 
353   SourceMgr SrcMgr;
354 
355   // Tell SrcMgr about this buffer, which is what the parser will pick up.
356   unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
357 
358   // Record the location of the include directories so that the lexer can find
359   // it later.
360   SrcMgr.setIncludeDirs(Opts.IncludePaths);
361 
362   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
363   assert(MRI && "Unable to create target register info!");
364 
365   MCTargetOptions MCOptions;
366   std::unique_ptr<MCAsmInfo> MAI(
367       TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
368   assert(MAI && "Unable to create target asm info!");
369 
370   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
371   // may be created with a combination of default and explicit settings.
372   MAI->setCompressDebugSections(Opts.CompressDebugSections);
373 
374   MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
375 
376   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
377   if (Opts.OutputPath.empty())
378     Opts.OutputPath = "-";
379   std::unique_ptr<raw_fd_ostream> FDOS =
380       getOutputStream(Opts.OutputPath, Diags, IsBinary);
381   if (!FDOS)
382     return true;
383   std::unique_ptr<raw_fd_ostream> DwoOS;
384   if (!Opts.SplitDwarfOutput.empty())
385     DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
386 
387   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
388   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
389   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
390 
391   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr, &MCOptions);
392 
393   bool PIC = false;
394   if (Opts.RelocationModel == "static") {
395     PIC = false;
396   } else if (Opts.RelocationModel == "pic") {
397     PIC = true;
398   } else {
399     assert(Opts.RelocationModel == "dynamic-no-pic" &&
400            "Invalid PIC model!");
401     PIC = false;
402   }
403 
404   MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
405   if (Opts.SaveTemporaryLabels)
406     Ctx.setAllowTemporaryLabels(false);
407   if (Opts.GenDwarfForAssembly)
408     Ctx.setGenDwarfForAssembly(true);
409   if (!Opts.DwarfDebugFlags.empty())
410     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
411   if (!Opts.DwarfDebugProducer.empty())
412     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
413   if (!Opts.DebugCompilationDir.empty())
414     Ctx.setCompilationDir(Opts.DebugCompilationDir);
415   else {
416     // If no compilation dir is set, try to use the current directory.
417     SmallString<128> CWD;
418     if (!sys::fs::current_path(CWD))
419       Ctx.setCompilationDir(CWD);
420   }
421   if (!Opts.DebugPrefixMap.empty())
422     for (const auto &KV : Opts.DebugPrefixMap)
423       Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
424   if (!Opts.MainFileName.empty())
425     Ctx.setMainFileName(StringRef(Opts.MainFileName));
426   Ctx.setDwarfVersion(Opts.DwarfVersion);
427   if (Opts.GenDwarfForAssembly)
428     Ctx.setGenDwarfRootFile(Opts.InputFile,
429                             SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
430 
431   // Build up the feature string from the target feature list.
432   std::string FS = llvm::join(Opts.Features, ",");
433 
434   std::unique_ptr<MCStreamer> Str;
435 
436   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
437   std::unique_ptr<MCSubtargetInfo> STI(
438       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
439 
440   raw_pwrite_stream *Out = FDOS.get();
441   std::unique_ptr<buffer_ostream> BOS;
442 
443   MCOptions.MCNoWarn = Opts.NoWarn;
444   MCOptions.MCFatalWarnings = Opts.FatalWarnings;
445   MCOptions.ABIName = Opts.TargetABI;
446 
447   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
448   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
449     MCInstPrinter *IP = TheTarget->createMCInstPrinter(
450         llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
451 
452     std::unique_ptr<MCCodeEmitter> CE;
453     if (Opts.ShowEncoding)
454       CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
455     std::unique_ptr<MCAsmBackend> MAB(
456         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
457 
458     auto FOut = std::make_unique<formatted_raw_ostream>(*Out);
459     Str.reset(TheTarget->createAsmStreamer(
460         Ctx, std::move(FOut), /*asmverbose*/ true,
461         /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
462         Opts.ShowInst));
463   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
464     Str.reset(createNullStreamer(Ctx));
465   } else {
466     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
467            "Invalid file type!");
468     if (!FDOS->supportsSeeking()) {
469       BOS = std::make_unique<buffer_ostream>(*FDOS);
470       Out = BOS.get();
471     }
472 
473     std::unique_ptr<MCCodeEmitter> CE(
474         TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
475     std::unique_ptr<MCAsmBackend> MAB(
476         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
477     std::unique_ptr<MCObjectWriter> OW =
478         DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
479               : MAB->createObjectWriter(*Out);
480 
481     Triple T(Opts.Triple);
482     Str.reset(TheTarget->createMCObjectStreamer(
483         T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
484         Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
485         /*DWARFMustBeAtTheEnd*/ true));
486     Str.get()->InitSections(Opts.NoExecStack);
487   }
488 
489   // When -fembed-bitcode is passed to clang_as, a 1-byte marker
490   // is emitted in __LLVM,__asm section if the object file is MachO format.
491   if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
492                                MCObjectFileInfo::IsMachO) {
493     MCSection *AsmLabel = Ctx.getMachOSection(
494         "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
495     Str.get()->SwitchSection(AsmLabel);
496     Str.get()->emitZeros(1);
497   }
498 
499   // Assembly to object compilation should leverage assembly info.
500   Str->setUseAssemblerInfoForParsing(true);
501 
502   bool Failed = false;
503 
504   std::unique_ptr<MCAsmParser> Parser(
505       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
506 
507   // FIXME: init MCTargetOptions from sanitizer flags here.
508   std::unique_ptr<MCTargetAsmParser> TAP(
509       TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
510   if (!TAP)
511     Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
512 
513   // Set values for symbols, if any.
514   for (auto &S : Opts.SymbolDefs) {
515     auto Pair = StringRef(S).split('=');
516     auto Sym = Pair.first;
517     auto Val = Pair.second;
518     int64_t Value;
519     // We have already error checked this in the driver.
520     Val.getAsInteger(0, Value);
521     Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
522   }
523 
524   if (!Failed) {
525     Parser->setTargetParser(*TAP.get());
526     Failed = Parser->Run(Opts.NoInitialTextSection);
527   }
528 
529   // Close Streamer first.
530   // It might have a reference to the output stream.
531   Str.reset();
532   // Close the output stream early.
533   BOS.reset();
534   FDOS.reset();
535 
536   // Delete output file if there were errors.
537   if (Failed) {
538     if (Opts.OutputPath != "-")
539       sys::fs::remove(Opts.OutputPath);
540     if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")
541       sys::fs::remove(Opts.SplitDwarfOutput);
542   }
543 
544   return Failed;
545 }
546 
547 static void LLVMErrorHandler(void *UserData, const std::string &Message,
548                              bool GenCrashDiag) {
549   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
550 
551   Diags.Report(diag::err_fe_error_backend) << Message;
552 
553   // We cannot recover from llvm errors.
554   sys::Process::Exit(1);
555 }
556 
557 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
558   // Initialize targets and assembly printers/parsers.
559   InitializeAllTargetInfos();
560   InitializeAllTargetMCs();
561   InitializeAllAsmParsers();
562 
563   // Construct our diagnostic client.
564   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
565   TextDiagnosticPrinter *DiagClient
566     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
567   DiagClient->setPrefix("clang -cc1as");
568   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
569   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
570 
571   // Set an error handler, so that any LLVM backend diagnostics go through our
572   // error handler.
573   ScopedFatalErrorHandler FatalErrorHandler
574     (LLVMErrorHandler, static_cast<void*>(&Diags));
575 
576   // Parse the arguments.
577   AssemblerInvocation Asm;
578   if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
579     return 1;
580 
581   if (Asm.ShowHelp) {
582     getDriverOptTable().PrintHelp(
583         llvm::outs(), "clang -cc1as [options] file...",
584         "Clang Integrated Assembler",
585         /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
586         /*ShowAllAliases=*/false);
587     return 0;
588   }
589 
590   // Honor -version.
591   //
592   // FIXME: Use a better -version message?
593   if (Asm.ShowVersion) {
594     llvm::cl::PrintVersionMessage();
595     return 0;
596   }
597 
598   // Honor -mllvm.
599   //
600   // FIXME: Remove this, one day.
601   if (!Asm.LLVMArgs.empty()) {
602     unsigned NumArgs = Asm.LLVMArgs.size();
603     auto Args = std::make_unique<const char*[]>(NumArgs + 2);
604     Args[0] = "clang (LLVM option parsing)";
605     for (unsigned i = 0; i != NumArgs; ++i)
606       Args[i + 1] = Asm.LLVMArgs[i].c_str();
607     Args[NumArgs + 1] = nullptr;
608     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
609   }
610 
611   // Execute the invocation, unless there were parsing errors.
612   bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
613 
614   // If any timers were active but haven't been destroyed yet, print their
615   // results now.
616   TimerGroup::printAll(errs());
617   TimerGroup::clearAll();
618 
619   return !!Failed;
620 }
621