llvm-mc: Add option for prefering hex format disassembly.
[oota-llvm.git] / tools / llvm-mc / llvm-mc.cpp
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
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/MCRegisterInfo.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCTargetAsmParser.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 using namespace llvm;
43
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
46
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"),
49                cl::value_desc("filename"));
50
51 static cl::opt<bool>
52 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
53
54 static cl::opt<bool>
55 CompressDebugSections("compress-debug-sections", cl::desc("Compress DWARF debug sections"));
56
57 static cl::opt<bool>
58 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
59
60 static cl::opt<bool>
61 ShowInstOperands("show-inst-operands",
62                  cl::desc("Show instructions operands as parsed"));
63
64 static cl::opt<unsigned>
65 OutputAsmVariant("output-asm-variant",
66                  cl::desc("Syntax variant to use for output printing"));
67
68 static cl::opt<bool>
69 PrintImmHex("print-imm-hex", cl::init(false),
70             cl::desc("Prefer hex format for immediate values"));
71
72 enum OutputFileType {
73   OFT_Null,
74   OFT_AssemblyFile,
75   OFT_ObjectFile
76 };
77 static cl::opt<OutputFileType>
78 FileType("filetype", cl::init(OFT_AssemblyFile),
79   cl::desc("Choose an output file type:"),
80   cl::values(
81        clEnumValN(OFT_AssemblyFile, "asm",
82                   "Emit an assembly ('.s') file"),
83        clEnumValN(OFT_Null, "null",
84                   "Don't emit anything (for timing purposes)"),
85        clEnumValN(OFT_ObjectFile, "obj",
86                   "Emit a native object ('.o') file"),
87        clEnumValEnd));
88
89 static cl::list<std::string>
90 IncludeDirs("I", cl::desc("Directory of include files"),
91             cl::value_desc("directory"), cl::Prefix);
92
93 static cl::opt<std::string>
94 ArchName("arch", cl::desc("Target arch to assemble for, "
95                           "see -version for available targets"));
96
97 static cl::opt<std::string>
98 TripleName("triple", cl::desc("Target triple to assemble for, "
99                               "see -version for available targets"));
100
101 static cl::opt<std::string>
102 MCPU("mcpu",
103      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
104      cl::value_desc("cpu-name"),
105      cl::init(""));
106
107 static cl::list<std::string>
108 MAttrs("mattr",
109   cl::CommaSeparated,
110   cl::desc("Target specific attributes (-mattr=help for details)"),
111   cl::value_desc("a1,+a2,-a3,..."));
112
113 static cl::opt<Reloc::Model>
114 RelocModel("relocation-model",
115              cl::desc("Choose relocation model"),
116              cl::init(Reloc::Default),
117              cl::values(
118             clEnumValN(Reloc::Default, "default",
119                        "Target default relocation model"),
120             clEnumValN(Reloc::Static, "static",
121                        "Non-relocatable code"),
122             clEnumValN(Reloc::PIC_, "pic",
123                        "Fully relocatable, position independent code"),
124             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
125                        "Relocatable external references, non-relocatable code"),
126             clEnumValEnd));
127
128 static cl::opt<llvm::CodeModel::Model>
129 CMModel("code-model",
130         cl::desc("Choose code model"),
131         cl::init(CodeModel::Default),
132         cl::values(clEnumValN(CodeModel::Default, "default",
133                               "Target default code model"),
134                    clEnumValN(CodeModel::Small, "small",
135                               "Small code model"),
136                    clEnumValN(CodeModel::Kernel, "kernel",
137                               "Kernel code model"),
138                    clEnumValN(CodeModel::Medium, "medium",
139                               "Medium code model"),
140                    clEnumValN(CodeModel::Large, "large",
141                               "Large code model"),
142                    clEnumValEnd));
143
144 static cl::opt<bool>
145 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
146                                    "in the text section"));
147
148 static cl::opt<bool>
149 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
150                                   "source files"));
151
152 static cl::opt<int>
153 DwarfVersion("dwarf-version", cl::desc("Dwarf version"), cl::init(4));
154
155 static cl::opt<std::string>
156 DebugCompilationDir("fdebug-compilation-dir",
157                     cl::desc("Specifies the debug info's compilation dir"));
158
159 static cl::opt<std::string>
160 MainFileName("main-file-name",
161              cl::desc("Specifies the name we should consider the input file"));
162
163 static cl::opt<bool> SaveTempLabels("save-temp-labels",
164                                     cl::desc("Don't discard temporary labels"));
165
166 static cl::opt<bool> NoExecStack("no-exec-stack",
167                                  cl::desc("File doesn't need an exec stack"));
168
169 enum ActionType {
170   AC_AsLex,
171   AC_Assemble,
172   AC_Disassemble,
173   AC_MDisassemble,
174 };
175
176 static cl::opt<ActionType>
177 Action(cl::desc("Action to perform:"),
178        cl::init(AC_Assemble),
179        cl::values(clEnumValN(AC_AsLex, "as-lex",
180                              "Lex tokens from a .s file"),
181                   clEnumValN(AC_Assemble, "assemble",
182                              "Assemble a .s file (default)"),
183                   clEnumValN(AC_Disassemble, "disassemble",
184                              "Disassemble strings of hex bytes"),
185                   clEnumValN(AC_MDisassemble, "mdis",
186                              "Marked up disassembly of strings of hex bytes"),
187                   clEnumValEnd));
188
189 static const Target *GetTarget(const char *ProgName) {
190   // Figure out the target triple.
191   if (TripleName.empty())
192     TripleName = sys::getDefaultTargetTriple();
193   Triple TheTriple(Triple::normalize(TripleName));
194
195   // Get the target specific parser.
196   std::string Error;
197   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
198                                                          Error);
199   if (!TheTarget) {
200     errs() << ProgName << ": " << Error;
201     return nullptr;
202   }
203
204   // Update the triple name and return the found target.
205   TripleName = TheTriple.getTriple();
206   return TheTarget;
207 }
208
209 static tool_output_file *GetOutputStream() {
210   if (OutputFilename == "")
211     OutputFilename = "-";
212
213   std::string Err;
214   tool_output_file *Out =
215       new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_None);
216   if (!Err.empty()) {
217     errs() << Err << '\n';
218     delete Out;
219     return nullptr;
220   }
221
222   return Out;
223 }
224
225 static std::string DwarfDebugFlags;
226 static void setDwarfDebugFlags(int argc, char **argv) {
227   if (!getenv("RC_DEBUG_OPTIONS"))
228     return;
229   for (int i = 0; i < argc; i++) {
230     DwarfDebugFlags += argv[i];
231     if (i + 1 < argc)
232       DwarfDebugFlags += " ";
233   }
234 }
235
236 static std::string DwarfDebugProducer;
237 static void setDwarfDebugProducer(void) {
238   if(!getenv("DEBUG_PRODUCER"))
239     return;
240   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
241 }
242
243 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
244
245   AsmLexer Lexer(MAI);
246   Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
247
248   bool Error = false;
249   while (Lexer.Lex().isNot(AsmToken::Eof)) {
250     AsmToken Tok = Lexer.getTok();
251
252     switch (Tok.getKind()) {
253     default:
254       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
255                           "unknown token");
256       Error = true;
257       break;
258     case AsmToken::Error:
259       Error = true; // error already printed.
260       break;
261     case AsmToken::Identifier:
262       Out->os() << "identifier: " << Lexer.getTok().getString();
263       break;
264     case AsmToken::Integer:
265       Out->os() << "int: " << Lexer.getTok().getString();
266       break;
267     case AsmToken::Real:
268       Out->os() << "real: " << Lexer.getTok().getString();
269       break;
270     case AsmToken::String:
271       Out->os() << "string: " << Lexer.getTok().getString();
272       break;
273
274     case AsmToken::Amp:            Out->os() << "Amp"; break;
275     case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
276     case AsmToken::At:             Out->os() << "At"; break;
277     case AsmToken::Caret:          Out->os() << "Caret"; break;
278     case AsmToken::Colon:          Out->os() << "Colon"; break;
279     case AsmToken::Comma:          Out->os() << "Comma"; break;
280     case AsmToken::Dollar:         Out->os() << "Dollar"; break;
281     case AsmToken::Dot:            Out->os() << "Dot"; break;
282     case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
283     case AsmToken::Eof:            Out->os() << "Eof"; break;
284     case AsmToken::Equal:          Out->os() << "Equal"; break;
285     case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
286     case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
287     case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
288     case AsmToken::Greater:        Out->os() << "Greater"; break;
289     case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
290     case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
291     case AsmToken::Hash:           Out->os() << "Hash"; break;
292     case AsmToken::LBrac:          Out->os() << "LBrac"; break;
293     case AsmToken::LCurly:         Out->os() << "LCurly"; break;
294     case AsmToken::LParen:         Out->os() << "LParen"; break;
295     case AsmToken::Less:           Out->os() << "Less"; break;
296     case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
297     case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
298     case AsmToken::LessLess:       Out->os() << "LessLess"; break;
299     case AsmToken::Minus:          Out->os() << "Minus"; break;
300     case AsmToken::Percent:        Out->os() << "Percent"; break;
301     case AsmToken::Pipe:           Out->os() << "Pipe"; break;
302     case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
303     case AsmToken::Plus:           Out->os() << "Plus"; break;
304     case AsmToken::RBrac:          Out->os() << "RBrac"; break;
305     case AsmToken::RCurly:         Out->os() << "RCurly"; break;
306     case AsmToken::RParen:         Out->os() << "RParen"; break;
307     case AsmToken::Slash:          Out->os() << "Slash"; break;
308     case AsmToken::Star:           Out->os() << "Star"; break;
309     case AsmToken::Tilde:          Out->os() << "Tilde"; break;
310     }
311
312     // Print the token string.
313     Out->os() << " (\"";
314     Out->os().write_escaped(Tok.getString());
315     Out->os() << "\")\n";
316   }
317
318   return Error;
319 }
320
321 static int AssembleInput(const char *ProgName, const Target *TheTarget,
322                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
323                          MCAsmInfo &MAI, MCSubtargetInfo &STI, MCInstrInfo &MCII) {
324   std::unique_ptr<MCAsmParser> Parser(
325       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
326   std::unique_ptr<MCTargetAsmParser> TAP(
327       TheTarget->createMCAsmParser(STI, *Parser, MCII,
328                                    InitMCTargetOptionsFromFlags()));
329   if (!TAP) {
330     errs() << ProgName
331            << ": error: this target does not support assembly parsing.\n";
332     return 1;
333   }
334
335   Parser->setShowParsedOperands(ShowInstOperands);
336   Parser->setTargetParser(*TAP.get());
337
338   int Res = Parser->Run(NoInitialTextSection);
339
340   return Res;
341 }
342
343 int main(int argc, char **argv) {
344   // Print a stack trace if we signal out.
345   sys::PrintStackTraceOnErrorSignal();
346   PrettyStackTraceProgram X(argc, argv);
347   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
348
349   // Initialize targets and assembly printers/parsers.
350   llvm::InitializeAllTargetInfos();
351   llvm::InitializeAllTargetMCs();
352   llvm::InitializeAllAsmParsers();
353   llvm::InitializeAllDisassemblers();
354
355   // Register the target printer for --version.
356   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
357
358   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
359   TripleName = Triple::normalize(TripleName);
360   setDwarfDebugFlags(argc, argv);
361
362   setDwarfDebugProducer();
363
364   const char *ProgName = argv[0];
365   const Target *TheTarget = GetTarget(ProgName);
366   if (!TheTarget)
367     return 1;
368
369   std::unique_ptr<MemoryBuffer> BufferPtr;
370   if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
371     errs() << ProgName << ": " << ec.message() << '\n';
372     return 1;
373   }
374   MemoryBuffer *Buffer = BufferPtr.release();
375
376   SourceMgr SrcMgr;
377
378   // Tell SrcMgr about this buffer, which is what the parser will pick up.
379   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
380
381   // Record the location of the include directories so that the lexer can find
382   // it later.
383   SrcMgr.setIncludeDirs(IncludeDirs);
384
385   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
386   assert(MRI && "Unable to create target register info!");
387
388   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
389   assert(MAI && "Unable to create target asm info!");
390
391   if (CompressDebugSections) {
392     if (!zlib::isAvailable()) {
393       errs() << ProgName << ": build tools with zlib to enable -compress-debug-sections";
394       return 1;
395     }
396     MAI->setCompressDebugSections(true);
397   }
398
399   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
400   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
401   std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
402   MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
403   MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
404
405   if (SaveTempLabels)
406     Ctx.setAllowTemporaryLabels(false);
407
408   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
409   if (DwarfVersion < 2 || DwarfVersion > 4) {
410     errs() << ProgName << ": Dwarf version " << DwarfVersion
411            << " is not supported." << '\n';
412     return 1;
413   }
414   Ctx.setDwarfVersion(DwarfVersion);
415   if (!DwarfDebugFlags.empty())
416     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
417   if (!DwarfDebugProducer.empty())
418     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
419   if (!DebugCompilationDir.empty())
420     Ctx.setCompilationDir(DebugCompilationDir);
421   if (!MainFileName.empty())
422     Ctx.setMainFileName(MainFileName);
423
424   // Package up features to be passed to target/subtarget
425   std::string FeaturesStr;
426   if (MAttrs.size()) {
427     SubtargetFeatures Features;
428     for (unsigned i = 0; i != MAttrs.size(); ++i)
429       Features.AddFeature(MAttrs[i]);
430     FeaturesStr = Features.getString();
431   }
432
433   std::unique_ptr<tool_output_file> Out(GetOutputStream());
434   if (!Out)
435     return 1;
436
437   formatted_raw_ostream FOS(Out->os());
438   std::unique_ptr<MCStreamer> Str;
439
440   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
441   std::unique_ptr<MCSubtargetInfo> STI(
442       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
443
444   MCInstPrinter *IP = nullptr;
445   if (FileType == OFT_AssemblyFile) {
446     IP =
447       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
448
449     // Set the display preference for hex vs. decimal immediates.
450     IP->setPrintImmHex(PrintImmHex);
451
452     // Set up the AsmStreamer.
453     MCCodeEmitter *CE = nullptr;
454     MCAsmBackend *MAB = nullptr;
455     if (ShowEncoding) {
456       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
457       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
458     }
459     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/ true,
460                                            /*useDwarfDirectory*/ true, IP, CE,
461                                            MAB, ShowInst));
462
463   } else if (FileType == OFT_Null) {
464     Str.reset(createNullStreamer(Ctx));
465   } else {
466     assert(FileType == OFT_ObjectFile && "Invalid file type!");
467     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
468     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
469     Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
470                                                 FOS, CE, *STI, RelaxAll,
471                                                 NoExecStack));
472   }
473
474   int Res = 1;
475   bool disassemble = false;
476   switch (Action) {
477   case AC_AsLex:
478     Res = AsLexInput(SrcMgr, *MAI, Out.get());
479     break;
480   case AC_Assemble:
481     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, *MCII);
482     break;
483   case AC_MDisassemble:
484     assert(IP && "Expected assembly output");
485     IP->setUseMarkup(1);
486     disassemble = true;
487     break;
488   case AC_Disassemble:
489     disassemble = true;
490     break;
491   }
492   if (disassemble)
493     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
494                                     *Buffer, SrcMgr, Out->os());
495
496   // Keep output if no errors.
497   if (Res == 0) Out->keep();
498   return Res;
499 }