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