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