Allow MCCodeEmitter access to the target MCRegisterInfo.
[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/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/system_error.h"
44 #include "Disassembler.h"
45 using namespace llvm;
46
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
49
50 static cl::opt<std::string>
51 OutputFilename("o", cl::desc("Output filename"),
52                cl::value_desc("filename"));
53
54 static cl::opt<bool>
55 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
56
57 static cl::opt<bool>
58 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
59
60 static cl::opt<bool>
61 ShowInstOperands("show-inst-operands",
62                  cl::desc("Show instructions operands as parsed"));
63
64 static cl::opt<unsigned>
65 OutputAsmVariant("output-asm-variant",
66                  cl::desc("Syntax variant to use for output printing"));
67
68 static cl::opt<bool>
69 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
70
71 static cl::opt<bool>
72 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
73
74 enum OutputFileType {
75   OFT_Null,
76   OFT_AssemblyFile,
77   OFT_ObjectFile
78 };
79 static cl::opt<OutputFileType>
80 FileType("filetype", cl::init(OFT_AssemblyFile),
81   cl::desc("Choose an output file type:"),
82   cl::values(
83        clEnumValN(OFT_AssemblyFile, "asm",
84                   "Emit an assembly ('.s') file"),
85        clEnumValN(OFT_Null, "null",
86                   "Don't emit anything (for timing purposes)"),
87        clEnumValN(OFT_ObjectFile, "obj",
88                   "Emit a native object ('.o') file"),
89        clEnumValEnd));
90
91 static cl::list<std::string>
92 IncludeDirs("I", cl::desc("Directory of include files"),
93             cl::value_desc("directory"), cl::Prefix);
94
95 static cl::opt<std::string>
96 ArchName("arch", cl::desc("Target arch to assemble for, "
97                           "see -version for available targets"));
98
99 static cl::opt<std::string>
100 TripleName("triple", cl::desc("Target triple to assemble for, "
101                               "see -version for available targets"));
102
103 static cl::opt<std::string>
104 MCPU("mcpu",
105      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
106      cl::value_desc("cpu-name"),
107      cl::init(""));
108
109 static cl::list<std::string>
110 MAttrs("mattr",
111   cl::CommaSeparated,
112   cl::desc("Target specific attributes (-mattr=help for details)"),
113   cl::value_desc("a1,+a2,-a3,..."));
114
115 static cl::opt<Reloc::Model>
116 RelocModel("relocation-model",
117              cl::desc("Choose relocation model"),
118              cl::init(Reloc::Default),
119              cl::values(
120             clEnumValN(Reloc::Default, "default",
121                        "Target default relocation model"),
122             clEnumValN(Reloc::Static, "static",
123                        "Non-relocatable code"),
124             clEnumValN(Reloc::PIC_, "pic",
125                        "Fully relocatable, position independent code"),
126             clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
127                        "Relocatable external references, non-relocatable code"),
128             clEnumValEnd));
129
130 static cl::opt<llvm::CodeModel::Model>
131 CMModel("code-model",
132         cl::desc("Choose code model"),
133         cl::init(CodeModel::Default),
134         cl::values(clEnumValN(CodeModel::Default, "default",
135                               "Target default code model"),
136                    clEnumValN(CodeModel::Small, "small",
137                               "Small code model"),
138                    clEnumValN(CodeModel::Kernel, "kernel",
139                               "Kernel code model"),
140                    clEnumValN(CodeModel::Medium, "medium",
141                               "Medium code model"),
142                    clEnumValN(CodeModel::Large, "large",
143                               "Large code model"),
144                    clEnumValEnd));
145
146 static cl::opt<bool>
147 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
148                                    "in the text section"));
149
150 static cl::opt<bool>
151 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
152
153 static cl::opt<bool>
154 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
155                                   "source files"));
156
157 enum ActionType {
158   AC_AsLex,
159   AC_Assemble,
160   AC_Disassemble,
161   AC_EDisassemble
162 };
163
164 static cl::opt<ActionType>
165 Action(cl::desc("Action to perform:"),
166        cl::init(AC_Assemble),
167        cl::values(clEnumValN(AC_AsLex, "as-lex",
168                              "Lex tokens from a .s file"),
169                   clEnumValN(AC_Assemble, "assemble",
170                              "Assemble a .s file (default)"),
171                   clEnumValN(AC_Disassemble, "disassemble",
172                              "Disassemble strings of hex bytes"),
173                   clEnumValN(AC_EDisassemble, "edis",
174                              "Enhanced disassembly of strings of hex bytes"),
175                   clEnumValEnd));
176
177 static const Target *GetTarget(const char *ProgName) {
178   // Figure out the target triple.
179   if (TripleName.empty())
180     TripleName = sys::getDefaultTargetTriple();
181   Triple TheTriple(Triple::normalize(TripleName));
182
183   // Get the target specific parser.
184   std::string Error;
185   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
186                                                          Error);
187   if (!TheTarget) {
188     errs() << ProgName << ": " << Error;
189     return 0;
190   }
191
192   // Update the triple name and return the found target.
193   TripleName = TheTriple.getTriple();
194   return TheTarget;
195 }
196
197 static tool_output_file *GetOutputStream() {
198   if (OutputFilename == "")
199     OutputFilename = "-";
200
201   std::string Err;
202   tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
203                                                raw_fd_ostream::F_Binary);
204   if (!Err.empty()) {
205     errs() << Err << '\n';
206     delete Out;
207     return 0;
208   }
209
210   return Out;
211 }
212
213 static std::string DwarfDebugFlags;
214 static void setDwarfDebugFlags(int argc, char **argv) {
215   if (!getenv("RC_DEBUG_OPTIONS"))
216     return;
217   for (int i = 0; i < argc; i++) {
218     DwarfDebugFlags += argv[i];
219     if (i + 1 < argc)
220       DwarfDebugFlags += " ";
221   }
222 }
223
224 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
225
226   AsmLexer Lexer(MAI);
227   Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
228
229   bool Error = false;
230   while (Lexer.Lex().isNot(AsmToken::Eof)) {
231     AsmToken Tok = Lexer.getTok();
232
233     switch (Tok.getKind()) {
234     default:
235       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
236                           "unknown token");
237       Error = true;
238       break;
239     case AsmToken::Error:
240       Error = true; // error already printed.
241       break;
242     case AsmToken::Identifier:
243       Out->os() << "identifier: " << Lexer.getTok().getString();
244       break;
245     case AsmToken::Integer:
246       Out->os() << "int: " << Lexer.getTok().getString();
247       break;
248     case AsmToken::Real:
249       Out->os() << "real: " << Lexer.getTok().getString();
250       break;
251     case AsmToken::Register:
252       Out->os() << "register: " << Lexer.getTok().getRegVal();
253       break;
254     case AsmToken::String:
255       Out->os() << "string: " << Lexer.getTok().getString();
256       break;
257
258     case AsmToken::Amp:            Out->os() << "Amp"; break;
259     case AsmToken::AmpAmp:         Out->os() << "AmpAmp"; break;
260     case AsmToken::At:             Out->os() << "At"; break;
261     case AsmToken::Caret:          Out->os() << "Caret"; break;
262     case AsmToken::Colon:          Out->os() << "Colon"; break;
263     case AsmToken::Comma:          Out->os() << "Comma"; break;
264     case AsmToken::Dollar:         Out->os() << "Dollar"; break;
265     case AsmToken::Dot:            Out->os() << "Dot"; break;
266     case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
267     case AsmToken::Eof:            Out->os() << "Eof"; break;
268     case AsmToken::Equal:          Out->os() << "Equal"; break;
269     case AsmToken::EqualEqual:     Out->os() << "EqualEqual"; break;
270     case AsmToken::Exclaim:        Out->os() << "Exclaim"; break;
271     case AsmToken::ExclaimEqual:   Out->os() << "ExclaimEqual"; break;
272     case AsmToken::Greater:        Out->os() << "Greater"; break;
273     case AsmToken::GreaterEqual:   Out->os() << "GreaterEqual"; break;
274     case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
275     case AsmToken::Hash:           Out->os() << "Hash"; break;
276     case AsmToken::LBrac:          Out->os() << "LBrac"; break;
277     case AsmToken::LCurly:         Out->os() << "LCurly"; break;
278     case AsmToken::LParen:         Out->os() << "LParen"; break;
279     case AsmToken::Less:           Out->os() << "Less"; break;
280     case AsmToken::LessEqual:      Out->os() << "LessEqual"; break;
281     case AsmToken::LessGreater:    Out->os() << "LessGreater"; break;
282     case AsmToken::LessLess:       Out->os() << "LessLess"; break;
283     case AsmToken::Minus:          Out->os() << "Minus"; break;
284     case AsmToken::Percent:        Out->os() << "Percent"; break;
285     case AsmToken::Pipe:           Out->os() << "Pipe"; break;
286     case AsmToken::PipePipe:       Out->os() << "PipePipe"; break;
287     case AsmToken::Plus:           Out->os() << "Plus"; break;
288     case AsmToken::RBrac:          Out->os() << "RBrac"; break;
289     case AsmToken::RCurly:         Out->os() << "RCurly"; break;
290     case AsmToken::RParen:         Out->os() << "RParen"; break;
291     case AsmToken::Slash:          Out->os() << "Slash"; break;
292     case AsmToken::Star:           Out->os() << "Star"; break;
293     case AsmToken::Tilde:          Out->os() << "Tilde"; break;
294     }
295
296     // Print the token string.
297     Out->os() << " (\"";
298     Out->os().write_escaped(Tok.getString());
299     Out->os() << "\")\n";
300   }
301
302   return Error;
303 }
304
305 static int AssembleInput(const char *ProgName, const Target *TheTarget, 
306                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
307                          MCAsmInfo &MAI, MCSubtargetInfo &STI) {
308   OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
309                                                   Str, MAI));
310   OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(STI, *Parser));
311   if (!TAP) {
312     errs() << ProgName
313            << ": error: this target does not support assembly parsing.\n";
314     return 1;
315   }
316
317   Parser->setShowParsedOperands(ShowInstOperands);
318   Parser->setTargetParser(*TAP.get());
319
320   int Res = Parser->Run(NoInitialTextSection);
321
322   return Res;
323 }
324
325 int main(int argc, char **argv) {
326   // Print a stack trace if we signal out.
327   sys::PrintStackTraceOnErrorSignal();
328   PrettyStackTraceProgram X(argc, argv);
329   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
330
331   // Initialize targets and assembly printers/parsers.
332   llvm::InitializeAllTargetInfos();
333   llvm::InitializeAllTargetMCs();
334   llvm::InitializeAllAsmParsers();
335   llvm::InitializeAllDisassemblers();
336
337   // Register the target printer for --version.
338   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
339
340   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
341   TripleName = Triple::normalize(TripleName);
342   setDwarfDebugFlags(argc, argv);
343
344   const char *ProgName = argv[0];
345   const Target *TheTarget = GetTarget(ProgName);
346   if (!TheTarget)
347     return 1;
348
349   OwningPtr<MemoryBuffer> BufferPtr;
350   if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
351     errs() << ProgName << ": " << ec.message() << '\n';
352     return 1;
353   }
354   MemoryBuffer *Buffer = BufferPtr.take();
355
356   SourceMgr SrcMgr;
357
358   // Tell SrcMgr about this buffer, which is what the parser will pick up.
359   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
360
361   // Record the location of the include directories so that the lexer can find
362   // it later.
363   SrcMgr.setIncludeDirs(IncludeDirs);
364
365
366   llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
367   assert(MAI && "Unable to create target asm info!");
368
369   llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
370   assert(MRI && "Unable to create target register info!");
371
372   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
373   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
374   OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
375   MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
376   MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
377
378   if (SaveTempLabels)
379     Ctx.setAllowTemporaryLabels(false);
380
381   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
382   if (!DwarfDebugFlags.empty()) 
383     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
384
385   // Package up features to be passed to target/subtarget
386   std::string FeaturesStr;
387   if (MAttrs.size()) {
388     SubtargetFeatures Features;
389     for (unsigned i = 0; i != MAttrs.size(); ++i)
390       Features.AddFeature(MAttrs[i]);
391     FeaturesStr = Features.getString();
392   }
393
394   OwningPtr<tool_output_file> Out(GetOutputStream());
395   if (!Out)
396     return 1;
397
398   formatted_raw_ostream FOS(Out->os());
399   OwningPtr<MCStreamer> Str;
400
401   OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
402   OwningPtr<MCSubtargetInfo>
403     STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
404
405   if (FileType == OFT_AssemblyFile) {
406     MCInstPrinter *IP =
407       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
408     MCCodeEmitter *CE = 0;
409     MCAsmBackend *MAB = 0;
410     if (ShowEncoding) {
411       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
412       MAB = TheTarget->createMCAsmBackend(TripleName);
413     }
414     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
415                                            /*useLoc*/ true,
416                                            /*useCFI*/ true,
417                                            /*useDwarfDirectory*/ true,
418                                            IP, CE, MAB, ShowInst));
419
420   } else if (FileType == OFT_Null) {
421     Str.reset(createNullStreamer(Ctx));
422   } else {
423     assert(FileType == OFT_ObjectFile && "Invalid file type!");
424     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
425     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName);
426     Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
427                                                 FOS, CE, RelaxAll,
428                                                 NoExecStack));
429   }
430
431   int Res = 1;
432   switch (Action) {
433   case AC_AsLex:
434     Res = AsLexInput(SrcMgr, *MAI, Out.get());
435     break;
436   case AC_Assemble:
437     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI);
438     break;
439   case AC_Disassemble:
440     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
441                                     *Buffer, SrcMgr, Out->os());
442     break;
443   case AC_EDisassemble:
444     Res =  Disassembler::disassembleEnhanced(TripleName, *Buffer, SrcMgr, Out->os());
445     break;
446   }
447
448   // Keep output if no errors.
449   if (Res == 0) Out->keep();
450   return Res;
451 }