1 //===-- cc1as_main.cpp - Clang Assembler ---------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This is the entry point to the clang -cc1as functionality, which implements
10 // the direct interface to the LLVM MC based assembler.
12 //===----------------------------------------------------------------------===//
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"
57 #include <system_error>
58 using namespace clang;
59 using namespace clang::driver;
60 using namespace clang::driver::options;
62 using namespace llvm::opt;
66 /// Helper class for representing a single invocation of the assembler.
67 struct AssemblerInvocation {
68 /// @name Target Options
71 /// The name of the target triple to assemble for.
74 /// If given, the name of the target CPU to determine which instructions
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;
82 /// The list of symbol definitions.
83 std::vector<std::string> SymbolDefs;
86 /// @name Language Options
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;
105 /// @name Frontend Options
108 std::string InputFile;
109 std::vector<std::string> LLVMArgs;
110 std::string OutputPath;
112 FT_Asm, ///< Assembly (.s) output, transliterate mode.
113 FT_Null, ///< No output, for timing purposes.
114 FT_Obj ///< Object file output.
117 unsigned ShowHelp : 1;
118 unsigned ShowVersion : 1;
121 /// @name Transliterate Options
124 unsigned OutputAsmVariant;
125 unsigned ShowEncoding : 1;
126 unsigned ShowInst : 1;
129 /// @name Assembler Options
132 unsigned RelaxAll : 1;
133 unsigned NoExecStack : 1;
134 unsigned FatalWarnings : 1;
136 unsigned IncrementalLinkerCompatible : 1;
137 unsigned EmbedBitcode : 1;
139 /// The name of the relocation model to use.
140 std::string RelocationModel;
142 /// The ABI targeted by the backend. Specified using -target-abi. Empty
144 std::string TargetABI;
149 AssemblerInvocation() {
151 NoInitialTextSection = 0;
155 OutputAsmVariant = 0;
162 IncrementalLinkerCompatible = 0;
167 static bool CreateFromArgs(AssemblerInvocation &Res,
168 ArrayRef<const char *> Argv,
169 DiagnosticsEngine &Diags);
174 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
175 ArrayRef<const char *> Argv,
176 DiagnosticsEngine &Diags) {
179 // Parse the arguments.
180 const OptTable &OptTbl = getDriverOptTable();
182 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
183 unsigned MissingArgIndex, MissingArgCount;
184 InputArgList Args = OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount,
185 IncludedFlagsBitmask);
187 // Check for missing argument error.
188 if (MissingArgCount) {
189 Diags.Report(diag::err_drv_missing_argument)
190 << Args.getArgString(MissingArgIndex) << MissingArgCount;
194 // Issue errors on unknown arguments.
195 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
196 auto ArgString = A->getAsString(Args);
198 if (OptTbl.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
199 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
201 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
202 << ArgString << Nearest;
206 // Construct the invocation.
209 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
210 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
211 Opts.Features = Args.getAllArgValues(OPT_target_feature);
213 // Use the default target triple if unspecified.
214 if (Opts.Triple.empty())
215 Opts.Triple = llvm::sys::getDefaultTargetTriple();
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);
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;
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);
239 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
240 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
241 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
242 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
243 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
244 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
246 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
247 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
250 if (Args.hasArg(OPT_INPUT)) {
252 for (const Arg *A : Args.filtered(OPT_INPUT)) {
254 Opts.InputFile = A->getValue();
257 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
262 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
263 Opts.OutputPath = Args.getLastArgValue(OPT_o);
264 Opts.SplitDwarfOutput = Args.getLastArgValue(OPT_split_dwarf_output);
265 if (Arg *A = Args.getLastArg(OPT_filetype)) {
266 StringRef Name = A->getValue();
267 unsigned OutputType = StringSwitch<unsigned>(Name)
269 .Case("null", FT_Null)
272 if (OutputType == ~0U) {
273 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
276 Opts.OutputType = FileType(OutputType);
278 Opts.ShowHelp = Args.hasArg(OPT_help);
279 Opts.ShowVersion = Args.hasArg(OPT_version);
281 // Transliterate Options
282 Opts.OutputAsmVariant =
283 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
284 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
285 Opts.ShowInst = Args.hasArg(OPT_show_inst);
288 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
289 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
290 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
291 Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);
292 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
293 Opts.TargetABI = Args.getLastArgValue(OPT_target_abi);
294 Opts.IncrementalLinkerCompatible =
295 Args.hasArg(OPT_mincremental_linker_compatible);
296 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
298 // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
299 // EmbedBitcode behaves the same for all embed options for assembly files.
300 if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
301 Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
311 static std::unique_ptr<raw_fd_ostream>
312 getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
313 // Make sure that the Out file gets unlinked from the disk if we get a
316 sys::RemoveFileOnSignal(Path);
319 auto Out = std::make_unique<raw_fd_ostream>(
320 Path, EC, (Binary ? sys::fs::OF_None : sys::fs::OF_Text));
322 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
329 static bool ExecuteAssembler(AssemblerInvocation &Opts,
330 DiagnosticsEngine &Diags) {
331 // Get the target specific parser.
333 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
335 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
337 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
338 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
340 if (std::error_code EC = Buffer.getError()) {
341 Error = EC.message();
342 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
347 // Tell SrcMgr about this buffer, which is what the parser will pick up.
348 unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
350 // Record the location of the include directories so that the lexer can find
352 SrcMgr.setIncludeDirs(Opts.IncludePaths);
354 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
355 assert(MRI && "Unable to create target register info!");
357 MCTargetOptions MCOptions;
358 std::unique_ptr<MCAsmInfo> MAI(
359 TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));
360 assert(MAI && "Unable to create target asm info!");
362 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
363 // may be created with a combination of default and explicit settings.
364 MAI->setCompressDebugSections(Opts.CompressDebugSections);
366 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
368 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
369 if (Opts.OutputPath.empty())
370 Opts.OutputPath = "-";
371 std::unique_ptr<raw_fd_ostream> FDOS =
372 getOutputStream(Opts.OutputPath, Diags, IsBinary);
375 std::unique_ptr<raw_fd_ostream> DwoOS;
376 if (!Opts.SplitDwarfOutput.empty())
377 DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
379 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
380 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
381 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
383 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr, &MCOptions);
386 if (Opts.RelocationModel == "static") {
388 } else if (Opts.RelocationModel == "pic") {
391 assert(Opts.RelocationModel == "dynamic-no-pic" &&
392 "Invalid PIC model!");
396 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
397 if (Opts.SaveTemporaryLabels)
398 Ctx.setAllowTemporaryLabels(false);
399 if (Opts.GenDwarfForAssembly)
400 Ctx.setGenDwarfForAssembly(true);
401 if (!Opts.DwarfDebugFlags.empty())
402 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
403 if (!Opts.DwarfDebugProducer.empty())
404 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
405 if (!Opts.DebugCompilationDir.empty())
406 Ctx.setCompilationDir(Opts.DebugCompilationDir);
408 // If no compilation dir is set, try to use the current directory.
409 SmallString<128> CWD;
410 if (!sys::fs::current_path(CWD))
411 Ctx.setCompilationDir(CWD);
413 if (!Opts.DebugPrefixMap.empty())
414 for (const auto &KV : Opts.DebugPrefixMap)
415 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
416 if (!Opts.MainFileName.empty())
417 Ctx.setMainFileName(StringRef(Opts.MainFileName));
418 Ctx.setDwarfVersion(Opts.DwarfVersion);
419 if (Opts.GenDwarfForAssembly)
420 Ctx.setGenDwarfRootFile(Opts.InputFile,
421 SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
423 // Build up the feature string from the target feature list.
425 if (!Opts.Features.empty()) {
426 FS = Opts.Features[0];
427 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
428 FS += "," + Opts.Features[i];
431 std::unique_ptr<MCStreamer> Str;
433 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
434 std::unique_ptr<MCSubtargetInfo> STI(
435 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
437 raw_pwrite_stream *Out = FDOS.get();
438 std::unique_ptr<buffer_ostream> BOS;
440 MCOptions.MCNoWarn = Opts.NoWarn;
441 MCOptions.MCFatalWarnings = Opts.FatalWarnings;
442 MCOptions.ABIName = Opts.TargetABI;
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);
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));
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),
460 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
461 Str.reset(createNullStreamer(Ctx));
463 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
464 "Invalid file type!");
465 if (!FDOS->supportsSeeking()) {
466 BOS = std::make_unique<buffer_ostream>(*FDOS);
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 std::unique_ptr<MCObjectWriter> OW =
475 DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
476 : MAB->createObjectWriter(*Out);
478 Triple T(Opts.Triple);
479 Str.reset(TheTarget->createMCObjectStreamer(
480 T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
481 Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
482 /*DWARFMustBeAtTheEnd*/ true));
483 Str.get()->InitSections(Opts.NoExecStack);
486 // When -fembed-bitcode is passed to clang_as, a 1-byte marker
487 // is emitted in __LLVM,__asm section if the object file is MachO format.
488 if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
489 MCObjectFileInfo::IsMachO) {
490 MCSection *AsmLabel = Ctx.getMachOSection(
491 "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
492 Str.get()->SwitchSection(AsmLabel);
493 Str.get()->EmitZeros(1);
496 // Assembly to object compilation should leverage assembly info.
497 Str->setUseAssemblerInfoForParsing(true);
501 std::unique_ptr<MCAsmParser> Parser(
502 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
504 // FIXME: init MCTargetOptions from sanitizer flags here.
505 std::unique_ptr<MCTargetAsmParser> TAP(
506 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
508 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
510 // Set values for symbols, if any.
511 for (auto &S : Opts.SymbolDefs) {
512 auto Pair = StringRef(S).split('=');
513 auto Sym = Pair.first;
514 auto Val = Pair.second;
516 // We have already error checked this in the driver.
517 Val.getAsInteger(0, Value);
518 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
522 Parser->setTargetParser(*TAP.get());
523 Failed = Parser->Run(Opts.NoInitialTextSection);
526 // Close Streamer first.
527 // It might have a reference to the output stream.
529 // Close the output stream early.
533 // Delete output file if there were errors.
535 if (Opts.OutputPath != "-")
536 sys::fs::remove(Opts.OutputPath);
537 if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")
538 sys::fs::remove(Opts.SplitDwarfOutput);
544 static void LLVMErrorHandler(void *UserData, const std::string &Message,
546 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
548 Diags.Report(diag::err_fe_error_backend) << Message;
550 // We cannot recover from llvm errors.
551 sys::Process::Exit(1);
554 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
555 // Initialize targets and assembly printers/parsers.
556 InitializeAllTargetInfos();
557 InitializeAllTargetMCs();
558 InitializeAllAsmParsers();
560 // Construct our diagnostic client.
561 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
562 TextDiagnosticPrinter *DiagClient
563 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
564 DiagClient->setPrefix("clang -cc1as");
565 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
566 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
568 // Set an error handler, so that any LLVM backend diagnostics go through our
570 ScopedFatalErrorHandler FatalErrorHandler
571 (LLVMErrorHandler, static_cast<void*>(&Diags));
573 // Parse the arguments.
574 AssemblerInvocation Asm;
575 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
579 getDriverOptTable().PrintHelp(
580 llvm::outs(), "clang -cc1as [options] file...",
581 "Clang Integrated Assembler",
582 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
583 /*ShowAllAliases=*/false);
589 // FIXME: Use a better -version message?
590 if (Asm.ShowVersion) {
591 llvm::cl::PrintVersionMessage();
597 // FIXME: Remove this, one day.
598 if (!Asm.LLVMArgs.empty()) {
599 unsigned NumArgs = Asm.LLVMArgs.size();
600 auto Args = std::make_unique<const char*[]>(NumArgs + 2);
601 Args[0] = "clang (LLVM option parsing)";
602 for (unsigned i = 0; i != NumArgs; ++i)
603 Args[i + 1] = Asm.LLVMArgs[i].c_str();
604 Args[NumArgs + 1] = nullptr;
605 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
608 // Execute the invocation, unless there were parsing errors.
609 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
611 // If any timers were active but haven't been destroyed yet, print their
613 TimerGroup::printAll(errs());
614 TimerGroup::clearAll();