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