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