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
14#include "Disassembler.h"
15#include "llvm/ADT/ScopeExit.h"
16#include "llvm/DWARFCFIChecker/DWARFCFIFunctionFrameAnalyzer.h"
17#include "llvm/DWARFCFIChecker/DWARFCFIFunctionFrameStreamer.h"
18#include "llvm/MC/MCAsmBackend.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCCodeEmitter.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCInstPrinter.h"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCLFI.h"
25#include "llvm/MC/MCObjectFileInfo.h"
26#include "llvm/MC/MCObjectWriter.h"
27#include "llvm/MC/MCParser/AsmLexer.h"
28#include "llvm/MC/MCParser/MCTargetAsmParser.h"
29#include "llvm/MC/MCRegisterInfo.h"
30#include "llvm/MC/MCStreamer.h"
31#include "llvm/MC/MCSubtargetInfo.h"
32#include "llvm/MC/MCTargetOptionsCommandFlags.h"
33#include "llvm/MC/TargetRegistry.h"
34#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Compression.h"
36#include "llvm/Support/FileUtilities.h"
37#include "llvm/Support/FormattedStream.h"
38#include "llvm/Support/InitLLVM.h"
39#include "llvm/Support/LibraryOptionsContext.h"
40#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/SourceMgr.h"
42#include "llvm/Support/TargetSelect.h"
43#include "llvm/Support/TimeProfiler.h"
44#include "llvm/Support/ToolOutputFile.h"
45#include "llvm/Support/VirtualFileSystem.h"
46#include "llvm/Support/WithColor.h"
47#include "llvm/TargetParser/Host.h"
48#include <memory>
49
50using namespace llvm;
51
52static mc::RegisterMCTargetOptionsFlags MOF;
53
54static cl::OptionCategory MCCategory("MC Options");
55
56static cl::opt<std::string> InputFilename(cl::Positional,
57 cl::desc("<input file>"),
58 cl::init(Val: "-"), cl::cat(MCCategory));
59
60static cl::list<std::string> InstPrinterOptions("M",
61 cl::desc("InstPrinter options"),
62 cl::cat(MCCategory));
63
64static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
65 cl::value_desc("filename"),
66 cl::init(Val: "-"), cl::cat(MCCategory));
67
68static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
69 cl::desc("DWO output filename"),
70 cl::value_desc("filename"),
71 cl::cat(MCCategory));
72
73static cl::opt<bool> ShowEncoding("show-encoding",
74 cl::desc("Show instruction encodings"),
75 cl::cat(MCCategory));
76
77static cl::opt<DebugCompressionType> CompressDebugSections(
78 "compress-debug-sections", cl::ValueOptional,
79 cl::init(Val: DebugCompressionType::None),
80 cl::desc("Choose DWARF debug sections compression:"),
81 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
82 clEnumValN(DebugCompressionType::Zlib, "zlib", "Use zlib"),
83 clEnumValN(DebugCompressionType::Zstd, "zstd", "Use zstd")),
84 cl::cat(MCCategory));
85
86static cl::opt<bool>
87 ShowInst("show-inst", cl::desc("Show internal instruction representation"),
88 cl::cat(MCCategory));
89
90static cl::opt<bool>
91 ShowInstOperands("show-inst-operands",
92 cl::desc("Show instructions operands as parsed"),
93 cl::cat(MCCategory));
94
95static cl::opt<unsigned>
96 OutputAsmVariant("output-asm-variant",
97 cl::desc("Syntax variant to use for output printing"),
98 cl::cat(MCCategory));
99
100static cl::opt<bool>
101 PrintImmHex("print-imm-hex", cl::init(Val: false),
102 cl::desc("Prefer hex format for immediate values"),
103 cl::cat(MCCategory));
104
105static cl::opt<bool>
106 HexBytes("hex",
107 cl::desc("Take raw hexadecimal bytes as input for disassembly. "
108 "Whitespace is ignored"),
109 cl::cat(MCCategory));
110
111static cl::list<std::string>
112 DefineSymbol("defsym",
113 cl::desc("Defines a symbol to be an integer constant"),
114 cl::cat(MCCategory));
115
116static cl::opt<bool>
117 PreserveComments("preserve-comments",
118 cl::desc("Preserve Comments in outputted assembly"),
119 cl::cat(MCCategory));
120
121static cl::opt<unsigned> CommentColumn("comment-column",
122 cl::desc("Asm comments indentation"),
123 cl::init(Val: 40));
124
125enum OutputFileType {
126 OFT_Null,
127 OFT_AssemblyFile,
128 OFT_ObjectFile
129};
130static cl::opt<OutputFileType>
131 FileType("filetype", cl::init(Val: OFT_AssemblyFile),
132 cl::desc("Choose an output file type:"),
133 cl::values(clEnumValN(OFT_AssemblyFile, "asm",
134 "Emit an assembly ('.s') file"),
135 clEnumValN(OFT_Null, "null",
136 "Don't emit anything (for timing purposes)"),
137 clEnumValN(OFT_ObjectFile, "obj",
138 "Emit a native object ('.o') file")),
139 cl::cat(MCCategory));
140
141static cl::list<std::string> IncludeDirs("I",
142 cl::desc("Directory of include files"),
143 cl::value_desc("directory"),
144 cl::Prefix, cl::cat(MCCategory));
145
146static cl::opt<std::string>
147 ArchName("arch",
148 cl::desc("Target arch to assemble for, "
149 "see -version for available targets"),
150 cl::cat(MCCategory));
151
152static cl::opt<std::string>
153 TripleName("triple",
154 cl::desc("Target triple to assemble for, "
155 "see -version for available targets"),
156 cl::cat(MCCategory));
157
158static cl::opt<std::string>
159 MCPU("mcpu",
160 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
161 cl::value_desc("cpu-name"), cl::init(Val: ""), cl::cat(MCCategory));
162
163static cl::list<std::string>
164 MAttrs("mattr", cl::CommaSeparated,
165 cl::desc("Target specific attributes (-mattr=help for details)"),
166 cl::value_desc("a1,+a2,-a3,..."), cl::cat(MCCategory));
167
168static cl::opt<bool> PIC("position-independent",
169 cl::desc("Position independent"), cl::init(Val: false),
170 cl::cat(MCCategory));
171
172static cl::opt<bool>
173 LargeCodeModel("large-code-model",
174 cl::desc("Create cfi directives that assume the code might "
175 "be more than 2gb away"),
176 cl::cat(MCCategory));
177
178static cl::opt<bool>
179 NoInitialTextSection("n",
180 cl::desc("Don't assume assembly file starts "
181 "in the text section"),
182 cl::cat(MCCategory));
183
184static cl::opt<bool>
185 GenDwarfForAssembly("g",
186 cl::desc("Generate dwarf debugging info for assembly "
187 "source files"),
188 cl::cat(MCCategory));
189
190static cl::opt<std::string>
191 DebugCompilationDir("fdebug-compilation-dir",
192 cl::desc("Specifies the debug info's compilation dir"),
193 cl::cat(MCCategory));
194
195static cl::list<std::string> DebugPrefixMap(
196 "fdebug-prefix-map", cl::desc("Map file source paths in debug info"),
197 cl::value_desc("= separated key-value pairs"), cl::cat(MCCategory));
198
199static cl::opt<std::string> MainFileName(
200 "main-file-name",
201 cl::desc("Specifies the name we should consider the input file"),
202 cl::cat(MCCategory));
203
204static cl::opt<bool> LexMasmIntegers(
205 "masm-integers",
206 cl::desc("Enable binary and hex masm integers (0b110 and 0ABCh)"),
207 cl::cat(MCCategory));
208
209static cl::opt<bool> LexMasmHexFloats(
210 "masm-hexfloats",
211 cl::desc("Enable MASM-style hex float initializers (3F800000r)"),
212 cl::cat(MCCategory));
213
214static cl::opt<bool> LexMotorolaIntegers(
215 "motorola-integers",
216 cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)"),
217 cl::cat(MCCategory));
218
219static cl::opt<bool> NoExecStack("no-exec-stack",
220 cl::desc("File doesn't need an exec stack"),
221 cl::cat(MCCategory));
222
223static cl::opt<bool> ValidateCFI("validate-cfi",
224 cl::desc("Validate the CFI directives"),
225 cl::cat(MCCategory));
226
227enum ActionType {
228 AC_AsLex,
229 AC_Assemble,
230 AC_Disassemble,
231 AC_MDisassemble,
232 AC_CDisassemble,
233};
234
235static cl::opt<ActionType> Action(
236 cl::desc("Action to perform:"), cl::init(Val: AC_Assemble),
237 cl::values(clEnumValN(AC_AsLex, "as-lex", "Lex tokens from a .s file"),
238 clEnumValN(AC_Assemble, "assemble",
239 "Assemble a .s file (default)"),
240 clEnumValN(AC_Disassemble, "disassemble",
241 "Disassemble strings of hex bytes"),
242 clEnumValN(AC_MDisassemble, "mdis",
243 "Marked up disassembly of strings of hex bytes"),
244 clEnumValN(AC_CDisassemble, "cdis",
245 "Colored disassembly of strings of hex bytes")),
246 cl::cat(MCCategory));
247
248static cl::opt<unsigned>
249 NumBenchmarkRuns("runs", cl::desc("Number of runs for benchmarking"),
250 cl::cat(MCCategory));
251
252static cl::opt<bool> TimeTrace("time-trace", cl::desc("Record time trace"));
253
254static cl::opt<unsigned> TimeTraceGranularity(
255 "time-trace-granularity",
256 cl::desc(
257 "Minimum time granularity (in microseconds) traced by time profiler"),
258 cl::init(Val: 500), cl::Hidden);
259
260static cl::opt<std::string>
261 TimeTraceFile("time-trace-file",
262 cl::desc("Specify time trace file destination"),
263 cl::value_desc("filename"));
264
265static const Target *GetTarget(const char *ProgName) {
266 // Figure out the target triple.
267 if (TripleName.empty())
268 TripleName = sys::getDefaultTargetTriple();
269 Triple TheTriple(Triple::normalize(Str: TripleName));
270
271 // Get the target specific parser.
272 std::string Error;
273 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
274 Error);
275 if (!TheTarget) {
276 WithColor::error(OS&: errs(), Prefix: ProgName) << Error;
277 return nullptr;
278 }
279
280 // Update the triple name and return the found target.
281 TripleName = TheTriple.getTriple();
282 return TheTarget;
283}
284
285static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path,
286 sys::fs::OpenFlags Flags) {
287 std::error_code EC;
288 auto Out = std::make_unique<ToolOutputFile>(args&: Path, args&: EC, args&: Flags);
289 if (EC) {
290 WithColor::error() << EC.message() << '\n';
291 return nullptr;
292 }
293
294 return Out;
295}
296
297static std::string DwarfDebugFlags;
298static void setDwarfDebugFlags(int argc, char **argv) {
299 if (!getenv(name: "RC_DEBUG_OPTIONS"))
300 return;
301 for (int i = 0; i < argc; i++) {
302 DwarfDebugFlags += argv[i];
303 if (i + 1 < argc)
304 DwarfDebugFlags += " ";
305 }
306}
307
308static std::string DwarfDebugProducer;
309static void setDwarfDebugProducer() {
310 if(!getenv(name: "DEBUG_PRODUCER"))
311 return;
312 DwarfDebugProducer += getenv(name: "DEBUG_PRODUCER");
313}
314
315static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
316 raw_ostream &OS) {
317
318 AsmLexer Lexer(MAI);
319 Lexer.setBuffer(Buf: SrcMgr.getMemoryBuffer(i: SrcMgr.getMainFileID())->getBuffer());
320
321 bool Error = false;
322 while (Lexer.Lex().isNot(K: AsmToken::Eof)) {
323 Lexer.getTok().dump(OS);
324 OS << "\n";
325 if (Lexer.getTok().getKind() == AsmToken::Error)
326 Error = true;
327 }
328
329 return Error;
330}
331
332static int fillCommandLineSymbols(MCAsmParser &Parser) {
333 for (auto &I: DefineSymbol) {
334 auto Pair = StringRef(I).split(Separator: '=');
335 auto Sym = Pair.first;
336 auto Val = Pair.second;
337
338 if (Sym.empty() || Val.empty()) {
339 WithColor::error() << "defsym must be of the form: sym=value: " << I
340 << "\n";
341 return 1;
342 }
343 int64_t Value;
344 if (Val.getAsInteger(Radix: 0, Result&: Value)) {
345 WithColor::error() << "value is not an integer: " << Val << "\n";
346 return 1;
347 }
348 Parser.getContext().setSymbolValue(Streamer&: Parser.getStreamer(), Sym, Val: Value);
349 }
350 return 0;
351}
352
353static int AssembleInput(const char *ProgName, const Target *TheTarget,
354 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
355 MCAsmInfo &MAI, MCSubtargetInfo &STI,
356 MCInstrInfo &MCII, MCTargetOptions const &MCOptions) {
357 std::unique_ptr<MCAsmParser> Parser(
358 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
359 std::unique_ptr<MCTargetAsmParser> TAP(
360 TheTarget->createMCAsmParser(STI, Parser&: *Parser, MII: MCII));
361
362 if (!TAP) {
363 WithColor::error(OS&: errs(), Prefix: ProgName)
364 << "this target does not support assembly parsing.\n";
365 return 1;
366 }
367
368 int SymbolResult = fillCommandLineSymbols(Parser&: *Parser);
369 if(SymbolResult)
370 return SymbolResult;
371 Parser->setShowParsedOperands(ShowInstOperands);
372 Parser->setTargetParser(*TAP);
373 Parser->getLexer().setLexMasmIntegers(LexMasmIntegers);
374 Parser->getLexer().setLexMasmHexFloats(LexMasmHexFloats);
375 Parser->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers);
376
377 int Res = Parser->Run(NoInitialTextSection);
378
379 return Res;
380}
381
382int main(int argc, char **argv) {
383 InitLLVM X(argc, argv);
384
385 // Initialize targets and assembly printers/parsers.
386 llvm::InitializeAllTargetInfos();
387 llvm::InitializeAllTargetMCs();
388 llvm::InitializeAllAsmParsers();
389 llvm::InitializeAllDisassemblers();
390
391 // Register the target printer for --version.
392 cl::AddExtraVersionPrinter(func: TargetRegistry::printRegisteredTargetsForVersion);
393
394 cl::HideUnrelatedOptions(Categories: {&MCCategory, &getColorCategory()});
395 cl::LibraryOptionsContext LibraryOptions;
396 cl::parseCommandLineOptions(Context&: LibraryOptions, Args: ArrayRef(argv, argc),
397 Overview: "llvm machine code playground\n");
398
399 if (TimeTrace)
400 timeTraceProfilerInitialize(TimeTraceGranularity, ProcName: argv[0]);
401
402 llvm::scope_exit TimeTraceScopeExit([]() {
403 if (!TimeTrace)
404 return;
405 if (auto E = timeTraceProfilerWrite(PreferredFileName: TimeTraceFile, FallbackFileName: OutputFilename)) {
406 logAllUnhandledErrors(E: std::move(E), OS&: errs());
407 return;
408 }
409 timeTraceProfilerCleanup();
410 });
411
412 MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
413 MCOptions.LibraryOptions = &LibraryOptions;
414 MCOptions.CompressDebugSections = CompressDebugSections.getValue();
415 MCOptions.ShowMCInst = ShowInst;
416 MCOptions.AsmVerbose = true;
417 MCOptions.MCNoExecStack = NoExecStack;
418 MCOptions.MCUseDwarfDirectory = MCTargetOptions::EnableDwarfDirectory;
419 MCOptions.InstPrinterOptions = InstPrinterOptions;
420 if (OutputAsmVariant.getNumOccurrences())
421 MCOptions.OutputAsmVariant = OutputAsmVariant;
422
423 setDwarfDebugFlags(argc, argv);
424 setDwarfDebugProducer();
425
426 const char *ProgName = argv[0];
427 const Target *TheTarget = GetTarget(ProgName);
428 if (!TheTarget)
429 return 1;
430 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
431 // construct the Triple object.
432 Triple TheTriple(TripleName);
433
434 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
435 MemoryBuffer::getFileOrSTDIN(Filename: InputFilename, /*IsText=*/true);
436 if (std::error_code EC = BufferPtr.getError()) {
437 WithColor::error(OS&: errs(), Prefix: ProgName)
438 << InputFilename << ": " << EC.message() << '\n';
439 return 1;
440 }
441 MemoryBuffer *Buffer = BufferPtr->get();
442
443 SourceMgr SrcMgr;
444
445 // Tell SrcMgr about this buffer, which is what the parser will pick up.
446 SrcMgr.AddNewSourceBuffer(F: std::move(*BufferPtr), IncludeLoc: SMLoc());
447
448 // Record the location of the include directories so that the lexer can find
449 // it later.
450 SrcMgr.setIncludeDirs(IncludeDirs);
451 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
452
453 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TheTriple));
454 assert(MRI && "Unable to create target register info!");
455
456 std::unique_ptr<MCAsmInfo> MAI(
457 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
458 assert(MAI && "Unable to create target asm info!");
459
460 if (CompressDebugSections != DebugCompressionType::None) {
461 if (const char *Reason = compression::getReasonIfUnsupported(
462 F: compression::formatFor(Type: CompressDebugSections))) {
463 WithColor::error(OS&: errs(), Prefix: ProgName)
464 << "--compress-debug-sections: " << Reason;
465 return 1;
466 }
467 }
468 MAI->setPreserveAsmComments(PreserveComments);
469 MAI->setCommentColumn(CommentColumn);
470
471 // Package up features to be passed to target/subtarget
472 SubtargetFeatures Features;
473 std::string FeaturesStr;
474
475 // Replace -mcpu=native with Host CPU and features.
476 if (MCPU == "native") {
477 MCPU = std::string(llvm::sys::getHostCPUName());
478
479 llvm::StringMap<bool> TargetFeatures = llvm::sys::getHostCPUFeatures();
480 for (auto const &[FeatureName, IsSupported] : TargetFeatures)
481 Features.AddFeature(String: FeatureName, Enable: IsSupported);
482 }
483
484 // Handle features passed to target/subtarget.
485 for (unsigned i = 0; i != MAttrs.size(); ++i)
486 Features.AddFeature(String: MAttrs[i]);
487 FeaturesStr = Features.getString();
488
489 std::unique_ptr<MCSubtargetInfo> STI(
490 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU, Features: FeaturesStr));
491 if (!STI) {
492 WithColor::error(OS&: errs(), Prefix: ProgName) << "unable to create subtarget info\n";
493 return 1;
494 }
495
496 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
497 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
498 MCContext Ctx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
499 std::unique_ptr<MCObjectFileInfo> MOFI(
500 TheTarget->createMCObjectFileInfo(Ctx, PIC, LargeCodeModel));
501 Ctx.setObjectFileInfo(MOFI.get());
502
503 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
504 // Default to 4 for dwarf version.
505 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
506 if (DwarfVersion < 2 || DwarfVersion > 6) {
507 errs() << ProgName << ": Dwarf version " << DwarfVersion
508 << " is not supported." << '\n';
509 return 1;
510 }
511 Ctx.setDwarfVersion(DwarfVersion);
512 if (MCOptions.Dwarf64) {
513 // The 64-bit DWARF format was introduced in DWARFv3.
514 if (DwarfVersion < 3) {
515 errs() << ProgName
516 << ": the 64-bit DWARF format is not supported for DWARF versions "
517 "prior to 3\n";
518 return 1;
519 }
520 // 32-bit targets don't support DWARF64, which requires 64-bit relocations.
521 if (MAI->getCodePointerSize() < 8) {
522 errs() << ProgName
523 << ": the 64-bit DWARF format is only supported for 64-bit "
524 "targets\n";
525 return 1;
526 }
527 // If needsDwarfSectionOffsetDirective is true, we would eventually call
528 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that
529 // is supported only for 4-byte long references.
530 if (MAI->needsDwarfSectionOffsetDirective()) {
531 errs() << ProgName << ": the 64-bit DWARF format is not supported for "
532 << TheTriple.normalize() << "\n";
533 return 1;
534 }
535 Ctx.setDwarfFormat(dwarf::DWARF64);
536 }
537 if (!DwarfDebugFlags.empty())
538 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
539 if (!DwarfDebugProducer.empty())
540 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
541 if (!DebugCompilationDir.empty())
542 Ctx.setCompilationDir(DebugCompilationDir);
543 else {
544 // If no compilation dir is set, try to use the current directory.
545 SmallString<128> CWD;
546 if (!sys::fs::current_path(result&: CWD))
547 Ctx.setCompilationDir(CWD);
548 }
549 for (const auto &Arg : DebugPrefixMap) {
550 const auto &KV = StringRef(Arg).split(Separator: '=');
551 Ctx.addDebugPrefixMapEntry(From: std::string(KV.first), To: std::string(KV.second));
552 }
553 if (!MainFileName.empty())
554 Ctx.setMainFileName(MainFileName);
555 if (GenDwarfForAssembly)
556 Ctx.setGenDwarfRootFile(FileName: InputFilename, Buffer: Buffer->getBuffer());
557
558 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile)
559 ? sys::fs::OF_TextWithCRLF
560 : sys::fs::OF_None;
561 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(Path: OutputFilename, Flags);
562 if (!Out)
563 return 1;
564
565 std::unique_ptr<ToolOutputFile> DwoOut;
566 if (!SplitDwarfFile.empty()) {
567 if (FileType != OFT_ObjectFile) {
568 WithColor::error() << "dwo output only supported with object files\n";
569 return 1;
570 }
571 DwoOut = GetOutputStream(Path: SplitDwarfFile, Flags: sys::fs::OF_None);
572 if (!DwoOut)
573 return 1;
574 }
575
576 std::unique_ptr<buffer_ostream> BOS;
577 raw_pwrite_stream *OS = &Out->os();
578 std::unique_ptr<MCStreamer> Str;
579
580 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
581 assert(MCII && "Unable to create instruction info!");
582
583 std::unique_ptr<MCInstPrinter> IP;
584 if (ValidateCFI) {
585 // TODO: The DWARF CFI checker support for emitting anything other than
586 // errors and warnings has not been implemented yet. Because of this, it is
587 // assert-checked that the filetype output is null.
588 assert(FileType == OFT_Null);
589 auto FFA = std::make_unique<CFIFunctionFrameAnalyzer>(args&: Ctx, args&: *MCII);
590 auto FFS = std::make_unique<CFIFunctionFrameStreamer>(args&: Ctx, args: std::move(FFA));
591 TheTarget->createNullTargetStreamer(S&: *FFS);
592 Str = std::move(FFS);
593 } else if (FileType == OFT_AssemblyFile) {
594 unsigned AsmVariant = MAI->getOutputAssemblerDialect();
595 IP.reset(p: TheTarget->createMCInstPrinter(T: Triple(TripleName), SyntaxVariant: AsmVariant,
596 MAI: *MAI, MII: *MCII, MRI: *MRI));
597
598 if (!IP) {
599 WithColor::error()
600 << "unable to create instruction printer for target triple '"
601 << TheTriple.normalize() << "' with assembly variant " << AsmVariant
602 << "\n";
603 return 1;
604 }
605
606 for (StringRef Opt : InstPrinterOptions)
607 if (!IP->applyTargetSpecificCLOption(Opt)) {
608 WithColor::error() << "invalid InstPrinter option '" << Opt << "'\n";
609 return 1;
610 }
611
612 // Set the display preference for hex vs. decimal immediates.
613 IP->setPrintImmHex(PrintImmHex);
614
615 switch (Action) {
616 case AC_MDisassemble:
617 IP->setUseMarkup(true);
618 break;
619 case AC_CDisassemble:
620 IP->setUseColor(true);
621 break;
622 default:
623 break;
624 }
625
626 // Set up the AsmStreamer.
627 std::unique_ptr<MCCodeEmitter> CE;
628 if (ShowEncoding)
629 CE.reset(p: TheTarget->createMCCodeEmitter(II: *MCII, Ctx));
630
631 std::unique_ptr<MCAsmBackend> MAB(
632 TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions));
633 auto FOut = std::make_unique<formatted_raw_ostream>(args&: *OS);
634 Str.reset(p: TheTarget->createAsmStreamer(Ctx, OS: std::move(FOut), IP: std::move(IP),
635 CE: std::move(CE), TAB: std::move(MAB)));
636
637 Triple T(TripleName);
638 if (T.isLFI())
639 initializeLFIMCStreamer(Streamer&: *Str.get(), Ctx, TheTriple: T);
640 } else if (FileType == OFT_Null) {
641 Str.reset(p: TheTarget->createNullStreamer(Ctx));
642 } else {
643 assert(FileType == OFT_ObjectFile && "Invalid file type!");
644
645 if (!Out->os().supportsSeeking()) {
646 BOS = std::make_unique<buffer_ostream>(args&: Out->os());
647 OS = BOS.get();
648 }
649
650 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(II: *MCII, Ctx);
651 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions);
652 Str.reset(p: TheTarget->createMCObjectStreamer(
653 T: TheTriple, Ctx, TAB: std::unique_ptr<MCAsmBackend>(MAB),
654 OW: DwoOut ? MAB->createDwoObjectWriter(OS&: *OS, DwoOS&: DwoOut->os())
655 : MAB->createObjectWriter(OS&: *OS),
656 Emitter: std::unique_ptr<MCCodeEmitter>(CE), STI: *STI));
657 Str->emitVersionForTarget(Target: TheTriple, SDKVersion: VersionTuple(), DarwinTargetVariantTriple: nullptr,
658 DarwinTargetVariantSDKVersion: VersionTuple());
659 }
660
661 int Res = 1;
662 bool disassemble = false;
663 switch (Action) {
664 case AC_AsLex:
665 Res = AsLexInput(SrcMgr, MAI&: *MAI, OS&: Out->os());
666 break;
667 case AC_Assemble:
668 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str&: *Str, MAI&: *MAI, STI&: *STI,
669 MCII&: *MCII, MCOptions);
670 break;
671 case AC_MDisassemble:
672 case AC_CDisassemble:
673 case AC_Disassemble:
674 disassemble = true;
675 break;
676 }
677 if (disassemble)
678 Res = Disassembler::disassemble(T: *TheTarget, STI&: *STI, Streamer&: *Str, Buffer&: *Buffer, SM&: SrcMgr,
679 Ctx, HexBytes, NumBenchmarkRuns);
680
681 // Keep output if no errors.
682 if (Res == 0) {
683 Out->keep();
684 if (DwoOut)
685 DwoOut->keep();
686 }
687
688 return Res;
689}
690