pass "-fasm-verbose" into createAsmStreamer.
[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/MCAsmLexer.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCCodeEmitter.h"
18 #include "llvm/MC/MCInstPrinter.h"
19 #include "llvm/MC/MCSectionMachO.h"
20 #include "llvm/MC/MCStreamer.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/FormattedStream.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/PrettyStackTrace.h"
27 #include "llvm/Support/SourceMgr.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/System/Signals.h"
30 #include "llvm/Target/TargetAsmParser.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Target/TargetMachine.h"  // FIXME.
34 #include "llvm/Target/TargetSelect.h"
35 #include "llvm/MC/MCParser/AsmParser.h"
36 #include "Disassembler.h"
37 using namespace llvm;
38
39 static cl::opt<std::string>
40 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
41
42 static cl::opt<std::string>
43 OutputFilename("o", cl::desc("Output filename"),
44                cl::value_desc("filename"));
45
46 static cl::opt<bool>
47 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
48
49 static cl::opt<unsigned>
50 OutputAsmVariant("output-asm-variant",
51                  cl::desc("Syntax variant to use for output printing"));
52
53 enum OutputFileType {
54   OFT_AssemblyFile,
55   OFT_ObjectFile
56 };
57 static cl::opt<OutputFileType>
58 FileType("filetype", cl::init(OFT_AssemblyFile),
59   cl::desc("Choose an output file type:"),
60   cl::values(
61        clEnumValN(OFT_AssemblyFile, "asm",
62                   "Emit an assembly ('.s') file"),
63        clEnumValN(OFT_ObjectFile, "obj",
64                   "Emit a native object ('.o') file"),
65        clEnumValEnd));
66
67 static cl::opt<bool>
68 Force("f", cl::desc("Enable binary output on terminals"));
69
70 static cl::list<std::string>
71 IncludeDirs("I", cl::desc("Directory of include files"),
72             cl::value_desc("directory"), cl::Prefix);
73
74 static cl::opt<std::string>
75 TripleName("triple", cl::desc("Target triple to assemble for, "
76                               "see -version for available targets"),
77            cl::init(LLVM_HOSTTRIPLE));
78
79 enum ActionType {
80   AC_AsLex,
81   AC_Assemble,
82   AC_Disassemble
83 };
84
85 static cl::opt<ActionType>
86 Action(cl::desc("Action to perform:"),
87        cl::init(AC_Assemble),
88        cl::values(clEnumValN(AC_AsLex, "as-lex",
89                              "Lex tokens from a .s file"),
90                   clEnumValN(AC_Assemble, "assemble",
91                              "Assemble a .s file (default)"),
92                   clEnumValN(AC_Disassemble, "disassemble",
93                              "Disassemble strings of hex bytes"),
94                   clEnumValEnd));
95
96 static const Target *GetTarget(const char *ProgName) {
97   // Get the target specific parser.
98   std::string Error;
99   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
100   if (TheTarget)
101     return TheTarget;
102
103   errs() << ProgName << ": error: unable to get target for '" << TripleName
104          << "', see --version and --triple.\n";
105   return 0;
106 }
107
108 static int AsLexInput(const char *ProgName) {
109   std::string ErrorMessage;
110   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
111                                                       &ErrorMessage);
112   if (Buffer == 0) {
113     errs() << ProgName << ": ";
114     if (ErrorMessage.size())
115       errs() << ErrorMessage << "\n";
116     else
117       errs() << "input file didn't read correctly.\n";
118     return 1;
119   }
120
121   SourceMgr SrcMgr;
122   
123   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
124   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
125   
126   // Record the location of the include directories so that the lexer can find
127   // it later.
128   SrcMgr.setIncludeDirs(IncludeDirs);
129
130   const Target *TheTarget = GetTarget(ProgName);
131   if (!TheTarget)
132     return 1;
133
134   const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
135   assert(MAI && "Unable to create target asm info!");
136
137   AsmLexer Lexer(*MAI);
138   
139   bool Error = false;
140   
141   while (Lexer.Lex().isNot(AsmToken::Eof)) {
142     switch (Lexer.getKind()) {
143     default:
144       SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
145       Error = true;
146       break;
147     case AsmToken::Error:
148       Error = true; // error already printed.
149       break;
150     case AsmToken::Identifier:
151       outs() << "identifier: " << Lexer.getTok().getString() << '\n';
152       break;
153     case AsmToken::String:
154       outs() << "string: " << Lexer.getTok().getString() << '\n';
155       break;
156     case AsmToken::Integer:
157       outs() << "int: " << Lexer.getTok().getString() << '\n';
158       break;
159
160     case AsmToken::Amp:            outs() << "Amp\n"; break;
161     case AsmToken::AmpAmp:         outs() << "AmpAmp\n"; break;
162     case AsmToken::Caret:          outs() << "Caret\n"; break;
163     case AsmToken::Colon:          outs() << "Colon\n"; break;
164     case AsmToken::Comma:          outs() << "Comma\n"; break;
165     case AsmToken::Dollar:         outs() << "Dollar\n"; break;
166     case AsmToken::EndOfStatement: outs() << "EndOfStatement\n"; break;
167     case AsmToken::Eof:            outs() << "Eof\n"; break;
168     case AsmToken::Equal:          outs() << "Equal\n"; break;
169     case AsmToken::EqualEqual:     outs() << "EqualEqual\n"; break;
170     case AsmToken::Exclaim:        outs() << "Exclaim\n"; break;
171     case AsmToken::ExclaimEqual:   outs() << "ExclaimEqual\n"; break;
172     case AsmToken::Greater:        outs() << "Greater\n"; break;
173     case AsmToken::GreaterEqual:   outs() << "GreaterEqual\n"; break;
174     case AsmToken::GreaterGreater: outs() << "GreaterGreater\n"; break;
175     case AsmToken::LParen:         outs() << "LParen\n"; break;
176     case AsmToken::Less:           outs() << "Less\n"; break;
177     case AsmToken::LessEqual:      outs() << "LessEqual\n"; break;
178     case AsmToken::LessGreater:    outs() << "LessGreater\n"; break;
179     case AsmToken::LessLess:       outs() << "LessLess\n"; break;
180     case AsmToken::Minus:          outs() << "Minus\n"; break;
181     case AsmToken::Percent:        outs() << "Percent\n"; break;
182     case AsmToken::Pipe:           outs() << "Pipe\n"; break;
183     case AsmToken::PipePipe:       outs() << "PipePipe\n"; break;
184     case AsmToken::Plus:           outs() << "Plus\n"; break;
185     case AsmToken::RParen:         outs() << "RParen\n"; break;
186     case AsmToken::Slash:          outs() << "Slash\n"; break;
187     case AsmToken::Star:           outs() << "Star\n"; break;
188     case AsmToken::Tilde:          outs() << "Tilde\n"; break;
189     }
190   }
191   
192   return Error;
193 }
194
195 static formatted_raw_ostream *GetOutputStream() {
196   if (OutputFilename == "")
197     OutputFilename = "-";
198
199   // Make sure that the Out file gets unlinked from the disk if we get a
200   // SIGINT.
201   if (OutputFilename != "-")
202     sys::RemoveFileOnSignal(sys::Path(OutputFilename));
203
204   std::string Err;
205   raw_fd_ostream *Out = new raw_fd_ostream(OutputFilename.c_str(), Err,
206                                            raw_fd_ostream::F_Binary);
207   if (!Err.empty()) {
208     errs() << Err << '\n';
209     delete Out;
210     return 0;
211   }
212   
213   return new formatted_raw_ostream(*Out, formatted_raw_ostream::DELETE_STREAM);
214 }
215
216 static int AssembleInput(const char *ProgName) {
217   const Target *TheTarget = GetTarget(ProgName);
218   if (!TheTarget)
219     return 1;
220
221   std::string Error;
222   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
223   if (Buffer == 0) {
224     errs() << ProgName << ": ";
225     if (Error.size())
226       errs() << Error << "\n";
227     else
228       errs() << "input file didn't read correctly.\n";
229     return 1;
230   }
231   
232   SourceMgr SrcMgr;
233   
234   // Tell SrcMgr about this buffer, which is what the parser will pick up.
235   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
236   
237   // Record the location of the include directories so that the lexer can find
238   // it later.
239   SrcMgr.setIncludeDirs(IncludeDirs);
240   
241   MCContext Ctx;
242   formatted_raw_ostream *Out = GetOutputStream();
243   if (!Out)
244     return 1;
245
246
247   // FIXME: We shouldn't need to do this (and link in codegen).
248   OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, ""));
249
250   if (!TM) {
251     errs() << ProgName << ": error: could not create target for triple '"
252            << TripleName << "'.\n";
253     return 1;
254   }
255
256   OwningPtr<MCInstPrinter> IP;
257   OwningPtr<MCCodeEmitter> CE;
258   OwningPtr<MCStreamer> Str;
259
260   const MCAsmInfo *MAI = TheTarget->createAsmInfo(TripleName);
261   assert(MAI && "Unable to create target asm info!");
262
263   if (FileType == OFT_AssemblyFile) {
264     IP.reset(TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *Out));
265     if (ShowEncoding)
266       CE.reset(TheTarget->createCodeEmitter(*TM));
267     Str.reset(createAsmStreamer(Ctx, *Out, *MAI,
268                                 TM->getTargetData()->isLittleEndian(),
269                                 /*asmverbose*/true, IP.get(), CE.get()));
270   } else {
271     assert(FileType == OFT_ObjectFile && "Invalid file type!");
272     CE.reset(TheTarget->createCodeEmitter(*TM));
273     Str.reset(createMachOStreamer(Ctx, *Out, CE.get()));
274   }
275
276   AsmParser Parser(SrcMgr, Ctx, *Str.get(), *MAI);
277   OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(Parser));
278   if (!TAP) {
279     errs() << ProgName 
280            << ": error: this target does not support assembly parsing.\n";
281     return 1;
282   }
283
284   Parser.setTargetParser(*TAP.get());
285
286   int Res = Parser.Run();
287   if (Out != &fouts())
288     delete Out;
289
290   return Res;
291 }
292
293 static int DisassembleInput(const char *ProgName) {
294   std::string Error;
295   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
296   if (TheTarget == 0) {
297     errs() << ProgName << ": error: unable to get target for '" << TripleName
298     << "', see --version and --triple.\n";
299     return 0;
300   }
301   
302   std::string ErrorMessage;
303   
304   MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
305                                                       &ErrorMessage);
306
307   if (Buffer == 0) {
308     errs() << ProgName << ": ";
309     if (ErrorMessage.size())
310       errs() << ErrorMessage << "\n";
311     else
312       errs() << "input file didn't read correctly.\n";
313     return 1;
314   }
315   
316   return Disassembler::disassemble(*TheTarget, TripleName, *Buffer);
317 }
318
319
320 int main(int argc, char **argv) {
321   // Print a stack trace if we signal out.
322   sys::PrintStackTraceOnErrorSignal();
323   PrettyStackTraceProgram X(argc, argv);
324   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
325
326   // Initialize targets and assembly printers/parsers.
327   llvm::InitializeAllTargetInfos();
328   // FIXME: We shouldn't need to initialize the Target(Machine)s.
329   llvm::InitializeAllTargets();
330   llvm::InitializeAllAsmPrinters();
331   llvm::InitializeAllAsmParsers();
332   llvm::InitializeAllDisassemblers();
333   
334   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
335
336   switch (Action) {
337   default:
338   case AC_AsLex:
339     return AsLexInput(argv[0]);
340   case AC_Assemble:
341     return AssembleInput(argv[0]);
342   case AC_Disassemble:
343     return DisassembleInput(argv[0]);
344   }
345   
346   return 0;
347 }
348