727 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8//9// This is the entry point to the clang -cc1as functionality, which implements10// the direct interface to the LLVM MC based assembler.11//12//===----------------------------------------------------------------------===//13 14#include "clang/Basic/Diagnostic.h"15#include "clang/Basic/DiagnosticFrontend.h"16#include "clang/Basic/DiagnosticOptions.h"17#include "clang/Driver/DriverDiagnostic.h"18#include "clang/Frontend/TextDiagnosticPrinter.h"19#include "clang/Frontend/Utils.h"20#include "clang/Options/Options.h"21#include "llvm/ADT/STLExtras.h"22#include "llvm/ADT/StringExtras.h"23#include "llvm/ADT/StringSwitch.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/MCInstPrinter.h"30#include "llvm/MC/MCInstrInfo.h"31#include "llvm/MC/MCObjectFileInfo.h"32#include "llvm/MC/MCObjectWriter.h"33#include "llvm/MC/MCParser/MCAsmParser.h"34#include "llvm/MC/MCParser/MCTargetAsmParser.h"35#include "llvm/MC/MCRegisterInfo.h"36#include "llvm/MC/MCSectionMachO.h"37#include "llvm/MC/MCStreamer.h"38#include "llvm/MC/MCSubtargetInfo.h"39#include "llvm/MC/MCTargetOptions.h"40#include "llvm/MC/TargetRegistry.h"41#include "llvm/Option/Arg.h"42#include "llvm/Option/ArgList.h"43#include "llvm/Option/OptTable.h"44#include "llvm/Support/CommandLine.h"45#include "llvm/Support/ErrorHandling.h"46#include "llvm/Support/FileSystem.h"47#include "llvm/Support/FormattedStream.h"48#include "llvm/Support/MemoryBuffer.h"49#include "llvm/Support/Path.h"50#include "llvm/Support/Process.h"51#include "llvm/Support/Signals.h"52#include "llvm/Support/SourceMgr.h"53#include "llvm/Support/TargetSelect.h"54#include "llvm/Support/Timer.h"55#include "llvm/Support/raw_ostream.h"56#include "llvm/TargetParser/Host.h"57#include "llvm/TargetParser/Triple.h"58#include <memory>59#include <optional>60#include <system_error>61using namespace clang;62using namespace clang::options;63using namespace llvm;64using namespace llvm::opt;65 66namespace {67 68/// Helper class for representing a single invocation of the assembler.69struct AssemblerInvocation {70 /// @name Target Options71 /// @{72 73 /// The target triple to assemble for.74 llvm::Triple Triple;75 76 /// If given, the name of the target CPU to determine which instructions77 /// are legal.78 std::string CPU;79 80 /// The list of target specific features to enable or disable -- this should81 /// be a list of strings starting with '+' or '-'.82 std::vector<std::string> Features;83 84 /// The list of symbol definitions.85 std::vector<std::string> SymbolDefs;86 87 /// @}88 /// @name Language Options89 /// @{90 91 std::vector<std::string> IncludePaths;92 LLVM_PREFERRED_TYPE(bool)93 unsigned NoInitialTextSection : 1;94 LLVM_PREFERRED_TYPE(bool)95 unsigned SaveTemporaryLabels : 1;96 LLVM_PREFERRED_TYPE(bool)97 unsigned GenDwarfForAssembly : 1;98 LLVM_PREFERRED_TYPE(bool)99 unsigned Dwarf64 : 1;100 unsigned DwarfVersion;101 std::string DwarfDebugFlags;102 std::string DwarfDebugProducer;103 std::string DebugCompilationDir;104 llvm::SmallVector<std::pair<std::string, std::string>, 0> DebugPrefixMap;105 llvm::DebugCompressionType CompressDebugSections =106 llvm::DebugCompressionType::None;107 std::string MainFileName;108 std::string SplitDwarfOutput;109 110 /// @}111 /// @name Frontend Options112 /// @{113 114 std::string InputFile;115 std::vector<std::string> LLVMArgs;116 std::string OutputPath;117 enum FileType {118 FT_Asm, ///< Assembly (.s) output, transliterate mode.119 FT_Null, ///< No output, for timing purposes.120 FT_Obj ///< Object file output.121 };122 FileType OutputType;123 LLVM_PREFERRED_TYPE(bool)124 unsigned ShowHelp : 1;125 LLVM_PREFERRED_TYPE(bool)126 unsigned ShowVersion : 1;127 128 /// @}129 /// @name Transliterate Options130 /// @{131 132 unsigned OutputAsmVariant;133 LLVM_PREFERRED_TYPE(bool)134 unsigned ShowEncoding : 1;135 LLVM_PREFERRED_TYPE(bool)136 unsigned ShowInst : 1;137 138 /// @}139 /// @name Assembler Options140 /// @{141 142 LLVM_PREFERRED_TYPE(bool)143 unsigned RelaxAll : 1;144 LLVM_PREFERRED_TYPE(bool)145 unsigned NoExecStack : 1;146 LLVM_PREFERRED_TYPE(bool)147 unsigned FatalWarnings : 1;148 LLVM_PREFERRED_TYPE(bool)149 unsigned NoWarn : 1;150 LLVM_PREFERRED_TYPE(bool)151 unsigned NoTypeCheck : 1;152 LLVM_PREFERRED_TYPE(bool)153 unsigned IncrementalLinkerCompatible : 1;154 LLVM_PREFERRED_TYPE(bool)155 unsigned EmbedBitcode : 1;156 157 /// Whether to emit DWARF unwind info.158 EmitDwarfUnwindType EmitDwarfUnwind;159 160 // Whether to emit compact-unwind for non-canonical entries.161 // Note: maybe overriden by other constraints.162 LLVM_PREFERRED_TYPE(bool)163 unsigned EmitCompactUnwindNonCanonical : 1;164 165 LLVM_PREFERRED_TYPE(bool)166 unsigned Crel : 1;167 LLVM_PREFERRED_TYPE(bool)168 unsigned ImplicitMapsyms : 1;169 170 LLVM_PREFERRED_TYPE(bool)171 unsigned X86RelaxRelocations : 1;172 LLVM_PREFERRED_TYPE(bool)173 unsigned X86Sse2Avx : 1;174 175 /// The name of the relocation model to use.176 std::string RelocationModel;177 178 /// The ABI targeted by the backend. Specified using -target-abi. Empty179 /// otherwise.180 std::string TargetABI;181 182 /// Darwin target variant triple, the variant of the deployment target183 /// for which the code is being compiled.184 std::optional<llvm::Triple> DarwinTargetVariantTriple;185 186 /// The version of the darwin target variant SDK which was used during the187 /// compilation188 llvm::VersionTuple DarwinTargetVariantSDKVersion;189 190 /// The name of a file to use with \c .secure_log_unique directives.191 std::string AsSecureLogFile;192 /// @}193 194 void setTriple(llvm::StringRef Str) {195 Triple = llvm::Triple(llvm::Triple::normalize(Str));196 }197 198public:199 AssemblerInvocation() {200 NoInitialTextSection = 0;201 InputFile = "-";202 OutputPath = "-";203 OutputType = FT_Asm;204 OutputAsmVariant = 0;205 ShowInst = 0;206 ShowEncoding = 0;207 RelaxAll = 0;208 NoExecStack = 0;209 FatalWarnings = 0;210 NoWarn = 0;211 NoTypeCheck = 0;212 IncrementalLinkerCompatible = 0;213 Dwarf64 = 0;214 DwarfVersion = 0;215 EmbedBitcode = 0;216 EmitDwarfUnwind = EmitDwarfUnwindType::Default;217 EmitCompactUnwindNonCanonical = false;218 Crel = false;219 ImplicitMapsyms = 0;220 X86RelaxRelocations = 0;221 X86Sse2Avx = 0;222 }223 224 static bool CreateFromArgs(AssemblerInvocation &Res,225 ArrayRef<const char *> Argv,226 DiagnosticsEngine &Diags);227};228 229}230 231bool AssemblerInvocation::CreateFromArgs(AssemblerInvocation &Opts,232 ArrayRef<const char *> Argv,233 DiagnosticsEngine &Diags) {234 bool Success = true;235 236 // Parse the arguments.237 const OptTable &OptTbl = getDriverOptTable();238 239 llvm::opt::Visibility VisibilityMask(options::CC1AsOption);240 unsigned MissingArgIndex, MissingArgCount;241 InputArgList Args =242 OptTbl.ParseArgs(Argv, MissingArgIndex, MissingArgCount, VisibilityMask);243 244 // Check for missing argument error.245 if (MissingArgCount) {246 Diags.Report(diag::err_drv_missing_argument)247 << Args.getArgString(MissingArgIndex) << MissingArgCount;248 Success = false;249 }250 251 // Issue errors on unknown arguments.252 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) {253 auto ArgString = A->getAsString(Args);254 std::string Nearest;255 if (OptTbl.findNearest(ArgString, Nearest, VisibilityMask) > 1)256 Diags.Report(diag::err_drv_unknown_argument) << ArgString;257 else258 Diags.Report(diag::err_drv_unknown_argument_with_suggestion)259 << ArgString << Nearest;260 Success = false;261 }262 263 // Construct the invocation.264 265 // Target Options266 Opts.setTriple(Args.getLastArgValue(OPT_triple));267 if (Arg *A = Args.getLastArg(options::OPT_darwin_target_variant_triple))268 Opts.DarwinTargetVariantTriple = llvm::Triple(A->getValue());269 if (Arg *A = Args.getLastArg(OPT_darwin_target_variant_sdk_version_EQ)) {270 VersionTuple Version;271 if (Version.tryParse(A->getValue()))272 Diags.Report(diag::err_drv_invalid_value)273 << A->getAsString(Args) << A->getValue();274 else275 Opts.DarwinTargetVariantSDKVersion = Version;276 }277 278 Opts.CPU = std::string(Args.getLastArgValue(OPT_target_cpu));279 Opts.Features = Args.getAllArgValues(OPT_target_feature);280 281 // Use the default target triple if unspecified.282 if (Opts.Triple.empty())283 Opts.setTriple(llvm::sys::getDefaultTargetTriple());284 285 // Language Options286 Opts.IncludePaths = Args.getAllArgValues(OPT_I);287 Opts.NoInitialTextSection = Args.hasArg(OPT_n);288 Opts.SaveTemporaryLabels = Args.hasArg(OPT_msave_temp_labels);289 // Any DebugInfoKind implies GenDwarfForAssembly.290 Opts.GenDwarfForAssembly = Args.hasArg(OPT_debug_info_kind_EQ);291 292 if (const Arg *A = Args.getLastArg(OPT_compress_debug_sections_EQ)) {293 Opts.CompressDebugSections =294 llvm::StringSwitch<llvm::DebugCompressionType>(A->getValue())295 .Case("none", llvm::DebugCompressionType::None)296 .Case("zlib", llvm::DebugCompressionType::Zlib)297 .Case("zstd", llvm::DebugCompressionType::Zstd)298 .Default(llvm::DebugCompressionType::None);299 }300 301 if (auto *DwarfFormatArg = Args.getLastArg(OPT_gdwarf64, OPT_gdwarf32))302 Opts.Dwarf64 = DwarfFormatArg->getOption().matches(OPT_gdwarf64);303 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 2, Diags);304 Opts.DwarfDebugFlags =305 std::string(Args.getLastArgValue(OPT_dwarf_debug_flags));306 Opts.DwarfDebugProducer =307 std::string(Args.getLastArgValue(OPT_dwarf_debug_producer));308 if (const Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,309 options::OPT_fdebug_compilation_dir_EQ))310 Opts.DebugCompilationDir = A->getValue();311 Opts.MainFileName = std::string(Args.getLastArgValue(OPT_main_file_name));312 313 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {314 auto Split = StringRef(Arg).split('=');315 Opts.DebugPrefixMap.emplace_back(Split.first, Split.second);316 }317 318 // Frontend Options319 if (Args.hasArg(OPT_INPUT)) {320 bool First = true;321 for (const Arg *A : Args.filtered(OPT_INPUT)) {322 if (First) {323 Opts.InputFile = A->getValue();324 First = false;325 } else {326 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args);327 Success = false;328 }329 }330 }331 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);332 Opts.OutputPath = std::string(Args.getLastArgValue(OPT_o));333 Opts.SplitDwarfOutput =334 std::string(Args.getLastArgValue(OPT_split_dwarf_output));335 if (Arg *A = Args.getLastArg(OPT_filetype)) {336 StringRef Name = A->getValue();337 unsigned OutputType = StringSwitch<unsigned>(Name)338 .Case("asm", FT_Asm)339 .Case("null", FT_Null)340 .Case("obj", FT_Obj)341 .Default(~0U);342 if (OutputType == ~0U) {343 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;344 Success = false;345 } else346 Opts.OutputType = FileType(OutputType);347 }348 Opts.ShowHelp = Args.hasArg(OPT_help);349 Opts.ShowVersion = Args.hasArg(OPT_version);350 351 // Transliterate Options352 Opts.OutputAsmVariant =353 getLastArgIntValue(Args, OPT_output_asm_variant, 0, Diags);354 Opts.ShowEncoding = Args.hasArg(OPT_show_encoding);355 Opts.ShowInst = Args.hasArg(OPT_show_inst);356 357 // Assemble Options358 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);359 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);360 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);361 Opts.NoWarn = Args.hasArg(OPT_massembler_no_warn);362 Opts.NoTypeCheck = Args.hasArg(OPT_mno_type_check);363 Opts.RelocationModel =364 std::string(Args.getLastArgValue(OPT_mrelocation_model, "pic"));365 Opts.TargetABI = std::string(Args.getLastArgValue(OPT_target_abi));366 Opts.IncrementalLinkerCompatible =367 Args.hasArg(OPT_mincremental_linker_compatible);368 Opts.SymbolDefs = Args.getAllArgValues(OPT_defsym);369 370 // EmbedBitcode Option. If -fembed-bitcode is enabled, set the flag.371 // EmbedBitcode behaves the same for all embed options for assembly files.372 if (auto *A = Args.getLastArg(OPT_fembed_bitcode_EQ)) {373 Opts.EmbedBitcode = llvm::StringSwitch<unsigned>(A->getValue())374 .Case("all", 1)375 .Case("bitcode", 1)376 .Case("marker", 1)377 .Default(0);378 }379 380 if (auto *A = Args.getLastArg(OPT_femit_dwarf_unwind_EQ)) {381 Opts.EmitDwarfUnwind =382 llvm::StringSwitch<EmitDwarfUnwindType>(A->getValue())383 .Case("always", EmitDwarfUnwindType::Always)384 .Case("no-compact-unwind", EmitDwarfUnwindType::NoCompactUnwind)385 .Case("default", EmitDwarfUnwindType::Default);386 }387 388 Opts.EmitCompactUnwindNonCanonical =389 Args.hasArg(OPT_femit_compact_unwind_non_canonical);390 Opts.Crel = Args.hasArg(OPT_crel);391 Opts.ImplicitMapsyms = Args.hasArg(OPT_mmapsyms_implicit);392 Opts.X86RelaxRelocations = !Args.hasArg(OPT_mrelax_relocations_no);393 Opts.X86Sse2Avx = Args.hasArg(OPT_msse2avx);394 395 Opts.AsSecureLogFile = Args.getLastArgValue(OPT_as_secure_log_file);396 397 return Success;398}399 400static std::unique_ptr<raw_fd_ostream>401getOutputStream(StringRef Path, DiagnosticsEngine &Diags, bool Binary) {402 // Make sure that the Out file gets unlinked from the disk if we get a403 // SIGINT.404 if (Path != "-")405 sys::RemoveFileOnSignal(Path);406 407 std::error_code EC;408 auto Out = std::make_unique<raw_fd_ostream>(409 Path, EC, (Binary ? sys::fs::OF_None : sys::fs::OF_TextWithCRLF));410 if (EC) {411 Diags.Report(diag::err_fe_unable_to_open_output) << Path << EC.message();412 return nullptr;413 }414 415 return Out;416}417 418static bool ExecuteAssemblerImpl(AssemblerInvocation &Opts,419 DiagnosticsEngine &Diags,420 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {421 // Get the target specific parser.422 std::string Error;423 const Target *TheTarget = TargetRegistry::lookupTarget(Opts.Triple, Error);424 if (!TheTarget)425 return Diags.Report(diag::err_target_unknown_triple) << Opts.Triple.str();426 427 ErrorOr<std::unique_ptr<MemoryBuffer>> Buffer =428 MemoryBuffer::getFileOrSTDIN(Opts.InputFile, /*IsText=*/true);429 430 if (std::error_code EC = Buffer.getError()) {431 return Diags.Report(diag::err_fe_error_reading)432 << Opts.InputFile << EC.message();433 }434 435 SourceMgr SrcMgr;436 437 // Tell SrcMgr about this buffer, which is what the parser will pick up.438 unsigned BufferIndex = SrcMgr.AddNewSourceBuffer(std::move(*Buffer), SMLoc());439 440 // Record the location of the include directories so that the lexer can find441 // it later.442 SrcMgr.setIncludeDirs(Opts.IncludePaths);443 SrcMgr.setVirtualFileSystem(VFS);444 445 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(Opts.Triple));446 assert(MRI && "Unable to create target register info!");447 448 MCTargetOptions MCOptions;449 MCOptions.MCRelaxAll = Opts.RelaxAll;450 MCOptions.EmitDwarfUnwind = Opts.EmitDwarfUnwind;451 MCOptions.EmitCompactUnwindNonCanonical = Opts.EmitCompactUnwindNonCanonical;452 MCOptions.MCSaveTempLabels = Opts.SaveTemporaryLabels;453 MCOptions.Crel = Opts.Crel;454 MCOptions.ImplicitMapSyms = Opts.ImplicitMapsyms;455 MCOptions.X86RelaxRelocations = Opts.X86RelaxRelocations;456 MCOptions.X86Sse2Avx = Opts.X86Sse2Avx;457 MCOptions.CompressDebugSections = Opts.CompressDebugSections;458 MCOptions.AsSecureLogFile = Opts.AsSecureLogFile;459 460 std::unique_ptr<MCAsmInfo> MAI(461 TheTarget->createMCAsmInfo(*MRI, Opts.Triple, MCOptions));462 assert(MAI && "Unable to create target asm info!");463 464 // Ensure MCAsmInfo initialization occurs before any use, otherwise sections465 // may be created with a combination of default and explicit settings.466 467 468 bool IsBinary = Opts.OutputType == AssemblerInvocation::FT_Obj;469 if (Opts.OutputPath.empty())470 Opts.OutputPath = "-";471 std::unique_ptr<raw_fd_ostream> FDOS =472 getOutputStream(Opts.OutputPath, Diags, IsBinary);473 if (!FDOS)474 return true;475 std::unique_ptr<raw_fd_ostream> DwoOS;476 if (!Opts.SplitDwarfOutput.empty())477 DwoOS = getOutputStream(Opts.SplitDwarfOutput, Diags, IsBinary);478 479 // Build up the feature string from the target feature list.480 std::string FS = llvm::join(Opts.Features, ",");481 482 std::unique_ptr<MCSubtargetInfo> STI(483 TheTarget->createMCSubtargetInfo(Opts.Triple, Opts.CPU, FS));484 if (!STI) {485 return Diags.Report(diag::err_fe_unable_to_create_subtarget)486 << Opts.CPU << FS.empty() << FS;487 }488 489 MCContext Ctx(Triple(Opts.Triple), MAI.get(), MRI.get(), STI.get(), &SrcMgr,490 &MCOptions);491 492 bool PIC = false;493 if (Opts.RelocationModel == "static") {494 PIC = false;495 } else if (Opts.RelocationModel == "pic") {496 PIC = true;497 } else {498 assert(Opts.RelocationModel == "dynamic-no-pic" &&499 "Invalid PIC model!");500 PIC = false;501 }502 503 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and504 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.505 std::unique_ptr<MCObjectFileInfo> MOFI(506 TheTarget->createMCObjectFileInfo(Ctx, PIC));507 Ctx.setObjectFileInfo(MOFI.get());508 509 if (Opts.GenDwarfForAssembly)510 Ctx.setGenDwarfForAssembly(true);511 if (!Opts.DwarfDebugFlags.empty())512 Ctx.setDwarfDebugFlags(StringRef(Opts.DwarfDebugFlags));513 if (!Opts.DwarfDebugProducer.empty())514 Ctx.setDwarfDebugProducer(StringRef(Opts.DwarfDebugProducer));515 if (!Opts.DebugCompilationDir.empty())516 Ctx.setCompilationDir(Opts.DebugCompilationDir);517 else {518 // If no compilation dir is set, try to use the current directory.519 SmallString<128> CWD;520 if (!sys::fs::current_path(CWD))521 Ctx.setCompilationDir(CWD);522 }523 if (!Opts.DebugPrefixMap.empty())524 for (const auto &KV : Opts.DebugPrefixMap)525 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);526 if (!Opts.MainFileName.empty())527 Ctx.setMainFileName(StringRef(Opts.MainFileName));528 Ctx.setDwarfFormat(Opts.Dwarf64 ? dwarf::DWARF64 : dwarf::DWARF32);529 Ctx.setDwarfVersion(Opts.DwarfVersion);530 if (Opts.GenDwarfForAssembly)531 Ctx.setGenDwarfRootFile(Opts.InputFile,532 SrcMgr.getMemoryBuffer(BufferIndex)->getBuffer());533 534 std::unique_ptr<MCStreamer> Str;535 536 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());537 assert(MCII && "Unable to create instruction info!");538 539 raw_pwrite_stream *Out = FDOS.get();540 std::unique_ptr<buffer_ostream> BOS;541 542 MCOptions.MCNoWarn = Opts.NoWarn;543 MCOptions.MCFatalWarnings = Opts.FatalWarnings;544 MCOptions.MCNoTypeCheck = Opts.NoTypeCheck;545 MCOptions.ShowMCInst = Opts.ShowInst;546 MCOptions.AsmVerbose = true;547 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;548 MCOptions.ABIName = Opts.TargetABI;549 550 // FIXME: There is a bit of code duplication with addPassesToEmitFile.551 if (Opts.OutputType == AssemblerInvocation::FT_Asm) {552 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(553 llvm::Triple(Opts.Triple), Opts.OutputAsmVariant, *MAI, *MCII, *MRI));554 555 std::unique_ptr<MCCodeEmitter> CE;556 if (Opts.ShowEncoding)557 CE.reset(TheTarget->createMCCodeEmitter(*MCII, Ctx));558 std::unique_ptr<MCAsmBackend> MAB(559 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));560 561 auto FOut = std::make_unique<formatted_raw_ostream>(*Out);562 Str.reset(TheTarget->createAsmStreamer(Ctx, std::move(FOut), std::move(IP),563 std::move(CE), std::move(MAB)));564 } else if (Opts.OutputType == AssemblerInvocation::FT_Null) {565 Str.reset(createNullStreamer(Ctx));566 } else {567 assert(Opts.OutputType == AssemblerInvocation::FT_Obj &&568 "Invalid file type!");569 if (!FDOS->supportsSeeking()) {570 BOS = std::make_unique<buffer_ostream>(*FDOS);571 Out = BOS.get();572 }573 574 std::unique_ptr<MCCodeEmitter> CE(575 TheTarget->createMCCodeEmitter(*MCII, Ctx));576 std::unique_ptr<MCAsmBackend> MAB(577 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));578 assert(MAB && "Unable to create asm backend!");579 580 std::unique_ptr<MCObjectWriter> OW =581 DwoOS ? MAB->createDwoObjectWriter(*Out, *DwoOS)582 : MAB->createObjectWriter(*Out);583 584 Triple T(Opts.Triple);585 Str.reset(TheTarget->createMCObjectStreamer(586 T, Ctx, std::move(MAB), std::move(OW), std::move(CE), *STI));587 if (T.isOSBinFormatMachO() && T.isOSDarwin()) {588 Triple *TVT = Opts.DarwinTargetVariantTriple589 ? &*Opts.DarwinTargetVariantTriple590 : nullptr;591 Str->emitVersionForTarget(T, VersionTuple(), TVT,592 Opts.DarwinTargetVariantSDKVersion);593 }594 }595 596 // When -fembed-bitcode is passed to clang_as, a 1-byte marker597 // is emitted in __LLVM,__asm section if the object file is MachO format.598 if (Opts.EmbedBitcode && Ctx.getObjectFileType() == MCContext::IsMachO) {599 MCSection *AsmLabel = Ctx.getMachOSection(600 "__LLVM", "__asm", MachO::S_REGULAR, 4, SectionKind::getReadOnly());601 Str->switchSection(AsmLabel);602 Str->emitZeros(1);603 }604 605 bool Failed = false;606 607 std::unique_ptr<MCAsmParser> Parser(608 createMCAsmParser(SrcMgr, Ctx, *Str, *MAI));609 610 // FIXME: init MCTargetOptions from sanitizer flags here.611 std::unique_ptr<MCTargetAsmParser> TAP(612 TheTarget->createMCAsmParser(*STI, *Parser, *MCII, MCOptions));613 if (!TAP)614 Failed = Diags.Report(diag::err_target_unknown_triple) << Opts.Triple.str();615 616 // Set values for symbols, if any.617 for (auto &S : Opts.SymbolDefs) {618 auto Pair = StringRef(S).split('=');619 auto Sym = Pair.first;620 auto Val = Pair.second;621 int64_t Value;622 // We have already error checked this in the driver.623 Val.getAsInteger(0, Value);624 Ctx.setSymbolValue(Parser->getStreamer(), Sym, Value);625 }626 627 if (!Failed) {628 Parser->setTargetParser(*TAP);629 Failed = Parser->Run(Opts.NoInitialTextSection);630 }631 632 return Failed;633}634 635static bool ExecuteAssembler(AssemblerInvocation &Opts,636 DiagnosticsEngine &Diags,637 IntrusiveRefCntPtr<vfs::FileSystem> VFS) {638 bool Failed = ExecuteAssemblerImpl(Opts, Diags, VFS);639 640 // Delete output file if there were errors.641 if (Failed) {642 if (Opts.OutputPath != "-")643 sys::fs::remove(Opts.OutputPath);644 if (!Opts.SplitDwarfOutput.empty() && Opts.SplitDwarfOutput != "-")645 sys::fs::remove(Opts.SplitDwarfOutput);646 }647 648 return Failed;649}650 651static void LLVMErrorHandler(void *UserData, const char *Message,652 bool GenCrashDiag) {653 DiagnosticsEngine &Diags = *static_cast<DiagnosticsEngine*>(UserData);654 655 Diags.Report(diag::err_fe_error_backend) << Message;656 657 // We cannot recover from llvm errors.658 sys::Process::Exit(1);659}660 661int cc1as_main(ArrayRef<const char *> Argv, const char *Argv0, void *MainAddr) {662 // Initialize targets and assembly printers/parsers.663 InitializeAllTargetInfos();664 InitializeAllTargetMCs();665 InitializeAllAsmParsers();666 667 // Construct our diagnostic client.668 DiagnosticOptions DiagOpts;669 TextDiagnosticPrinter *DiagClient =670 new TextDiagnosticPrinter(errs(), DiagOpts);671 DiagClient->setPrefix("clang -cc1as");672 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagClient);673 674 auto VFS = vfs::getRealFileSystem();675 676 // Set an error handler, so that any LLVM backend diagnostics go through our677 // error handler.678 ScopedFatalErrorHandler FatalErrorHandler679 (LLVMErrorHandler, static_cast<void*>(&Diags));680 681 // Parse the arguments.682 AssemblerInvocation Asm;683 if (!AssemblerInvocation::CreateFromArgs(Asm, Argv, Diags))684 return 1;685 686 if (Asm.ShowHelp) {687 getDriverOptTable().printHelp(688 llvm::outs(), "clang -cc1as [options] file...",689 "Clang Integrated Assembler", /*ShowHidden=*/false,690 /*ShowAllAliases=*/false, llvm::opt::Visibility(options::CC1AsOption));691 692 return 0;693 }694 695 // Honor -version.696 //697 // FIXME: Use a better -version message?698 if (Asm.ShowVersion) {699 llvm::cl::PrintVersionMessage();700 return 0;701 }702 703 // Honor -mllvm.704 //705 // FIXME: Remove this, one day.706 if (!Asm.LLVMArgs.empty()) {707 unsigned NumArgs = Asm.LLVMArgs.size();708 auto Args = std::make_unique<const char*[]>(NumArgs + 2);709 Args[0] = "clang (LLVM option parsing)";710 for (unsigned i = 0; i != NumArgs; ++i)711 Args[i + 1] = Asm.LLVMArgs[i].c_str();712 Args[NumArgs + 1] = nullptr;713 llvm::cl::ParseCommandLineOptions(NumArgs + 1, Args.get(), /*Overview=*/"",714 /*Errs=*/nullptr, /*VFS=*/VFS.get());715 }716 717 // Execute the invocation, unless there were parsing errors.718 bool Failed = Diags.hasErrorOccurred() || ExecuteAssembler(Asm, Diags, VFS);719 720 // If any timers were active but haven't been destroyed yet, print their721 // results now.722 TimerGroup::printAll(errs());723 TimerGroup::clearAll();724 725 return !!Failed;726}727