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