xref: /freebsd/contrib/llvm-project/clang/tools/driver/cc1as_main.cpp (revision 19261079b74319502c6ffa1249920079f0f69a72)
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_EQ)) {
225     Opts.CompressDebugSections =
226         llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
227             .Case("none", llvm::DebugCompressionType::None)
228             .Case("zlib", llvm::DebugCompressionType::Z)
229             .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
230             .Default(llvm::DebugCompressionType::None);
231   }
232 
233   Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
234   Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
235   Opts.DwarfDebugFlags =
236       std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));
237   Opts.DwarfDebugProducer =
238       std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));
239   Opts.DebugCompilationDir =
240       std::string(Args.getLastArgValue(OPT_fdebug_compilation_dir));
241   Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));
242 
243   for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
244     auto Split = StringRef(Arg).split('=');
245     Opts.DebugPrefixMap.insert(
246         {std::string(Split.first), std::string(Split.second)});
247   }
248 
249   // Frontend Options
250   if (Args.hasArg(OPT_INPUT)) {
251     bool First = true;
252     for (const Arg *A : Args.filtered(OPT_INPUT)) {
253       if (First) {
254         Opts.InputFile = A->getValue();
255         First = false;
256       } else {
257         Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
258         Success = false;
259       }
260     }
261   }
262   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
263   Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));
264   Opts.SplitDwarfOutput =
265       std::string(Args.getLastArgValue(OPT_split_dwarf_output));
266   if (Arg *A = Args.getLastArg(OPT_filetype)) {
267     StringRef Name = A->getValue();
268     unsigned OutputType = StringSwitch<unsigned>(Name)
269       .Case("asm", FT_Asm)
270       .Case("null", FT_Null)
271       .Case("obj", FT_Obj)
272       .Default(~0U);
273     if (OutputType == ~0U) {
274       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
275       Success = false;
276     } else
277       Opts.OutputType = FileType(OutputType);
278   }
279   Opts.ShowHelp = Args.hasArg(OPT_help);
280   Opts.ShowVersion = Args.hasArg(OPT_version);
281 
282   // Transliterate Options
283   Opts.OutputAsmVariant =
284       getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
285   Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
286   Opts.ShowInst = Args.hasArg(OPT_show_inst);
287 
288   // Assemble Options
289   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
290   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
291   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
292   Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
293   Opts.RelocationModel =
294       std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));
295   Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));
296   Opts.IncrementalLinkerCompatible =
297       Args.hasArg(OPT_mincremental_linker_compatible);
298   Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
299 
300   // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
301   // EmbedBitcode behaves the same for all embed options for assembly files.
302   if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
303     Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
304                             .Case("all", 1)
305                             .Case("bitcode", 1)
306                             .Case("marker", 1)
307                             .Default(0);
308   }
309 
310   return Success;
311 }
312 
313 static std::unique_ptr<raw_fd_ostream>
314 getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
315   // Make sure that the Out file gets unlinked from the disk if we get a
316   // SIGINT.
317   if (Path != "-")
318     sys::RemoveFileOnSignal(Path);
319 
320   std::error_code EC;
321   auto Out = std::make_unique<raw_fd_ostream>(
322       Path, EC, (Binary ? sys::fs::OF_None : sys::fs::OF_Text));
323   if (EC) {
324     Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
325     return nullptr;
326   }
327 
328   return Out;
329 }
330 
331 static bool ExecuteAssembler(AssemblerInvocation &Opts,
332                              DiagnosticsEngine &Diags) {
333   // Get the target specific parser.
334   std::string Error;
335   const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
336   if (!TheTarget)
337     return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
338 
339   ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
340       MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
341 
342   if (std::error_code EC = Buffer.getError()) {
343     Error = EC.message();
344     return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
345   }
346 
347   SourceMgr SrcMgr;
348 
349   // Tell SrcMgr about this buffer, which is what the parser will pick up.
350   unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
351 
352   // Record the location of the include directories so that the lexer can find
353   // it later.
354   SrcMgr.setIncludeDirs(Opts.IncludePaths);
355 
356   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
357   assert(MRI && "Unable to create target register info!");
358 
359   MCTargetOptions MCOptions;
360   std::unique_ptr<MCAsmInfo> MAI(
361       TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
362   assert(MAI && "Unable to create target asm info!");
363 
364   // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
365   // may be created with a combination of default and explicit settings.
366   MAI->setCompressDebugSections(Opts.CompressDebugSections);
367 
368   MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
369 
370   bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
371   if (Opts.OutputPath.empty())
372     Opts.OutputPath = "-";
373   std::unique_ptr<raw_fd_ostream> FDOS =
374       getOutputStream(Opts.OutputPath, Diags, IsBinary);
375   if (!FDOS)
376     return true;
377   std::unique_ptr<raw_fd_ostream> DwoOS;
378   if (!Opts.SplitDwarfOutput.empty())
379     DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
380 
381   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
382   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
383   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
384 
385   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr, &MCOptions);
386 
387   bool PIC = false;
388   if (Opts.RelocationModel == "static") {
389     PIC = false;
390   } else if (Opts.RelocationModel == "pic") {
391     PIC = true;
392   } else {
393     assert(Opts.RelocationModel == "dynamic-no-pic" &&
394            "Invalid PIC model!");
395     PIC = false;
396   }
397 
398   MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
399   if (Opts.SaveTemporaryLabels)
400     Ctx.setAllowTemporaryLabels(false);
401   if (Opts.GenDwarfForAssembly)
402     Ctx.setGenDwarfForAssembly(true);
403   if (!Opts.DwarfDebugFlags.empty())
404     Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
405   if (!Opts.DwarfDebugProducer.empty())
406     Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
407   if (!Opts.DebugCompilationDir.empty())
408     Ctx.setCompilationDir(Opts.DebugCompilationDir);
409   else {
410     // If no compilation dir is set, try to use the current directory.
411     SmallString<128> CWD;
412     if (!sys::fs::current_path(CWD))
413       Ctx.setCompilationDir(CWD);
414   }
415   if (!Opts.DebugPrefixMap.empty())
416     for (const auto &KV : Opts.DebugPrefixMap)
417       Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
418   if (!Opts.MainFileName.empty())
419     Ctx.setMainFileName(StringRef(Opts.MainFileName));
420   Ctx.setDwarfVersion(Opts.DwarfVersion);
421   if (Opts.GenDwarfForAssembly)
422     Ctx.setGenDwarfRootFile(Opts.InputFile,
423                             SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
424 
425   // Build up the feature string from the target feature list.
426   std::string FS = llvm::join(Opts.Features, ",");
427 
428   std::unique_ptr<MCStreamer> Str;
429 
430   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
431   assert(MCII && "Unable to create instruction info!");
432 
433   std::unique_ptr<MCSubtargetInfo> STI(
434       TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
435   assert(STI && "Unable to create subtarget info!");
436 
437   raw_pwrite_stream *Out = FDOS.get();
438   std::unique_ptr<buffer_ostream> BOS;
439 
440   MCOptions.MCNoWarn = Opts.NoWarn;
441   MCOptions.MCFatalWarnings = Opts.FatalWarnings;
442   MCOptions.ABIName = Opts.TargetABI;
443 
444   // FIXME: There is a bit of code duplication with addPassesToEmitFile.
445   if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
446     MCInstPrinter *IP = TheTarget->createMCInstPrinter(
447         llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
448 
449     std::unique_ptr<MCCodeEmitter> CE;
450     if (Opts.ShowEncoding)
451       CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
452     std::unique_ptr<MCAsmBackend> MAB(
453         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
454 
455     auto FOut = std::make_unique<formatted_raw_ostream>(*Out);
456     Str.reset(TheTarget->createAsmStreamer(
457         Ctx, std::move(FOut), /*asmverbose*/ true,
458         /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
459         Opts.ShowInst));
460   } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
461     Str.reset(createNullStreamer(Ctx));
462   } else {
463     assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
464            "Invalid file type!");
465     if (!FDOS->supportsSeeking()) {
466       BOS = std::make_unique<buffer_ostream>(*FDOS);
467       Out = BOS.get();
468     }
469 
470     std::unique_ptr<MCCodeEmitter> CE(
471         TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
472     std::unique_ptr<MCAsmBackend> MAB(
473         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
474     assert(MAB && "Unable to create asm backend!");
475 
476     std::unique_ptr<MCObjectWriter> OW =
477         DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
478               : MAB->createObjectWriter(*Out);
479 
480     Triple T(Opts.Triple);
481     Str.reset(TheTarget->createMCObjectStreamer(
482         T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
483         Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
484         /*DWARFMustBeAtTheEnd*/ true));
485     Str.get()->InitSections(Opts.NoExecStack);
486   }
487 
488   // When -fembed-bitcode is passed to clang_as, a 1-byte marker
489   // is emitted in __LLVM,__asm section if the object file is MachO format.
490   if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
491                                MCObjectFileInfo::IsMachO) {
492     MCSection *AsmLabel = Ctx.getMachOSection(
493         "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
494     Str.get()->SwitchSection(AsmLabel);
495     Str.get()->emitZeros(1);
496   }
497 
498   // Assembly to object compilation should leverage assembly info.
499   Str->setUseAssemblerInfoForParsing(true);
500 
501   bool Failed = false;
502 
503   std::unique_ptr<MCAsmParser> Parser(
504       createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
505 
506   // FIXME: init MCTargetOptions from sanitizer flags here.
507   std::unique_ptr<MCTargetAsmParser> TAP(
508       TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
509   if (!TAP)
510     Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
511 
512   // Set values for symbols, if any.
513   for (auto &S : Opts.SymbolDefs) {
514     auto Pair = StringRef(S).split('=');
515     auto Sym = Pair.first;
516     auto Val = Pair.second;
517     int64_t Value;
518     // We have already error checked this in the driver.
519     Val.getAsInteger(0, Value);
520     Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
521   }
522 
523   if (!Failed) {
524     Parser->setTargetParser(*TAP.get());
525     Failed = Parser->Run(Opts.NoInitialTextSection);
526   }
527 
528   // Parser has a reference to the output stream (Str), so close Parser first.
529   Parser.reset();
530   Str.reset();
531   // Close the output stream early.
532   BOS.reset();
533   FDOS.reset();
534 
535   // Delete output file if there were errors.
536   if (Failed) {
537     if (Opts.OutputPath != "-")
538       sys::fs::remove(Opts.OutputPath);
539     if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")
540       sys::fs::remove(Opts.SplitDwarfOutput);
541   }
542 
543   return Failed;
544 }
545 
546 static void LLVMErrorHandler(void *UserData, const std::string &Message,
547                              bool GenCrashDiag) {
548   DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
549 
550   Diags.Report(diag::err_fe_error_backend) << Message;
551 
552   // We cannot recover from llvm errors.
553   sys::Process::Exit(1);
554 }
555 
556 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
557   // Initialize targets and assembly printers/parsers.
558   InitializeAllTargetInfos();
559   InitializeAllTargetMCs();
560   InitializeAllAsmParsers();
561 
562   // Construct our diagnostic client.
563   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
564   TextDiagnosticPrinter *DiagClient
565     = new TextDiagnosticPrinter(errs(), &*DiagOpts);
566   DiagClient->setPrefix("clang -cc1as");
567   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
568   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
569 
570   // Set an error handler, so that any LLVM backend diagnostics go through our
571   // error handler.
572   ScopedFatalErrorHandler FatalErrorHandler
573     (LLVMErrorHandler, static_cast<void*>(&Diags));
574 
575   // Parse the arguments.
576   AssemblerInvocation Asm;
577   if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
578     return 1;
579 
580   if (Asm.ShowHelp) {
581     getDriverOptTable().PrintHelp(
582         llvm::outs(), "clang -cc1as [options] file...",
583         "Clang Integrated Assembler",
584         /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
585         /*ShowAllAliases=*/false);
586     return 0;
587   }
588 
589   // Honor -version.
590   //
591   // FIXME: Use a better -version message?
592   if (Asm.ShowVersion) {
593     llvm::cl::PrintVersionMessage();
594     return 0;
595   }
596 
597   // Honor -mllvm.
598   //
599   // FIXME: Remove this, one day.
600   if (!Asm.LLVMArgs.empty()) {
601     unsigned NumArgs = Asm.LLVMArgs.size();
602     auto Args = std::make_unique<const char*[]>(NumArgs + 2);
603     Args[0] = "clang (LLVM option parsing)";
604     for (unsigned i = 0; i != NumArgs; ++i)
605       Args[i + 1] = Asm.LLVMArgs[i].c_str();
606     Args[NumArgs + 1] = nullptr;
607     llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
608   }
609 
610   // Execute the invocation, unless there were parsing errors.
611   bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
612 
613   // If any timers were active but haven't been destroyed yet, print their
614   // results now.
615   TimerGroup::printAll(errs());
616   TimerGroup::clearAll();
617 
618   return !!Failed;
619 }
620