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