cc1as_main.cpp 21 KB

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