cc1as_main.cpp 23 KB

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