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