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