llvm-mc.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
  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 utility is a simple driver that allows command line hacking on machine
  10. // code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "Disassembler.h"
  14. #include "llvm/MC/MCAsmBackend.h"
  15. #include "llvm/MC/MCAsmInfo.h"
  16. #include "llvm/MC/MCCodeEmitter.h"
  17. #include "llvm/MC/MCContext.h"
  18. #include "llvm/MC/MCInstPrinter.h"
  19. #include "llvm/MC/MCInstrInfo.h"
  20. #include "llvm/MC/MCObjectFileInfo.h"
  21. #include "llvm/MC/MCObjectWriter.h"
  22. #include "llvm/MC/MCParser/AsmLexer.h"
  23. #include "llvm/MC/MCParser/MCTargetAsmParser.h"
  24. #include "llvm/MC/MCRegisterInfo.h"
  25. #include "llvm/MC/MCStreamer.h"
  26. #include "llvm/MC/MCSubtargetInfo.h"
  27. #include "llvm/MC/MCTargetOptionsCommandFlags.h"
  28. #include "llvm/MC/TargetRegistry.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Compression.h"
  31. #include "llvm/Support/FileUtilities.h"
  32. #include "llvm/Support/FormattedStream.h"
  33. #include "llvm/Support/Host.h"
  34. #include "llvm/Support/InitLLVM.h"
  35. #include "llvm/Support/MemoryBuffer.h"
  36. #include "llvm/Support/SourceMgr.h"
  37. #include "llvm/Support/TargetSelect.h"
  38. #include "llvm/Support/ToolOutputFile.h"
  39. #include "llvm/Support/WithColor.h"
  40. using namespace llvm;
  41. static mc::RegisterMCTargetOptionsFlags MOF;
  42. static cl::OptionCategory MCCategory("MC Options");
  43. static cl::opt<std::string> InputFilename(cl::Positional,
  44. cl::desc("<input file>"),
  45. cl::init("-"), cl::cat(MCCategory));
  46. static cl::list<std::string>
  47. DisassemblerOptions("M", cl::desc("Disassembler options"),
  48. cl::cat(MCCategory));
  49. static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
  50. cl::value_desc("filename"),
  51. cl::init("-"), cl::cat(MCCategory));
  52. static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
  53. cl::desc("DWO output filename"),
  54. cl::value_desc("filename"),
  55. cl::cat(MCCategory));
  56. static cl::opt<bool> ShowEncoding("show-encoding",
  57. cl::desc("Show instruction encodings"),
  58. cl::cat(MCCategory));
  59. static cl::opt<bool> RelaxELFRel(
  60. "relax-relocations", cl::init(true),
  61. cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"),
  62. cl::cat(MCCategory));
  63. static cl::opt<DebugCompressionType> CompressDebugSections(
  64. "compress-debug-sections", cl::ValueOptional,
  65. cl::init(DebugCompressionType::None),
  66. cl::desc("Choose DWARF debug sections compression:"),
  67. cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
  68. clEnumValN(DebugCompressionType::Zlib, "zlib", "Use zlib"),
  69. clEnumValN(DebugCompressionType::Zstd, "zstd", "Use zstd")),
  70. cl::cat(MCCategory));
  71. static cl::opt<bool>
  72. ShowInst("show-inst", cl::desc("Show internal instruction representation"),
  73. cl::cat(MCCategory));
  74. static cl::opt<bool>
  75. ShowInstOperands("show-inst-operands",
  76. cl::desc("Show instructions operands as parsed"),
  77. cl::cat(MCCategory));
  78. static cl::opt<unsigned>
  79. OutputAsmVariant("output-asm-variant",
  80. cl::desc("Syntax variant to use for output printing"),
  81. cl::cat(MCCategory));
  82. static cl::opt<bool>
  83. PrintImmHex("print-imm-hex", cl::init(false),
  84. cl::desc("Prefer hex format for immediate values"),
  85. cl::cat(MCCategory));
  86. static cl::list<std::string>
  87. DefineSymbol("defsym",
  88. cl::desc("Defines a symbol to be an integer constant"),
  89. cl::cat(MCCategory));
  90. static cl::opt<bool>
  91. PreserveComments("preserve-comments",
  92. cl::desc("Preserve Comments in outputted assembly"),
  93. cl::cat(MCCategory));
  94. enum OutputFileType {
  95. OFT_Null,
  96. OFT_AssemblyFile,
  97. OFT_ObjectFile
  98. };
  99. static cl::opt<OutputFileType>
  100. FileType("filetype", cl::init(OFT_AssemblyFile),
  101. cl::desc("Choose an output file type:"),
  102. cl::values(clEnumValN(OFT_AssemblyFile, "asm",
  103. "Emit an assembly ('.s') file"),
  104. clEnumValN(OFT_Null, "null",
  105. "Don't emit anything (for timing purposes)"),
  106. clEnumValN(OFT_ObjectFile, "obj",
  107. "Emit a native object ('.o') file")),
  108. cl::cat(MCCategory));
  109. static cl::list<std::string> IncludeDirs("I",
  110. cl::desc("Directory of include files"),
  111. cl::value_desc("directory"),
  112. cl::Prefix, cl::cat(MCCategory));
  113. static cl::opt<std::string>
  114. ArchName("arch",
  115. cl::desc("Target arch to assemble for, "
  116. "see -version for available targets"),
  117. cl::cat(MCCategory));
  118. static cl::opt<std::string>
  119. TripleName("triple",
  120. cl::desc("Target triple to assemble for, "
  121. "see -version for available targets"),
  122. cl::cat(MCCategory));
  123. static cl::opt<std::string>
  124. MCPU("mcpu",
  125. cl::desc("Target a specific cpu type (-mcpu=help for details)"),
  126. cl::value_desc("cpu-name"), cl::init(""), cl::cat(MCCategory));
  127. static cl::list<std::string>
  128. MAttrs("mattr", cl::CommaSeparated,
  129. cl::desc("Target specific attributes (-mattr=help for details)"),
  130. cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory));
  131. static cl::opt<bool> PIC("position-independent",
  132. cl::desc("Position independent"), cl::init(false),
  133. cl::cat(MCCategory));
  134. static cl::opt<bool>
  135. LargeCodeModel("large-code-model",
  136. cl::desc("Create cfi directives that assume the code might "
  137. "be more than 2gb away"),
  138. cl::cat(MCCategory));
  139. static cl::opt<bool>
  140. NoInitialTextSection("n",
  141. cl::desc("Don't assume assembly file starts "
  142. "in the text section"),
  143. cl::cat(MCCategory));
  144. static cl::opt<bool>
  145. GenDwarfForAssembly("g",
  146. cl::desc("Generate dwarf debugging info for assembly "
  147. "source files"),
  148. cl::cat(MCCategory));
  149. static cl::opt<std::string>
  150. DebugCompilationDir("fdebug-compilation-dir",
  151. cl::desc("Specifies the debug info's compilation dir"),
  152. cl::cat(MCCategory));
  153. static cl::list<std::string> DebugPrefixMap(
  154. "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
  155. cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory));
  156. static cl::opt<std::string> MainFileName(
  157. "main-file-name",
  158. cl::desc("Specifies the name we should consider the input file"),
  159. cl::cat(MCCategory));
  160. static cl::opt<bool> SaveTempLabels("save-temp-labels",
  161. cl::desc("Don't discard temporary labels"),
  162. cl::cat(MCCategory));
  163. static cl::opt<bool> LexMasmIntegers(
  164. "masm-integers",
  165. cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
  166. cl::cat(MCCategory));
  167. static cl::opt<bool> LexMasmHexFloats(
  168. "masm-hexfloats",
  169. cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
  170. cl::cat(MCCategory));
  171. static cl::opt<bool> LexMotorolaIntegers(
  172. "motorola-integers",
  173. cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
  174. cl::cat(MCCategory));
  175. static cl::opt<bool> NoExecStack("no-exec-stack",
  176. cl::desc("File doesn't need an exec stack"),
  177. cl::cat(MCCategory));
  178. enum ActionType {
  179. AC_AsLex,
  180. AC_Assemble,
  181. AC_Disassemble,
  182. AC_MDisassemble,
  183. };
  184. static cl::opt<ActionType> Action(
  185. cl::desc("Action to perform:"), cl::init(AC_Assemble),
  186. cl::values(clEnumValN(AC_AsLex, "as-lex", "Lex tokens from a .s file"),
  187. clEnumValN(AC_Assemble, "assemble",
  188. "Assemble a .s file (default)"),
  189. clEnumValN(AC_Disassemble, "disassemble",
  190. "Disassemble strings of hex bytes"),
  191. clEnumValN(AC_MDisassemble, "mdis",
  192. "Marked up disassembly of strings of hex bytes")),
  193. cl::cat(MCCategory));
  194. static const Target *GetTarget(const char *ProgName) {
  195. // Figure out the target triple.
  196. if (TripleName.empty())
  197. TripleName = sys::getDefaultTargetTriple();
  198. Triple TheTriple(Triple::normalize(TripleName));
  199. // Get the target specific parser.
  200. std::string Error;
  201. const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
  202. Error);
  203. if (!TheTarget) {
  204. WithColor::error(errs(), ProgName) << Error;
  205. return nullptr;
  206. }
  207. // Update the triple name and return the found target.
  208. TripleName = TheTriple.getTriple();
  209. return TheTarget;
  210. }
  211. static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
  212. sys::fs::OpenFlags Flags) {
  213. std::error_code EC;
  214. auto Out = std::make_unique<ToolOutputFile>(Path, EC, Flags);
  215. if (EC) {
  216. WithColor::error() << EC.message() << '\n';
  217. return nullptr;
  218. }
  219. return Out;
  220. }
  221. static std::string DwarfDebugFlags;
  222. static void setDwarfDebugFlags(int argc, char **argv) {
  223. if (!getenv("RC_DEBUG_OPTIONS"))
  224. return;
  225. for (int i = 0; i < argc; i++) {
  226. DwarfDebugFlags += argv[i];
  227. if (i + 1 < argc)
  228. DwarfDebugFlags += " ";
  229. }
  230. }
  231. static std::string DwarfDebugProducer;
  232. static void setDwarfDebugProducer() {
  233. if(!getenv("DEBUG_PRODUCER"))
  234. return;
  235. DwarfDebugProducer += getenv("DEBUG_PRODUCER");
  236. }
  237. static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
  238. raw_ostream &OS) {
  239. AsmLexer Lexer(MAI);
  240. Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
  241. bool Error = false;
  242. while (Lexer.Lex().isNot(AsmToken::Eof)) {
  243. Lexer.getTok().dump(OS);
  244. OS << "\n";
  245. if (Lexer.getTok().getKind() == AsmToken::Error)
  246. Error = true;
  247. }
  248. return Error;
  249. }
  250. static int fillCommandLineSymbols(MCAsmParser &Parser) {
  251. for (auto &I: DefineSymbol) {
  252. auto Pair = StringRef(I).split('=');
  253. auto Sym = Pair.first;
  254. auto Val = Pair.second;
  255. if (Sym.empty() || Val.empty()) {
  256. WithColor::error() << "defsym must be of the form: sym=value: " << I
  257. << "\n";
  258. return 1;
  259. }
  260. int64_t Value;
  261. if (Val.getAsInteger(0, Value)) {
  262. WithColor::error() << "value is not an integer: " << Val << "\n";
  263. return 1;
  264. }
  265. Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
  266. }
  267. return 0;
  268. }
  269. static int AssembleInput(const char *ProgName, const Target *TheTarget,
  270. SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
  271. MCAsmInfo &MAI, MCSubtargetInfo &STI,
  272. MCInstrInfo &MCII, MCTargetOptions const &MCOptions) {
  273. std::unique_ptr<MCAsmParser> Parser(
  274. createMCAsmParser(SrcMgr, Ctx, Str, MAI));
  275. std::unique_ptr<MCTargetAsmParser> TAP(
  276. TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
  277. if (!TAP) {
  278. WithColor::error(errs(), ProgName)
  279. << "this target does not support assembly parsing.\n";
  280. return 1;
  281. }
  282. int SymbolResult = fillCommandLineSymbols(*Parser);
  283. if(SymbolResult)
  284. return SymbolResult;
  285. Parser->setShowParsedOperands(ShowInstOperands);
  286. Parser->setTargetParser(*TAP);
  287. Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
  288. Parser->getLexer().setLexMasmHexFloats(LexMasmHexFloats);
  289. Parser->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers);
  290. int Res = Parser->Run(NoInitialTextSection);
  291. return Res;
  292. }
  293. int main(int argc, char **argv) {
  294. InitLLVM X(argc, argv);
  295. // Initialize targets and assembly printers/parsers.
  296. llvm::InitializeAllTargetInfos();
  297. llvm::InitializeAllTargetMCs();
  298. llvm::InitializeAllAsmParsers();
  299. llvm::InitializeAllDisassemblers();
  300. // Register the target printer for --version.
  301. cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
  302. cl::HideUnrelatedOptions({&MCCategory, &getColorCategory()});
  303. cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
  304. const MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
  305. setDwarfDebugFlags(argc, argv);
  306. setDwarfDebugProducer();
  307. const char *ProgName = argv[0];
  308. const Target *TheTarget = GetTarget(ProgName);
  309. if (!TheTarget)
  310. return 1;
  311. // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
  312. // construct the Triple object.
  313. Triple TheTriple(TripleName);
  314. ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
  315. MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true);
  316. if (std::error_code EC = BufferPtr.getError()) {
  317. WithColor::error(errs(), ProgName)
  318. << InputFilename << ": " << EC.message() << '\n';
  319. return 1;
  320. }
  321. MemoryBuffer *Buffer = BufferPtr->get();
  322. SourceMgr SrcMgr;
  323. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  324. SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
  325. // Record the location of the include directories so that the lexer can find
  326. // it later.
  327. SrcMgr.setIncludeDirs(IncludeDirs);
  328. std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
  329. assert(MRI && "Unable to create target register info!");
  330. std::unique_ptr<MCAsmInfo> MAI(
  331. TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
  332. assert(MAI && "Unable to create target asm info!");
  333. MAI->setRelaxELFRelocations(RelaxELFRel);
  334. if (CompressDebugSections != DebugCompressionType::None) {
  335. if (const char *Reason = compression::getReasonIfUnsupported(
  336. compression::formatFor(CompressDebugSections))) {
  337. WithColor::error(errs(), ProgName)
  338. << "--compress-debug-sections: " << Reason;
  339. return 1;
  340. }
  341. }
  342. MAI->setCompressDebugSections(CompressDebugSections);
  343. MAI->setPreserveAsmComments(PreserveComments);
  344. // Package up features to be passed to target/subtarget
  345. std::string FeaturesStr;
  346. if (MAttrs.size()) {
  347. SubtargetFeatures Features;
  348. for (unsigned i = 0; i != MAttrs.size(); ++i)
  349. Features.AddFeature(MAttrs[i]);
  350. FeaturesStr = Features.getString();
  351. }
  352. std::unique_ptr<MCSubtargetInfo> STI(
  353. TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
  354. assert(STI && "Unable to create subtarget info!");
  355. // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
  356. // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
  357. MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr,
  358. &MCOptions);
  359. std::unique_ptr<MCObjectFileInfo> MOFI(
  360. TheTarget->createMCObjectFileInfo(Ctx, PIC, LargeCodeModel));
  361. Ctx.setObjectFileInfo(MOFI.get());
  362. if (SaveTempLabels)
  363. Ctx.setAllowTemporaryLabels(false);
  364. Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
  365. // Default to 4 for dwarf version.
  366. unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
  367. if (DwarfVersion < 2 || DwarfVersion > 5) {
  368. errs() << ProgName << ": Dwarf version " << DwarfVersion
  369. << " is not supported." << '\n';
  370. return 1;
  371. }
  372. Ctx.setDwarfVersion(DwarfVersion);
  373. if (MCOptions.Dwarf64) {
  374. // The 64-bit DWARF format was introduced in DWARFv3.
  375. if (DwarfVersion < 3) {
  376. errs() << ProgName
  377. << ": the 64-bit DWARF format is not supported for DWARF versions "
  378. "prior to 3\n";
  379. return 1;
  380. }
  381. // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
  382. if (MAI->getCodePointerSize() < 8) {
  383. errs() << ProgName
  384. << ": the 64-bit DWARF format is only supported for 64-bit "
  385. "targets\n";
  386. return 1;
  387. }
  388. // If needsDwarfSectionOffsetDirective is true, we would eventually call
  389. // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
  390. // is supported only for 4-byte long references.
  391. if (MAI->needsDwarfSectionOffsetDirective()) {
  392. errs() << ProgName << ": the 64-bit DWARF format is not supported for "
  393. << TheTriple.normalize() << "\n";
  394. return 1;
  395. }
  396. Ctx.setDwarfFormat(dwarf::DWARF64);
  397. }
  398. if (!DwarfDebugFlags.empty())
  399. Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
  400. if (!DwarfDebugProducer.empty())
  401. Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
  402. if (!DebugCompilationDir.empty())
  403. Ctx.setCompilationDir(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. for (const auto &Arg : DebugPrefixMap) {
  411. const auto &KV = StringRef(Arg).split('=');
  412. Ctx.addDebugPrefixMapEntry(std::string(KV.first), std::string(KV.second));
  413. }
  414. if (!MainFileName.empty())
  415. Ctx.setMainFileName(MainFileName);
  416. if (GenDwarfForAssembly)
  417. Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer());
  418. sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile)
  419. ? sys::fs::OF_TextWithCRLF
  420. : sys::fs::OF_None;
  421. std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags);
  422. if (!Out)
  423. return 1;
  424. std::unique_ptr<ToolOutputFile> DwoOut;
  425. if (!SplitDwarfFile.empty()) {
  426. if (FileType != OFT_ObjectFile) {
  427. WithColor::error() << "dwo output only supported with object files\n";
  428. return 1;
  429. }
  430. DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None);
  431. if (!DwoOut)
  432. return 1;
  433. }
  434. std::unique_ptr<buffer_ostream> BOS;
  435. raw_pwrite_stream *OS = &Out->os();
  436. std::unique_ptr<MCStreamer> Str;
  437. std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
  438. assert(MCII && "Unable to create instruction info!");
  439. MCInstPrinter *IP = nullptr;
  440. if (FileType == OFT_AssemblyFile) {
  441. IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
  442. *MAI, *MCII, *MRI);
  443. if (!IP) {
  444. WithColor::error()
  445. << "unable to create instruction printer for target triple '"
  446. << TheTriple.normalize() << "' with assembly variant "
  447. << OutputAsmVariant << ".\n";
  448. return 1;
  449. }
  450. for (StringRef Opt : DisassemblerOptions)
  451. if (!IP->applyTargetSpecificCLOption(Opt)) {
  452. WithColor::error() << "invalid disassembler option '" << Opt << "'\n";
  453. return 1;
  454. }
  455. // Set the display preference for hex vs. decimal immediates.
  456. IP->setPrintImmHex(PrintImmHex);
  457. // Set up the AsmStreamer.
  458. std::unique_ptr<MCCodeEmitter> CE;
  459. if (ShowEncoding)
  460. CE.reset(TheTarget->createMCCodeEmitter(*MCII, Ctx));
  461. std::unique_ptr<MCAsmBackend> MAB(
  462. TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
  463. auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
  464. Str.reset(
  465. TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
  466. /*useDwarfDirectory*/ true, IP,
  467. std::move(CE), std::move(MAB), ShowInst));
  468. } else if (FileType == OFT_Null) {
  469. Str.reset(TheTarget->createNullStreamer(Ctx));
  470. } else {
  471. assert(FileType == OFT_ObjectFile && "Invalid file type!");
  472. if (!Out->os().supportsSeeking()) {
  473. BOS = std::make_unique<buffer_ostream>(Out->os());
  474. OS = BOS.get();
  475. }
  476. MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, Ctx);
  477. MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
  478. Str.reset(TheTarget->createMCObjectStreamer(
  479. TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
  480. DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
  481. : MAB->createObjectWriter(*OS),
  482. std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
  483. MCOptions.MCIncrementalLinkerCompatible,
  484. /*DWARFMustBeAtTheEnd*/ false));
  485. if (NoExecStack)
  486. Str->initSections(true, *STI);
  487. }
  488. // Use Assembler information for parsing.
  489. Str->setUseAssemblerInfoForParsing(true);
  490. int Res = 1;
  491. bool disassemble = false;
  492. switch (Action) {
  493. case AC_AsLex:
  494. Res = AsLexInput(SrcMgr, *MAI, Out->os());
  495. break;
  496. case AC_Assemble:
  497. Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
  498. *MCII, MCOptions);
  499. break;
  500. case AC_MDisassemble:
  501. assert(IP && "Expected assembly output");
  502. IP->setUseMarkup(true);
  503. disassemble = true;
  504. break;
  505. case AC_Disassemble:
  506. disassemble = true;
  507. break;
  508. }
  509. if (disassemble)
  510. Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer,
  511. SrcMgr, Ctx, Out->os(), MCOptions);
  512. // Keep output if no errors.
  513. if (Res == 0) {
  514. Out->keep();
  515. if (DwoOut)
  516. DwoOut->keep();
  517. }
  518. return Res;
  519. }