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