xref: /llvm-project/llvm/tools/llvm-mc/llvm-mc.cpp (revision 3feeb9c851a193f42d890b35f36816fae198860f)
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "Disassembler.h"
16 #include "llvm/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.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/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.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/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.h"
42 
43 using namespace llvm;
44 
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47 
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50                cl::value_desc("filename"));
51 
52 static cl::opt<bool>
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54 
55 static cl::opt<bool> RelaxELFRel(
56     "relax-relocations", cl::init(true),
57     cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
58 
59 static cl::opt<DebugCompressionType>
60 CompressDebugSections("compress-debug-sections", cl::ValueOptional,
61   cl::init(DebugCompressionType::DCT_None),
62   cl::desc("Choose DWARF debug sections compression:"),
63   cl::values(
64     clEnumValN(DebugCompressionType::DCT_None, "none",
65       "No compression"),
66     clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
67       "Use zlib compression"),
68     clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
69       "Use zlib-gnu compression (depricated)"),
70     clEnumValEnd));
71 
72 static cl::opt<bool>
73 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
74 
75 static cl::opt<bool>
76 ShowInstOperands("show-inst-operands",
77                  cl::desc("Show instructions operands as parsed"));
78 
79 static cl::opt<unsigned>
80 OutputAsmVariant("output-asm-variant",
81                  cl::desc("Syntax variant to use for output printing"));
82 
83 static cl::opt<bool>
84 PrintImmHex("print-imm-hex", cl::init(false),
85             cl::desc("Prefer hex format for immediate values"));
86 
87 static cl::list<std::string>
88 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
89 
90 static cl::opt<bool>
91     PreserveComments("preserve-comments",
92                      cl::desc("Preserve Comments in outputted assembly"));
93 
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(
103        clEnumValN(OFT_AssemblyFile, "asm",
104                   "Emit an assembly ('.s') file"),
105        clEnumValN(OFT_Null, "null",
106                   "Don't emit anything (for timing purposes)"),
107        clEnumValN(OFT_ObjectFile, "obj",
108                   "Emit a native object ('.o') file"),
109        clEnumValEnd));
110 
111 static cl::list<std::string>
112 IncludeDirs("I", cl::desc("Directory of include files"),
113             cl::value_desc("directory"), cl::Prefix);
114 
115 static cl::opt<std::string>
116 ArchName("arch", cl::desc("Target arch to assemble for, "
117                           "see -version for available targets"));
118 
119 static cl::opt<std::string>
120 TripleName("triple", cl::desc("Target triple to assemble for, "
121                               "see -version for available targets"));
122 
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"),
127      cl::init(""));
128 
129 static cl::list<std::string>
130 MAttrs("mattr",
131   cl::CommaSeparated,
132   cl::desc("Target specific attributes (-mattr=help for details)"),
133   cl::value_desc("a1,+a2,-a3,..."));
134 
135 static cl::opt<bool> PIC("position-independent",
136                          cl::desc("Position independent"), cl::init(false));
137 
138 static cl::opt<llvm::CodeModel::Model>
139 CMModel("code-model",
140         cl::desc("Choose code model"),
141         cl::init(CodeModel::Default),
142         cl::values(clEnumValN(CodeModel::Default, "default",
143                               "Target default code model"),
144                    clEnumValN(CodeModel::Small, "small",
145                               "Small code model"),
146                    clEnumValN(CodeModel::Kernel, "kernel",
147                               "Kernel code model"),
148                    clEnumValN(CodeModel::Medium, "medium",
149                               "Medium code model"),
150                    clEnumValN(CodeModel::Large, "large",
151                               "Large code model"),
152                    clEnumValEnd));
153 
154 static cl::opt<bool>
155 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
156                                    "in the text section"));
157 
158 static cl::opt<bool>
159 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
160                                   "source files"));
161 
162 static cl::opt<std::string>
163 DebugCompilationDir("fdebug-compilation-dir",
164                     cl::desc("Specifies the debug info's compilation dir"));
165 
166 static cl::opt<std::string>
167 MainFileName("main-file-name",
168              cl::desc("Specifies the name we should consider the input file"));
169 
170 static cl::opt<bool> SaveTempLabels("save-temp-labels",
171                                     cl::desc("Don't discard temporary labels"));
172 
173 static cl::opt<bool> NoExecStack("no-exec-stack",
174                                  cl::desc("File doesn't need an exec stack"));
175 
176 enum ActionType {
177   AC_AsLex,
178   AC_Assemble,
179   AC_Disassemble,
180   AC_MDisassemble,
181 };
182 
183 static cl::opt<ActionType>
184 Action(cl::desc("Action to perform:"),
185        cl::init(AC_Assemble),
186        cl::values(clEnumValN(AC_AsLex, "as-lex",
187                              "Lex tokens from a .s file"),
188                   clEnumValN(AC_Assemble, "assemble",
189                              "Assemble a .s file (default)"),
190                   clEnumValN(AC_Disassemble, "disassemble",
191                              "Disassemble strings of hex bytes"),
192                   clEnumValN(AC_MDisassemble, "mdis",
193                              "Marked up disassembly of strings of hex bytes"),
194                   clEnumValEnd));
195 
196 static const Target *GetTarget(const char *ProgName) {
197   // Figure out the target triple.
198   if (TripleName.empty())
199     TripleName = sys::getDefaultTargetTriple();
200   Triple TheTriple(Triple::normalize(TripleName));
201 
202   // Get the target specific parser.
203   std::string Error;
204   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
205                                                          Error);
206   if (!TheTarget) {
207     errs() << ProgName << ": " << Error;
208     return nullptr;
209   }
210 
211   // Update the triple name and return the found target.
212   TripleName = TheTriple.getTriple();
213   return TheTarget;
214 }
215 
216 static std::unique_ptr<tool_output_file> GetOutputStream() {
217   if (OutputFilename == "")
218     OutputFilename = "-";
219 
220   std::error_code EC;
221   auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
222                                                  sys::fs::F_None);
223   if (EC) {
224     errs() << EC.message() << '\n';
225     return nullptr;
226   }
227 
228   return Out;
229 }
230 
231 static std::string DwarfDebugFlags;
232 static void setDwarfDebugFlags(int argc, char **argv) {
233   if (!getenv("RC_DEBUG_OPTIONS"))
234     return;
235   for (int i = 0; i < argc; i++) {
236     DwarfDebugFlags += argv[i];
237     if (i + 1 < argc)
238       DwarfDebugFlags += " ";
239   }
240 }
241 
242 static std::string DwarfDebugProducer;
243 static void setDwarfDebugProducer() {
244   if(!getenv("DEBUG_PRODUCER"))
245     return;
246   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
247 }
248 
249 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
250                       raw_ostream &OS) {
251 
252   AsmLexer Lexer(MAI);
253   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
254 
255   bool Error = false;
256   while (Lexer.Lex().isNot(AsmToken::Eof)) {
257     const AsmToken &Tok = Lexer.getTok();
258 
259     switch (Tok.getKind()) {
260     default:
261       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
262                           "unknown token");
263       Error = true;
264       break;
265     case AsmToken::Error:
266       Error = true; // error already printed.
267       break;
268     case AsmToken::Identifier:
269       OS << "identifier: " << Lexer.getTok().getString();
270       break;
271     case AsmToken::Integer:
272       OS << "int: " << Lexer.getTok().getString();
273       break;
274     case AsmToken::Real:
275       OS << "real: " << Lexer.getTok().getString();
276       break;
277     case AsmToken::String:
278       OS << "string: " << Lexer.getTok().getString();
279       break;
280 
281     case AsmToken::Amp:            OS << "Amp"; break;
282     case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
283     case AsmToken::At:             OS << "At"; break;
284     case AsmToken::Caret:          OS << "Caret"; break;
285     case AsmToken::Colon:          OS << "Colon"; break;
286     case AsmToken::Comma:          OS << "Comma"; break;
287     case AsmToken::Dollar:         OS << "Dollar"; break;
288     case AsmToken::Dot:            OS << "Dot"; break;
289     case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
290     case AsmToken::Eof:            OS << "Eof"; break;
291     case AsmToken::Equal:          OS << "Equal"; break;
292     case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
293     case AsmToken::Exclaim:        OS << "Exclaim"; break;
294     case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
295     case AsmToken::Greater:        OS << "Greater"; break;
296     case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
297     case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
298     case AsmToken::Hash:           OS << "Hash"; break;
299     case AsmToken::LBrac:          OS << "LBrac"; break;
300     case AsmToken::LCurly:         OS << "LCurly"; break;
301     case AsmToken::LParen:         OS << "LParen"; break;
302     case AsmToken::Less:           OS << "Less"; break;
303     case AsmToken::LessEqual:      OS << "LessEqual"; break;
304     case AsmToken::LessGreater:    OS << "LessGreater"; break;
305     case AsmToken::LessLess:       OS << "LessLess"; break;
306     case AsmToken::Minus:          OS << "Minus"; break;
307     case AsmToken::Percent:        OS << "Percent"; break;
308     case AsmToken::Pipe:           OS << "Pipe"; break;
309     case AsmToken::PipePipe:       OS << "PipePipe"; break;
310     case AsmToken::Plus:           OS << "Plus"; break;
311     case AsmToken::RBrac:          OS << "RBrac"; break;
312     case AsmToken::RCurly:         OS << "RCurly"; break;
313     case AsmToken::RParen:         OS << "RParen"; break;
314     case AsmToken::Slash:          OS << "Slash"; break;
315     case AsmToken::Star:           OS << "Star"; break;
316     case AsmToken::Tilde:          OS << "Tilde"; break;
317     case AsmToken::PercentCall16:
318       OS << "PercentCall16";
319       break;
320     case AsmToken::PercentCall_Hi:
321       OS << "PercentCall_Hi";
322       break;
323     case AsmToken::PercentCall_Lo:
324       OS << "PercentCall_Lo";
325       break;
326     case AsmToken::PercentDtprel_Hi:
327       OS << "PercentDtprel_Hi";
328       break;
329     case AsmToken::PercentDtprel_Lo:
330       OS << "PercentDtprel_Lo";
331       break;
332     case AsmToken::PercentGot:
333       OS << "PercentGot";
334       break;
335     case AsmToken::PercentGot_Disp:
336       OS << "PercentGot_Disp";
337       break;
338     case AsmToken::PercentGot_Hi:
339       OS << "PercentGot_Hi";
340       break;
341     case AsmToken::PercentGot_Lo:
342       OS << "PercentGot_Lo";
343       break;
344     case AsmToken::PercentGot_Ofst:
345       OS << "PercentGot_Ofst";
346       break;
347     case AsmToken::PercentGot_Page:
348       OS << "PercentGot_Page";
349       break;
350     case AsmToken::PercentGottprel:
351       OS << "PercentGottprel";
352       break;
353     case AsmToken::PercentGp_Rel:
354       OS << "PercentGp_Rel";
355       break;
356     case AsmToken::PercentHi:
357       OS << "PercentHi";
358       break;
359     case AsmToken::PercentHigher:
360       OS << "PercentHigher";
361       break;
362     case AsmToken::PercentHighest:
363       OS << "PercentHighest";
364       break;
365     case AsmToken::PercentLo:
366       OS << "PercentLo";
367       break;
368     case AsmToken::PercentNeg:
369       OS << "PercentNeg";
370       break;
371     case AsmToken::PercentPcrel_Hi:
372       OS << "PercentPcrel_Hi";
373       break;
374     case AsmToken::PercentPcrel_Lo:
375       OS << "PercentPcrel_Lo";
376       break;
377     case AsmToken::PercentTlsgd:
378       OS << "PercentTlsgd";
379       break;
380     case AsmToken::PercentTlsldm:
381       OS << "PercentTlsldm";
382       break;
383     case AsmToken::PercentTprel_Hi:
384       OS << "PercentTprel_Hi";
385       break;
386     case AsmToken::PercentTprel_Lo:
387       OS << "PercentTprel_Lo";
388       break;
389     }
390 
391     // Print the token string.
392     OS << " (\"";
393     OS.write_escaped(Tok.getString());
394     OS << "\")\n";
395   }
396 
397   return Error;
398 }
399 
400 static int fillCommandLineSymbols(MCAsmParser &Parser){
401   for(auto &I: DefineSymbol){
402     auto Pair = StringRef(I).split('=');
403     if(Pair.second.empty()){
404       errs() << "error: defsym must be of the form: sym=value: " << I;
405       return 1;
406     }
407     int64_t Value;
408     if(Pair.second.getAsInteger(0, Value)){
409       errs() << "error: Value is not an integer: " << Pair.second;
410       return 1;
411     }
412     auto &Context = Parser.getContext();
413     auto Symbol = Context.getOrCreateSymbol(Pair.first);
414     Parser.getStreamer().EmitAssignment(Symbol,
415                                         MCConstantExpr::create(Value, Context));
416   }
417   return 0;
418 }
419 
420 static int AssembleInput(const char *ProgName, const Target *TheTarget,
421                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
422                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
423                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
424   std::unique_ptr<MCAsmParser> Parser(
425       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
426   std::unique_ptr<MCTargetAsmParser> TAP(
427       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
428 
429   if (!TAP) {
430     errs() << ProgName
431            << ": error: this target does not support assembly parsing.\n";
432     return 1;
433   }
434 
435   int SymbolResult = fillCommandLineSymbols(*Parser);
436   if(SymbolResult)
437     return SymbolResult;
438   Parser->setShowParsedOperands(ShowInstOperands);
439   Parser->setTargetParser(*TAP);
440 
441   int Res = Parser->Run(NoInitialTextSection);
442 
443   return Res;
444 }
445 
446 int main(int argc, char **argv) {
447   // Print a stack trace if we signal out.
448   sys::PrintStackTraceOnErrorSignal(argv[0]);
449   PrettyStackTraceProgram X(argc, argv);
450   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
451 
452   // Initialize targets and assembly printers/parsers.
453   llvm::InitializeAllTargetInfos();
454   llvm::InitializeAllTargetMCs();
455   llvm::InitializeAllAsmParsers();
456   llvm::InitializeAllDisassemblers();
457 
458   // Register the target printer for --version.
459   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
460 
461   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
462   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
463   TripleName = Triple::normalize(TripleName);
464   setDwarfDebugFlags(argc, argv);
465 
466   setDwarfDebugProducer();
467 
468   const char *ProgName = argv[0];
469   const Target *TheTarget = GetTarget(ProgName);
470   if (!TheTarget)
471     return 1;
472   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
473   // construct the Triple object.
474   Triple TheTriple(TripleName);
475 
476   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
477       MemoryBuffer::getFileOrSTDIN(InputFilename);
478   if (std::error_code EC = BufferPtr.getError()) {
479     errs() << InputFilename << ": " << EC.message() << '\n';
480     return 1;
481   }
482   MemoryBuffer *Buffer = BufferPtr->get();
483 
484   SourceMgr SrcMgr;
485 
486   // Tell SrcMgr about this buffer, which is what the parser will pick up.
487   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
488 
489   // Record the location of the include directories so that the lexer can find
490   // it later.
491   SrcMgr.setIncludeDirs(IncludeDirs);
492 
493   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
494   assert(MRI && "Unable to create target register info!");
495 
496   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
497   assert(MAI && "Unable to create target asm info!");
498 
499   MAI->setRelaxELFRelocations(RelaxELFRel);
500 
501   if (CompressDebugSections != DebugCompressionType::DCT_None) {
502     if (!zlib::isAvailable()) {
503       errs() << ProgName
504              << ": build tools with zlib to enable -compress-debug-sections";
505       return 1;
506     }
507     MAI->setCompressDebugSections(CompressDebugSections);
508   }
509   MAI->setPreserveAsmComments(PreserveComments);
510 
511   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
512   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
513   MCObjectFileInfo MOFI;
514   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
515   MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
516 
517   if (SaveTempLabels)
518     Ctx.setAllowTemporaryLabels(false);
519 
520   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
521   // Default to 4 for dwarf version.
522   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
523   if (DwarfVersion < 2 || DwarfVersion > 4) {
524     errs() << ProgName << ": Dwarf version " << DwarfVersion
525            << " is not supported." << '\n';
526     return 1;
527   }
528   Ctx.setDwarfVersion(DwarfVersion);
529   if (!DwarfDebugFlags.empty())
530     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
531   if (!DwarfDebugProducer.empty())
532     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
533   if (!DebugCompilationDir.empty())
534     Ctx.setCompilationDir(DebugCompilationDir);
535   else {
536     // If no compilation dir is set, try to use the current directory.
537     SmallString<128> CWD;
538     if (!sys::fs::current_path(CWD))
539       Ctx.setCompilationDir(CWD);
540   }
541   if (!MainFileName.empty())
542     Ctx.setMainFileName(MainFileName);
543 
544   // Package up features to be passed to target/subtarget
545   std::string FeaturesStr;
546   if (MAttrs.size()) {
547     SubtargetFeatures Features;
548     for (unsigned i = 0; i != MAttrs.size(); ++i)
549       Features.AddFeature(MAttrs[i]);
550     FeaturesStr = Features.getString();
551   }
552 
553   std::unique_ptr<tool_output_file> Out = GetOutputStream();
554   if (!Out)
555     return 1;
556 
557   std::unique_ptr<buffer_ostream> BOS;
558   raw_pwrite_stream *OS = &Out->os();
559   std::unique_ptr<MCStreamer> Str;
560 
561   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
562   std::unique_ptr<MCSubtargetInfo> STI(
563       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
564 
565   MCInstPrinter *IP = nullptr;
566   if (FileType == OFT_AssemblyFile) {
567     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
568                                         *MAI, *MCII, *MRI);
569 
570     // Set the display preference for hex vs. decimal immediates.
571     IP->setPrintImmHex(PrintImmHex);
572 
573     // Set up the AsmStreamer.
574     MCCodeEmitter *CE = nullptr;
575     MCAsmBackend *MAB = nullptr;
576     if (ShowEncoding) {
577       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
578       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
579     }
580     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
581     Str.reset(TheTarget->createAsmStreamer(
582         Ctx, std::move(FOut), /*asmverbose*/ true,
583         /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
584 
585   } else if (FileType == OFT_Null) {
586     Str.reset(TheTarget->createNullStreamer(Ctx));
587   } else {
588     assert(FileType == OFT_ObjectFile && "Invalid file type!");
589 
590     // Don't waste memory on names of temp labels.
591     Ctx.setUseNamesOnTempLabels(false);
592 
593     if (!Out->os().supportsSeeking()) {
594       BOS = make_unique<buffer_ostream>(Out->os());
595       OS = BOS.get();
596     }
597 
598     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
599     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
600                                                       MCOptions);
601     Str.reset(TheTarget->createMCObjectStreamer(
602         TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
603         MCOptions.MCIncrementalLinkerCompatible,
604         /*DWARFMustBeAtTheEnd*/ false));
605     if (NoExecStack)
606       Str->InitSections(true);
607   }
608 
609   int Res = 1;
610   bool disassemble = false;
611   switch (Action) {
612   case AC_AsLex:
613     Res = AsLexInput(SrcMgr, *MAI, Out->os());
614     break;
615   case AC_Assemble:
616     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
617                         *MCII, MCOptions);
618     break;
619   case AC_MDisassemble:
620     assert(IP && "Expected assembly output");
621     IP->setUseMarkup(1);
622     disassemble = true;
623     break;
624   case AC_Disassemble:
625     disassemble = true;
626     break;
627   }
628   if (disassemble)
629     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
630                                     *Buffer, SrcMgr, Out->os());
631 
632   // Keep output if no errors.
633   if (Res == 0) Out->keep();
634   return Res;
635 }
636