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/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"
56 #include <system_error>
57 using namespace clang;
58 using namespace clang::driver;
59 using namespace clang::driver::options;
61 using namespace llvm::opt;
65 /// Helper class for representing a single invocation of the assembler.
66 struct AssemblerInvocation {
67 /// @name Target Options
70 /// The name of the target triple to assemble for.
73 /// If given, the name of the target CPU to determine which instructions
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;
81 /// The list of symbol definitions.
82 std::vector<std::string> SymbolDefs;
85 /// @name Language Options
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;
104 /// @name Frontend Options
107 std::string InputFile;
108 std::vector<std::string> LLVMArgs;
109 std::string OutputPath;
111 FT_Asm, ///< Assembly (.s) output, transliterate mode.
112 FT_Null, ///< No output, for timing purposes.
113 FT_Obj ///< Object file output.
116 unsigned ShowHelp : 1;
117 unsigned ShowVersion : 1;
120 /// @name Transliterate Options
123 unsigned OutputAsmVariant;
124 unsigned ShowEncoding : 1;
125 unsigned ShowInst : 1;
128 /// @name Assembler Options
131 unsigned RelaxAll : 1;
132 unsigned NoExecStack : 1;
133 unsigned FatalWarnings : 1;
134 unsigned IncrementalLinkerCompatible : 1;
135 unsigned EmbedBitcode : 1;
137 /// The name of the relocation model to use.
138 std::string RelocationModel;
140 /// The ABI targeted by the backend. Specified using -target-abi. Empty
142 std::string TargetABI;
147 AssemblerInvocation() {
149 NoInitialTextSection = 0;
153 OutputAsmVariant = 0;
159 IncrementalLinkerCompatible = 0;
164 static bool CreateFromArgs(AssemblerInvocation &Res,
165 ArrayRef<const char *> Argv,
166 DiagnosticsEngine &Diags);
171 bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,
172 ArrayRef<const char *> Argv,
173 DiagnosticsEngine &Diags) {
176 // Parse the arguments.
177 std::unique_ptr<OptTable> OptTbl(createDriverOptTable());
179 const unsigned IncludedFlagsBitmask = options::CC1AsOption;
180 unsigned MissingArgIndex, MissingArgCount;
181 InputArgList Args = OptTbl->ParseArgs(Argv, MissingArgIndex, MissingArgCount,
182 IncludedFlagsBitmask);
184 // Check for missing argument error.
185 if (MissingArgCount) {
186 Diags.Report(diag::err_drv_missing_argument)
187 << Args.getArgString(MissingArgIndex) << MissingArgCount;
191 // Issue errors on unknown arguments.
192 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {
193 auto ArgString = A->getAsString(Args);
195 if (OptTbl->findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
196 Diags.Report(diag::err_drv_unknown_argument) << ArgString;
198 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
199 << ArgString << Nearest;
203 // Construct the invocation.
206 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
207 Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
208 Opts.Features = Args.getAllArgValues(OPT_target_feature);
210 // Use the default target triple if unspecified.
211 if (Opts.Triple.empty())
212 Opts.Triple = llvm::sys::getDefaultTargetTriple();
215 Opts.IncludePaths = Args.getAllArgValues(OPT_I);
216 Opts.NoInitialTextSection = Args.hasArg(OPT_n);
217 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);
218 // Any DebugInfoKind implies GenDwarfForAssembly.
219 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);
221 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections,
222 OPT_compress_debug_sections_EQ)) {
223 if (A->getOption().getID() == OPT_compress_debug_sections) {
224 // TODO: be more clever about the compression type auto-detection
225 Opts.CompressDebugSections = llvm::DebugCompressionType::GNU;
227 Opts.CompressDebugSections =
228 llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())
229 .Case("none", llvm::DebugCompressionType::None)
230 .Case("zlib", llvm::DebugCompressionType::Z)
231 .Case("zlib-gnu", llvm::DebugCompressionType::GNU)
232 .Default(llvm::DebugCompressionType::None);
236 Opts.RelaxELFRelocations = Args.hasArg(OPT_mrelax_relocations);
237 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);
238 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
239 Opts.DwarfDebugProducer = Args.getLastArgValue(OPT_dwarf_debug_producer);
240 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
241 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
243 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ))
244 Opts.DebugPrefixMap.insert(StringRef(Arg).split('='));
247 if (Args.hasArg(OPT_INPUT)) {
249 for (const Arg *A : Args.filtered(OPT_INPUT)) {
251 Opts.InputFile = A->getValue();
254 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);
259 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
260 Opts.OutputPath = Args.getLastArgValue(OPT_o);
261 Opts.SplitDwarfOutput = Args.getLastArgValue(OPT_split_dwarf_output);
262 if (Arg *A = Args.getLastArg(OPT_filetype)) {
263 StringRef Name = A->getValue();
264 unsigned OutputType = StringSwitch<unsigned>(Name)
266 .Case("null", FT_Null)
269 if (OutputType == ~0U) {
270 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
273 Opts.OutputType = FileType(OutputType);
275 Opts.ShowHelp = Args.hasArg(OPT_help);
276 Opts.ShowVersion = Args.hasArg(OPT_version);
278 // Transliterate Options
279 Opts.OutputAsmVariant =
280 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);
281 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);
282 Opts.ShowInst = Args.hasArg(OPT_show_inst);
285 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
286 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
287 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
288 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
289 Opts.TargetABI = Args.getLastArgValue(OPT_target_abi);
290 Opts.IncrementalLinkerCompatible =
291 Args.hasArg(OPT_mincremental_linker_compatible);
292 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);
294 // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.
295 // EmbedBitcode behaves the same for all embed options for assembly files.
296 if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {
297 Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())
307 static std::unique_ptr<raw_fd_ostream>
308 getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {
309 // Make sure that the Out file gets unlinked from the disk if we get a
312 sys::RemoveFileOnSignal(Path);
315 auto Out = llvm::make_unique<raw_fd_ostream>(
316 Path, EC, (Binary ? sys::fs::F_None : sys::fs::F_Text));
318 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();
325 static bool ExecuteAssembler(AssemblerInvocation &Opts,
326 DiagnosticsEngine &Diags) {
327 // Get the target specific parser.
329 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);
331 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
333 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =
334 MemoryBuffer::getFileOrSTDIN(Opts.InputFile);
336 if (std::error_code EC = Buffer.getError()) {
337 Error = EC.message();
338 return Diags.Report(diag::err_fe_error_reading) << Opts.InputFile;
343 // Tell SrcMgr about this buffer, which is what the parser will pick up.
344 unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());
346 // Record the location of the include directories so that the lexer can find
348 SrcMgr.setIncludeDirs(Opts.IncludePaths);
350 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));
351 assert(MRI && "Unable to create target register info!");
353 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, Opts.Triple));
354 assert(MAI && "Unable to create target asm info!");
356 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections
357 // may be created with a combination of default and explicit settings.
358 MAI->setCompressDebugSections(Opts.CompressDebugSections);
360 MAI->setRelaxELFRelocations(Opts.RelaxELFRelocations);
362 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;
363 if (Opts.OutputPath.empty())
364 Opts.OutputPath = "-";
365 std::unique_ptr<raw_fd_ostream> FDOS =
366 getOutputStream(Opts.OutputPath, Diags, IsBinary);
369 std::unique_ptr<raw_fd_ostream> DwoOS;
370 if (!Opts.SplitDwarfOutput.empty())
371 DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);
373 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
374 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
375 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
377 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
380 if (Opts.RelocationModel == "static") {
382 } else if (Opts.RelocationModel == "pic") {
385 assert(Opts.RelocationModel == "dynamic-no-pic" &&
386 "Invalid PIC model!");
390 MOFI->InitMCObjectFileInfo(Triple(Opts.Triple), PIC, Ctx);
391 if (Opts.SaveTemporaryLabels)
392 Ctx.setAllowTemporaryLabels(false);
393 if (Opts.GenDwarfForAssembly)
394 Ctx.setGenDwarfForAssembly(true);
395 if (!Opts.DwarfDebugFlags.empty())
396 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));
397 if (!Opts.DwarfDebugProducer.empty())
398 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));
399 if (!Opts.DebugCompilationDir.empty())
400 Ctx.setCompilationDir(Opts.DebugCompilationDir);
402 // If no compilation dir is set, try to use the current directory.
403 SmallString<128> CWD;
404 if (!sys::fs::current_path(CWD))
405 Ctx.setCompilationDir(CWD);
407 if (!Opts.DebugPrefixMap.empty())
408 for (const auto &KV : Opts.DebugPrefixMap)
409 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
410 if (!Opts.MainFileName.empty())
411 Ctx.setMainFileName(StringRef(Opts.MainFileName));
412 Ctx.setDwarfVersion(Opts.DwarfVersion);
413 if (Opts.GenDwarfForAssembly)
414 Ctx.setGenDwarfRootFile(Opts.InputFile,
415 SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());
417 // Build up the feature string from the target feature list.
419 if (!Opts.Features.empty()) {
420 FS = Opts.Features[0];
421 for (unsigned i = 1, e = Opts.Features.size(); i != e; ++i)
422 FS += "," + Opts.Features[i];
425 std::unique_ptr<MCStreamer> Str;
427 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
428 std::unique_ptr<MCSubtargetInfo> STI(
429 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));
431 raw_pwrite_stream *Out = FDOS.get();
432 std::unique_ptr<buffer_ostream> BOS;
434 MCTargetOptions MCOptions;
435 MCOptions.ABIName = Opts.TargetABI;
437 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
438 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {
439 MCInstPrinter *IP = TheTarget->createMCInstPrinter(
440 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI);
442 std::unique_ptr<MCCodeEmitter> CE;
443 if (Opts.ShowEncoding)
444 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
445 std::unique_ptr<MCAsmBackend> MAB(
446 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
448 auto FOut = llvm::make_unique<formatted_raw_ostream>(*Out);
449 Str.reset(TheTarget->createAsmStreamer(
450 Ctx, std::move(FOut), /*asmverbose*/ true,
451 /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
453 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {
454 Str.reset(createNullStreamer(Ctx));
456 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&
457 "Invalid file type!");
458 if (!FDOS->supportsSeeking()) {
459 BOS = make_unique<buffer_ostream>(*FDOS);
463 std::unique_ptr<MCCodeEmitter> CE(
464 TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
465 std::unique_ptr<MCAsmBackend> MAB(
466 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
467 std::unique_ptr<MCObjectWriter> OW =
468 DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)
469 : MAB->createObjectWriter(*Out);
471 Triple T(Opts.Triple);
472 Str.reset(TheTarget->createMCObjectStreamer(
473 T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI,
474 Opts.RelaxAll, Opts.IncrementalLinkerCompatible,
475 /*DWARFMustBeAtTheEnd*/ true));
476 Str.get()->InitSections(Opts.NoExecStack);
479 // When -fembed-bitcode is passed to clang_as, a 1-byte marker
480 // is emitted in __LLVM,__asm section if the object file is MachO format.
481 if (Opts.EmbedBitcode && Ctx.getObjectFileInfo()->getObjectFileType() ==
482 MCObjectFileInfo::IsMachO) {
483 MCSection *AsmLabel = Ctx.getMachOSection(
484 "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());
485 Str.get()->SwitchSection(AsmLabel);
486 Str.get()->EmitZeros(1);
489 // Assembly to object compilation should leverage assembly info.
490 Str->setUseAssemblerInfoForParsing(true);
494 std::unique_ptr<MCAsmParser> Parser(
495 createMCAsmParser(SrcMgr, Ctx, *Str.get(), *MAI));
497 // FIXME: init MCTargetOptions from sanitizer flags here.
498 std::unique_ptr<MCTargetAsmParser> TAP(
499 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));
501 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple;
503 // Set values for symbols, if any.
504 for (auto &S : Opts.SymbolDefs) {
505 auto Pair = StringRef(S).split('=');
506 auto Sym = Pair.first;
507 auto Val = Pair.second;
509 // We have already error checked this in the driver.
510 Val.getAsInteger(0, Value);
511 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);
515 Parser->setTargetParser(*TAP.get());
516 Failed = Parser->Run(Opts.NoInitialTextSection);
519 // Close Streamer first.
520 // It might have a reference to the output stream.
522 // Close the output stream early.
526 // Delete output file if there were errors.
528 if (Opts.OutputPath != "-")
529 sys::fs::remove(Opts.OutputPath);
530 if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")
531 sys::fs::remove(Opts.SplitDwarfOutput);
537 static void LLVMErrorHandler(void *UserData, const std::string &Message,
539 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);
541 Diags.Report(diag::err_fe_error_backend) << Message;
543 // We cannot recover from llvm errors.
547 int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {
548 // Initialize targets and assembly printers/parsers.
549 InitializeAllTargetInfos();
550 InitializeAllTargetMCs();
551 InitializeAllAsmParsers();
553 // Construct our diagnostic client.
554 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
555 TextDiagnosticPrinter *DiagClient
556 = new TextDiagnosticPrinter(errs(), &*DiagOpts);
557 DiagClient->setPrefix("clang -cc1as");
558 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
559 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
561 // Set an error handler, so that any LLVM backend diagnostics go through our
563 ScopedFatalErrorHandler FatalErrorHandler
564 (LLVMErrorHandler, static_cast<void*>(&Diags));
566 // Parse the arguments.
567 AssemblerInvocation Asm;
568 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))
572 std::unique_ptr<OptTable> Opts(driver::createDriverOptTable());
573 Opts->PrintHelp(llvm::outs(), "clang -cc1as [options] file...",
574 "Clang Integrated Assembler",
575 /*Include=*/driver::options::CC1AsOption, /*Exclude=*/0,
576 /*ShowAllAliases=*/false);
582 // FIXME: Use a better -version message?
583 if (Asm.ShowVersion) {
584 llvm::cl::PrintVersionMessage();
590 // FIXME: Remove this, one day.
591 if (!Asm.LLVMArgs.empty()) {
592 unsigned NumArgs = Asm.LLVMArgs.size();
593 auto Args = llvm::make_unique<const char*[]>(NumArgs + 2);
594 Args[0] = "clang (LLVM option parsing)";
595 for (unsigned i = 0; i != NumArgs; ++i)
596 Args[i + 1] = Asm.LLVMArgs[i].c_str();
597 Args[NumArgs + 1] = nullptr;
598 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get());
601 // Execute the invocation, unless there were parsing errors.
602 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags);
604 // If any timers were active but haven't been destroyed yet, print their
606 TimerGroup::printAll(errs());