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