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