cc1as_main.cpp 21 KB

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