78fe9b72f208315dfea1af478504874324d45689
[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<std::string>
154 DebugCompilationDir("fdebug-compilation-dir",
155                     cl::desc("Specifies the debug info's compilation dir"));
156
157 static cl::opt<std::string>
158 MainFileName("main-file-name",
159              cl::desc("Specifies the name we should consider the input file"));
160
161 static cl::opt<bool> SaveTempLabels("save-temp-labels",
162                                     cl::desc("Don't discard temporary labels"));
163
164 static cl::opt<bool> NoExecStack("no-exec-stack",
165                                  cl::desc("File doesn't need an exec stack"));
166
167 enum ActionType {
168   AC_AsLex,
169   AC_Assemble,
170   AC_Disassemble,
171   AC_MDisassemble,
172 };
173
174 static cl::opt<ActionType>
175 Action(cl::desc("Action to perform:"),
176        cl::init(AC_Assemble),
177        cl::values(clEnumValN(AC_AsLex, "as-lex",
178                              "Lex tokens from a .s file"),
179                   clEnumValN(AC_Assemble, "assemble",
180                              "Assemble a .s file (default)"),
181                   clEnumValN(AC_Disassemble, "disassemble",
182                              "Disassemble strings of hex bytes"),
183                   clEnumValN(AC_MDisassemble, "mdis",
184                              "Marked up disassembly of strings of hex bytes"),
185                   clEnumValEnd));
186
187 static const Target *GetTarget(const char *ProgName) {
188   // Figure out the target triple.
189   if (TripleName.empty())
190     TripleName = sys::getDefaultTargetTriple();
191   Triple TheTriple(Triple::normalize(TripleName));
192
193   // Get the target specific parser.
194   std::string Error;
195   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
196                                                          Error);
197   if (!TheTarget) {
198     errs() << ProgName << ": " << Error;
199     return nullptr;
200   }
201
202   // Update the triple name and return the found target.
203   TripleName = TheTriple.getTriple();
204   return TheTarget;
205 }
206
207 static std::unique_ptr<tool_output_file> GetOutputStream() {
208   if (OutputFilename == "")
209     OutputFilename = "-";
210
211   std::error_code EC;
212   auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
213                                                  sys::fs::F_None);
214   if (EC) {
215     errs() << EC.message() << '\n';
216     return nullptr;
217   }
218
219   return Out;
220 }
221
222 static std::string DwarfDebugFlags;
223 static void setDwarfDebugFlags(int argc, char **argv) {
224   if (!getenv("RC_DEBUG_OPTIONS"))
225     return;
226   for (int i = 0; i < argc; i++) {
227     DwarfDebugFlags += argv[i];
228     if (i + 1 < argc)
229       DwarfDebugFlags += " ";
230   }
231 }
232
233 static std::string DwarfDebugProducer;
234 static void setDwarfDebugProducer(void) {
235   if(!getenv("DEBUG_PRODUCER"))
236     return;
237   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
238 }
239
240 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
241                       raw_ostream &OS) {
242
243   AsmLexer Lexer(MAI);
244   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
245
246   bool Error = false;
247   while (Lexer.Lex().isNot(AsmToken::Eof)) {
248     AsmToken Tok = Lexer.getTok();
249
250     switch (Tok.getKind()) {
251     default:
252       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
253                           "unknown token");
254       Error = true;
255       break;
256     case AsmToken::Error:
257       Error = true; // error already printed.
258       break;
259     case AsmToken::Identifier:
260       OS << "identifier: " << Lexer.getTok().getString();
261       break;
262     case AsmToken::Integer:
263       OS << "int: " << Lexer.getTok().getString();
264       break;
265     case AsmToken::Real:
266       OS << "real: " << Lexer.getTok().getString();
267       break;
268     case AsmToken::String:
269       OS << "string: " << Lexer.getTok().getString();
270       break;
271
272     case AsmToken::Amp:            OS << "Amp"; break;
273     case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
274     case AsmToken::At:             OS << "At"; break;
275     case AsmToken::Caret:          OS << "Caret"; break;
276     case AsmToken::Colon:          OS << "Colon"; break;
277     case AsmToken::Comma:          OS << "Comma"; break;
278     case AsmToken::Dollar:         OS << "Dollar"; break;
279     case AsmToken::Dot:            OS << "Dot"; break;
280     case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
281     case AsmToken::Eof:            OS << "Eof"; break;
282     case AsmToken::Equal:          OS << "Equal"; break;
283     case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
284     case AsmToken::Exclaim:        OS << "Exclaim"; break;
285     case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
286     case AsmToken::Greater:        OS << "Greater"; break;
287     case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
288     case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
289     case AsmToken::Hash:           OS << "Hash"; break;
290     case AsmToken::LBrac:          OS << "LBrac"; break;
291     case AsmToken::LCurly:         OS << "LCurly"; break;
292     case AsmToken::LParen:         OS << "LParen"; break;
293     case AsmToken::Less:           OS << "Less"; break;
294     case AsmToken::LessEqual:      OS << "LessEqual"; break;
295     case AsmToken::LessGreater:    OS << "LessGreater"; break;
296     case AsmToken::LessLess:       OS << "LessLess"; break;
297     case AsmToken::Minus:          OS << "Minus"; break;
298     case AsmToken::Percent:        OS << "Percent"; break;
299     case AsmToken::Pipe:           OS << "Pipe"; break;
300     case AsmToken::PipePipe:       OS << "PipePipe"; break;
301     case AsmToken::Plus:           OS << "Plus"; break;
302     case AsmToken::RBrac:          OS << "RBrac"; break;
303     case AsmToken::RCurly:         OS << "RCurly"; break;
304     case AsmToken::RParen:         OS << "RParen"; break;
305     case AsmToken::Slash:          OS << "Slash"; break;
306     case AsmToken::Star:           OS << "Star"; break;
307     case AsmToken::Tilde:          OS << "Tilde"; break;
308     }
309
310     // Print the token string.
311     OS << " (\"";
312     OS.write_escaped(Tok.getString());
313     OS << "\")\n";
314   }
315
316   return Error;
317 }
318
319 static int AssembleInput(const char *ProgName, const Target *TheTarget,
320                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
321                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
322                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
323   std::unique_ptr<MCAsmParser> Parser(
324       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
325   std::unique_ptr<MCTargetAsmParser> TAP(
326       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
327
328   if (!TAP) {
329     errs() << ProgName
330            << ": error: this target does not support assembly parsing.\n";
331     return 1;
332   }
333
334   Parser->setShowParsedOperands(ShowInstOperands);
335   Parser->setTargetParser(*TAP);
336
337   int Res = Parser->Run(NoInitialTextSection);
338
339   return Res;
340 }
341
342 int main(int argc, char **argv) {
343   // Print a stack trace if we signal out.
344   sys::PrintStackTraceOnErrorSignal();
345   PrettyStackTraceProgram X(argc, argv);
346   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
347
348   // Initialize targets and assembly printers/parsers.
349   llvm::InitializeAllTargetInfos();
350   llvm::InitializeAllTargetMCs();
351   llvm::InitializeAllAsmParsers();
352   llvm::InitializeAllDisassemblers();
353
354   // Register the target printer for --version.
355   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
356
357   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
358   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
359   TripleName = Triple::normalize(TripleName);
360   setDwarfDebugFlags(argc, argv);
361
362   setDwarfDebugProducer();
363
364   const char *ProgName = argv[0];
365   const Target *TheTarget = GetTarget(ProgName);
366   if (!TheTarget)
367     return 1;
368
369   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
370       MemoryBuffer::getFileOrSTDIN(InputFilename);
371   if (std::error_code EC = BufferPtr.getError()) {
372     errs() << ProgName << ": " << EC.message() << '\n';
373     return 1;
374   }
375   MemoryBuffer *Buffer = BufferPtr->get();
376
377   SourceMgr SrcMgr;
378
379   // Tell SrcMgr about this buffer, which is what the parser will pick up.
380   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
381
382   // Record the location of the include directories so that the lexer can find
383   // it later.
384   SrcMgr.setIncludeDirs(IncludeDirs);
385
386   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
387   assert(MRI && "Unable to create target register info!");
388
389   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
390   assert(MAI && "Unable to create target asm info!");
391
392   if (CompressDebugSections) {
393     if (!zlib::isAvailable()) {
394       errs() << ProgName
395              << ": build tools with zlib to enable -compress-debug-sections";
396       return 1;
397     }
398     MAI->setCompressDebugSections(true);
399   }
400
401   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
402   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
403   MCObjectFileInfo MOFI;
404   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
405   MOFI.InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
406
407   if (SaveTempLabels)
408     Ctx.setAllowTemporaryLabels(false);
409
410   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
411   // Default to 4 for dwarf version.
412   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
413   if (DwarfVersion < 2 || DwarfVersion > 4) {
414     errs() << ProgName << ": Dwarf version " << DwarfVersion
415            << " is not supported." << '\n';
416     return 1;
417   }
418   Ctx.setDwarfVersion(DwarfVersion);
419   if (!DwarfDebugFlags.empty())
420     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
421   if (!DwarfDebugProducer.empty())
422     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
423   if (!DebugCompilationDir.empty())
424     Ctx.setCompilationDir(DebugCompilationDir);
425   if (!MainFileName.empty())
426     Ctx.setMainFileName(MainFileName);
427
428   // Package up features to be passed to target/subtarget
429   std::string FeaturesStr;
430   if (MAttrs.size()) {
431     SubtargetFeatures Features;
432     for (unsigned i = 0; i != MAttrs.size(); ++i)
433       Features.AddFeature(MAttrs[i]);
434     FeaturesStr = Features.getString();
435   }
436
437   std::unique_ptr<tool_output_file> Out = GetOutputStream();
438   if (!Out)
439     return 1;
440
441   formatted_raw_ostream FOS(Out->os());
442   std::unique_ptr<MCStreamer> Str;
443
444   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
445   std::unique_ptr<MCSubtargetInfo> STI(
446       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
447
448   MCInstPrinter *IP = nullptr;
449   if (FileType == OFT_AssemblyFile) {
450     IP =
451       TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
452
453     // Set the display preference for hex vs. decimal immediates.
454     IP->setPrintImmHex(PrintImmHex);
455
456     // Set up the AsmStreamer.
457     MCCodeEmitter *CE = nullptr;
458     MCAsmBackend *MAB = nullptr;
459     if (ShowEncoding) {
460       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
461       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
462     }
463     Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/ true,
464                                            /*useDwarfDirectory*/ true, IP, CE,
465                                            MAB, ShowInst));
466
467   } else if (FileType == OFT_Null) {
468     Str.reset(createNullStreamer(Ctx));
469   } else {
470     assert(FileType == OFT_ObjectFile && "Invalid file type!");
471     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
472     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
473     Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB, FOS, CE,
474                                                 *STI, RelaxAll));
475     if (NoExecStack)
476       Str->InitSections(true);
477   }
478
479   int Res = 1;
480   bool disassemble = false;
481   switch (Action) {
482   case AC_AsLex:
483     Res = AsLexInput(SrcMgr, *MAI, Out->os());
484     break;
485   case AC_Assemble:
486     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
487                         *MCII, MCOptions);
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 }