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