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