llvm-mc.cpp revision 34ad6db8b958fdc0d38e122edf753b5326e69b03
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 "llvm/MC/MCParser/AsmLexer.h"
16#include "llvm/MC/MCParser/MCAsmLexer.h"
17#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCCodeEmitter.h"
19#include "llvm/MC/MCInstPrinter.h"
20#include "llvm/MC/MCInstrInfo.h"
21#include "llvm/MC/MCObjectFileInfo.h"
22#include "llvm/MC/MCRegisterInfo.h"
23#include "llvm/MC/MCSectionMachO.h"
24#include "llvm/MC/MCStreamer.h"
25#include "llvm/MC/MCSubtargetInfo.h"
26#include "llvm/MC/SubtargetFeature.h"
27#include "llvm/Target/TargetAsmBackend.h"
28#include "llvm/Target/TargetAsmParser.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Target/TargetRegistry.h"
31#include "llvm/Target/TargetAsmInfo.h"  // FIXME.
32#include "llvm/Target/TargetLowering.h"  // FIXME.
33#include "llvm/Target/TargetLoweringObjectFile.h"  // FIXME.
34#include "llvm/Target/TargetMachine.h"  // FIXME.
35#include "llvm/Target/TargetSelect.h"
36#include "llvm/ADT/OwningPtr.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/FileUtilities.h"
39#include "llvm/Support/FormattedStream.h"
40#include "llvm/Support/ManagedStatic.h"
41#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/SourceMgr.h"
44#include "llvm/Support/ToolOutputFile.h"
45#include "llvm/Support/Host.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/system_error.h"
48#include "Disassembler.h"
49using namespace llvm;
50
51static cl::opt<std::string>
52InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
53
54static cl::opt<std::string>
55OutputFilename("o", cl::desc("Output filename"),
56               cl::value_desc("filename"));
57
58static cl::opt<bool>
59ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
60
61static cl::opt<bool>
62ShowInst("show-inst", cl::desc("Show internal instruction representation"));
63
64static cl::opt<bool>
65ShowInstOperands("show-inst-operands",
66                 cl::desc("Show instructions operands as parsed"));
67
68static cl::opt<unsigned>
69OutputAsmVariant("output-asm-variant",
70                 cl::desc("Syntax variant to use for output printing"));
71
72static cl::opt<bool>
73RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
74
75static cl::opt<bool>
76NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
77
78static cl::opt<bool>
79EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
80
81enum OutputFileType {
82  OFT_Null,
83  OFT_AssemblyFile,
84  OFT_ObjectFile
85};
86static cl::opt<OutputFileType>
87FileType("filetype", cl::init(OFT_AssemblyFile),
88  cl::desc("Choose an output file type:"),
89  cl::values(
90       clEnumValN(OFT_AssemblyFile, "asm",
91                  "Emit an assembly ('.s') file"),
92       clEnumValN(OFT_Null, "null",
93                  "Don't emit anything (for timing purposes)"),
94       clEnumValN(OFT_ObjectFile, "obj",
95                  "Emit a native object ('.o') file"),
96       clEnumValEnd));
97
98static cl::list<std::string>
99IncludeDirs("I", cl::desc("Directory of include files"),
100            cl::value_desc("directory"), cl::Prefix);
101
102static cl::opt<std::string>
103ArchName("arch", cl::desc("Target arch to assemble for, "
104                          "see -version for available targets"));
105
106static cl::opt<std::string>
107TripleName("triple", cl::desc("Target triple to assemble for, "
108                              "see -version for available targets"));
109
110static cl::opt<std::string>
111MCPU("mcpu",
112     cl::desc("Target a specific cpu type (-mcpu=help for details)"),
113     cl::value_desc("cpu-name"),
114     cl::init(""));
115
116static cl::opt<Reloc::Model>
117RelocModel("relocation-model",
118             cl::desc("Choose relocation model"),
119             cl::init(Reloc::Default),
120             cl::values(
121            clEnumValN(Reloc::Default, "default",
122                       "Target default relocation model"),
123            clEnumValN(Reloc::Static, "static",
124                       "Non-relocatable code"),
125            clEnumValN(Reloc::PIC_, "pic",
126                       "Fully relocatable, position independent code"),
127            clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
128                       "Relocatable external references, non-relocatable code"),
129            clEnumValEnd));
130
131static cl::opt<llvm::CodeModel::Model>
132CMModel("code-model",
133        cl::desc("Choose code model"),
134        cl::init(CodeModel::Default),
135        cl::values(clEnumValN(CodeModel::Default, "default",
136                              "Target default code model"),
137                   clEnumValN(CodeModel::Small, "small",
138                              "Small code model"),
139                   clEnumValN(CodeModel::Kernel, "kernel",
140                              "Kernel code model"),
141                   clEnumValN(CodeModel::Medium, "medium",
142                              "Medium code model"),
143                   clEnumValN(CodeModel::Large, "large",
144                              "Large code model"),
145                   clEnumValEnd));
146
147static cl::opt<bool>
148NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
149                                   "in the text section"));
150
151static cl::opt<bool>
152SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
153
154enum ActionType {
155  AC_AsLex,
156  AC_Assemble,
157  AC_Disassemble,
158  AC_EDisassemble
159};
160
161static cl::opt<ActionType>
162Action(cl::desc("Action to perform:"),
163       cl::init(AC_Assemble),
164       cl::values(clEnumValN(AC_AsLex, "as-lex",
165                             "Lex tokens from a .s file"),
166                  clEnumValN(AC_Assemble, "assemble",
167                             "Assemble a .s file (default)"),
168                  clEnumValN(AC_Disassemble, "disassemble",
169                             "Disassemble strings of hex bytes"),
170                  clEnumValN(AC_EDisassemble, "edis",
171                             "Enhanced disassembly of strings of hex bytes"),
172                  clEnumValEnd));
173
174static const Target *GetTarget(const char *ProgName) {
175  // Figure out the target triple.
176  if (TripleName.empty())
177    TripleName = sys::getHostTriple();
178  if (!ArchName.empty()) {
179    llvm::Triple TT(TripleName);
180    TT.setArchName(ArchName);
181    TripleName = TT.str();
182  }
183
184  // Get the target specific parser.
185  std::string Error;
186  const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
187  if (TheTarget)
188    return TheTarget;
189
190  errs() << ProgName << ": error: unable to get target for '" << TripleName
191         << "', see --version and --triple.\n";
192  return 0;
193}
194
195static tool_output_file *GetOutputStream() {
196  if (OutputFilename == "")
197    OutputFilename = "-";
198
199  std::string Err;
200  tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
201                                               raw_fd_ostream::F_Binary);
202  if (!Err.empty()) {
203    errs() << Err << '\n';
204    delete Out;
205    return 0;
206  }
207
208  return Out;
209}
210
211static int AsLexInput(const char *ProgName) {
212  OwningPtr<MemoryBuffer> BufferPtr;
213  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
214    errs() << ProgName << ": " << ec.message() << '\n';
215    return 1;
216  }
217  MemoryBuffer *Buffer = BufferPtr.take();
218
219  SourceMgr SrcMgr;
220
221  // Tell SrcMgr about this buffer, which is what TGParser will pick up.
222  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
223
224  // Record the location of the include directories so that the lexer can find
225  // it later.
226  SrcMgr.setIncludeDirs(IncludeDirs);
227
228  const Target *TheTarget = GetTarget(ProgName);
229  if (!TheTarget)
230    return 1;
231
232  llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
233  assert(MAI && "Unable to create target asm info!");
234
235  AsmLexer Lexer(*MAI);
236  Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
237
238  OwningPtr<tool_output_file> Out(GetOutputStream());
239  if (!Out)
240    return 1;
241
242  bool Error = false;
243  while (Lexer.Lex().isNot(AsmToken::Eof)) {
244    AsmToken Tok = Lexer.getTok();
245
246    switch (Tok.getKind()) {
247    default:
248      SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
249      Error = true;
250      break;
251    case AsmToken::Error:
252      Error = true; // error already printed.
253      break;
254    case AsmToken::Identifier:
255      Out->os() << "identifier: " << Lexer.getTok().getString();
256      break;
257    case AsmToken::Integer:
258      Out->os() << "int: " << Lexer.getTok().getString();
259      break;
260    case AsmToken::Real:
261      Out->os() << "real: " << Lexer.getTok().getString();
262      break;
263    case AsmToken::Register:
264      Out->os() << "register: " << Lexer.getTok().getRegVal();
265      break;
266    case AsmToken::String:
267      Out->os() << "string: " << Lexer.getTok().getString();
268      break;
269
270    case AsmToken::Amp:            Out->os() << "Amp"; break;
271    case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
272    case AsmToken::At:             Out->os() << "At"; break;
273    case AsmToken::Caret:          Out->os() << "Caret"; break;
274    case AsmToken::Colon:          Out->os() << "Colon"; break;
275    case AsmToken::Comma:          Out->os() << "Comma"; break;
276    case AsmToken::Dollar:         Out->os() << "Dollar"; break;
277    case AsmToken::Dot:            Out->os() << "Dot"; break;
278    case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
279    case AsmToken::Eof:            Out->os() << "Eof"; break;
280    case AsmToken::Equal:          Out->os() << "Equal"; break;
281    case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
282    case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
283    case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
284    case AsmToken::Greater:        Out->os() << "Greater"; break;
285    case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
286    case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
287    case AsmToken::Hash:           Out->os() << "Hash"; break;
288    case AsmToken::LBrac:          Out->os() << "LBrac"; break;
289    case AsmToken::LCurly:         Out->os() << "LCurly"; break;
290    case AsmToken::LParen:         Out->os() << "LParen"; break;
291    case AsmToken::Less:           Out->os() << "Less"; break;
292    case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
293    case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
294    case AsmToken::LessLess:       Out->os() << "LessLess"; break;
295    case AsmToken::Minus:          Out->os() << "Minus"; break;
296    case AsmToken::Percent:        Out->os() << "Percent"; break;
297    case AsmToken::Pipe:           Out->os() << "Pipe"; break;
298    case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
299    case AsmToken::Plus:           Out->os() << "Plus"; break;
300    case AsmToken::RBrac:          Out->os() << "RBrac"; break;
301    case AsmToken::RCurly:         Out->os() << "RCurly"; break;
302    case AsmToken::RParen:         Out->os() << "RParen"; break;
303    case AsmToken::Slash:          Out->os() << "Slash"; break;
304    case AsmToken::Star:           Out->os() << "Star"; break;
305    case AsmToken::Tilde:          Out->os() << "Tilde"; break;
306    }
307
308    // Print the token string.
309    Out->os() << " (\"";
310    Out->os().write_escaped(Tok.getString());
311    Out->os() << "\")\n";
312  }
313
314  // Keep output if no errors.
315  if (Error == 0) Out->keep();
316
317  return Error;
318}
319
320static int AssembleInput(const char *ProgName) {
321  const Target *TheTarget = GetTarget(ProgName);
322  if (!TheTarget)
323    return 1;
324
325  OwningPtr<MemoryBuffer> BufferPtr;
326  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
327    errs() << ProgName << ": " << ec.message() << '\n';
328    return 1;
329  }
330  MemoryBuffer *Buffer = BufferPtr.take();
331
332  SourceMgr SrcMgr;
333
334  // Tell SrcMgr about this buffer, which is what the parser will pick up.
335  SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
336
337  // Record the location of the include directories so that the lexer can find
338  // it later.
339  SrcMgr.setIncludeDirs(IncludeDirs);
340
341
342  llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
343  assert(MAI && "Unable to create target asm info!");
344
345  llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
346  assert(MRI && "Unable to create target register info!");
347
348  // Package up features to be passed to target/subtarget
349  std::string FeaturesStr;
350
351  // FIXME: We shouldn't need to do this (and link in codegen).
352  //        When we split this out, we should do it in a way that makes
353  //        it straightforward to switch subtargets on the fly (.e.g,
354  //        the .cpu and .code16 directives).
355  OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
356                                                             MCPU,
357                                                             FeaturesStr,
358                                                             RelocModel,
359                                                             CMModel));
360
361  if (!TM) {
362    errs() << ProgName << ": error: could not create target for triple '"
363           << TripleName << "'.\n";
364    return 1;
365  }
366
367  const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
368  // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
369  // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
370  OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
371  MCContext Ctx(*MAI, *MRI, MOFI.get(), tai);
372  MOFI->InitMCObjectFileInfo(TripleName, RelocModel, Ctx);
373
374  if (SaveTempLabels)
375    Ctx.setAllowTemporaryLabels(false);
376
377  OwningPtr<tool_output_file> Out(GetOutputStream());
378  if (!Out)
379    return 1;
380
381  formatted_raw_ostream FOS(Out->os());
382  OwningPtr<MCStreamer> Str;
383
384  const TargetLoweringObjectFile &TLOF =
385    TM->getTargetLowering()->getObjFileLowering();
386  const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
387
388  OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
389  OwningPtr<MCSubtargetInfo>
390    STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
391
392  // FIXME: There is a bit of code duplication with addPassesToEmitFile.
393  if (FileType == OFT_AssemblyFile) {
394    MCInstPrinter *IP =
395      TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
396    MCCodeEmitter *CE = 0;
397    TargetAsmBackend *TAB = 0;
398    if (ShowEncoding) {
399      CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
400      TAB = TheTarget->createAsmBackend(TripleName);
401    }
402    Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
403                                           /*useLoc*/ true,
404                                           /*useCFI*/ true, IP, CE, TAB,
405                                           ShowInst));
406  } else if (FileType == OFT_Null) {
407    Str.reset(createNullStreamer(Ctx));
408  } else {
409    assert(FileType == OFT_ObjectFile && "Invalid file type!");
410    MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
411    TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
412    Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
413                                              FOS, CE, RelaxAll,
414                                              NoExecStack));
415  }
416
417  if (EnableLogging) {
418    Str.reset(createLoggingStreamer(Str.take(), errs()));
419  }
420
421  OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
422                                                   *Str.get(), *MAI));
423  OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
424  if (!TAP) {
425    errs() << ProgName
426           << ": error: this target does not support assembly parsing.\n";
427    return 1;
428  }
429
430  Parser->setShowParsedOperands(ShowInstOperands);
431  Parser->setTargetParser(*TAP.get());
432
433  int Res = Parser->Run(NoInitialTextSection);
434
435  // Keep output if no errors.
436  if (Res == 0) Out->keep();
437
438  return Res;
439}
440
441static int DisassembleInput(const char *ProgName, bool Enhanced) {
442  const Target *TheTarget = GetTarget(ProgName);
443  if (!TheTarget)
444    return 0;
445
446  OwningPtr<MemoryBuffer> Buffer;
447  if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
448    errs() << ProgName << ": " << ec.message() << '\n';
449    return 1;
450  }
451
452  OwningPtr<tool_output_file> Out(GetOutputStream());
453  if (!Out)
454    return 1;
455
456  int Res;
457  if (Enhanced) {
458    Res =
459      Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
460  } else {
461    Res = Disassembler::disassemble(*TheTarget, TripleName,
462                                    *Buffer.take(), Out->os());
463  }
464
465  // Keep output if no errors.
466  if (Res == 0) Out->keep();
467
468  return Res;
469}
470
471
472int main(int argc, char **argv) {
473  // Print a stack trace if we signal out.
474  sys::PrintStackTraceOnErrorSignal();
475  PrettyStackTraceProgram X(argc, argv);
476  llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
477
478  // Initialize targets and assembly printers/parsers.
479  llvm::InitializeAllTargetInfos();
480  // FIXME: We shouldn't need to initialize the Target(Machine)s.
481  llvm::InitializeAllTargets();
482  llvm::InitializeAllMCAsmInfos();
483  llvm::InitializeAllMCCodeGenInfos();
484  llvm::InitializeAllMCInstrInfos();
485  llvm::InitializeAllMCRegisterInfos();
486  llvm::InitializeAllMCSubtargetInfos();
487  llvm::InitializeAllAsmPrinters();
488  llvm::InitializeAllAsmParsers();
489  llvm::InitializeAllDisassemblers();
490
491  cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
492  TripleName = Triple::normalize(TripleName);
493
494  switch (Action) {
495  default:
496  case AC_AsLex:
497    return AsLexInput(argv[0]);
498  case AC_Assemble:
499    return AssembleInput(argv[0]);
500  case AC_Disassemble:
501    return DisassembleInput(argv[0], false);
502  case AC_EDisassemble:
503    return DisassembleInput(argv[0], true);
504  }
505
506  return 0;
507}
508
509