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