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