OSDN Git Service

Recommit 270977 - [llvm-mc] - Teach llvm-mc to generate zlib styled compression sections.
[android-x86/external-llvm.git] / tools / llvm-mc / llvm-mc.cpp
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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/MCParser/MCTargetAsmParser.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/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
43 using namespace llvm;
44
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50                cl::value_desc("filename"));
51
52 static cl::opt<bool>
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54
55 static cl::opt<DebugCompressionType>
56 CompressDebugSections("compress-debug-sections", cl::ValueOptional,
57   cl::init(DebugCompressionType::DCT_None),
58   cl::desc("Choose DWARF debug sections compression:"),
59   cl::values(
60     clEnumValN(DebugCompressionType::DCT_None, "none",
61       "No compression"),
62     clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
63       "Use zlib compression"),
64     clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
65       "Use zlib-gnu compression (depricated)"),
66     clEnumValEnd));
67
68 static cl::opt<bool>
69 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
70
71 static cl::opt<bool>
72 ShowInstOperands("show-inst-operands",
73                  cl::desc("Show instructions operands as parsed"));
74
75 static cl::opt<unsigned>
76 OutputAsmVariant("output-asm-variant",
77                  cl::desc("Syntax variant to use for output printing"));
78
79 static cl::opt<bool>
80 PrintImmHex("print-imm-hex", cl::init(false),
81             cl::desc("Prefer hex format for immediate values"));
82
83 static cl::list<std::string>
84 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
85
86 enum OutputFileType {
87   OFT_Null,
88   OFT_AssemblyFile,
89   OFT_ObjectFile
90 };
91 static cl::opt<OutputFileType>
92 FileType("filetype", cl::init(OFT_AssemblyFile),
93   cl::desc("Choose an output file type:"),
94   cl::values(
95        clEnumValN(OFT_AssemblyFile, "asm",
96                   "Emit an assembly ('.s') file"),
97        clEnumValN(OFT_Null, "null",
98                   "Don't emit anything (for timing purposes)"),
99        clEnumValN(OFT_ObjectFile, "obj",
100                   "Emit a native object ('.o') file"),
101        clEnumValEnd));
102
103 static cl::list<std::string>
104 IncludeDirs("I", cl::desc("Directory of include files"),
105             cl::value_desc("directory"), cl::Prefix);
106
107 static cl::opt<std::string>
108 ArchName("arch", cl::desc("Target arch to assemble for, "
109                           "see -version for available targets"));
110
111 static cl::opt<std::string>
112 TripleName("triple", cl::desc("Target triple to assemble for, "
113                               "see -version for available targets"));
114
115 static cl::opt<std::string>
116 MCPU("mcpu",
117      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
118      cl::value_desc("cpu-name"),
119      cl::init(""));
120
121 static cl::list<std::string>
122 MAttrs("mattr",
123   cl::CommaSeparated,
124   cl::desc("Target specific attributes (-mattr=help for details)"),
125   cl::value_desc("a1,+a2,-a3,..."));
126
127 static cl::opt<bool> PIC("position-independent",
128                          cl::desc("Position independent"), cl::init(false));
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 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
152                                   "source files"));
153
154 static cl::opt<std::string>
155 DebugCompilationDir("fdebug-compilation-dir",
156                     cl::desc("Specifies the debug info's compilation dir"));
157
158 static cl::opt<std::string>
159 MainFileName("main-file-name",
160              cl::desc("Specifies the name we should consider the input file"));
161
162 static cl::opt<bool> SaveTempLabels("save-temp-labels",
163                                     cl::desc("Don't discard temporary labels"));
164
165 static cl::opt<bool> NoExecStack("no-exec-stack",
166                                  cl::desc("File doesn't need an exec stack"));
167
168 enum ActionType {
169   AC_AsLex,
170   AC_Assemble,
171   AC_Disassemble,
172   AC_MDisassemble,
173 };
174
175 static cl::opt<ActionType>
176 Action(cl::desc("Action to perform:"),
177        cl::init(AC_Assemble),
178        cl::values(clEnumValN(AC_AsLex, "as-lex",
179                              "Lex tokens from a .s file"),
180                   clEnumValN(AC_Assemble, "assemble",
181                              "Assemble a .s file (default)"),
182                   clEnumValN(AC_Disassemble, "disassemble",
183                              "Disassemble strings of hex bytes"),
184                   clEnumValN(AC_MDisassemble, "mdis",
185                              "Marked up disassembly of strings of hex bytes"),
186                   clEnumValEnd));
187
188 static const Target *GetTarget(const char *ProgName) {
189   // Figure out the target triple.
190   if (TripleName.empty())
191     TripleName = sys::getDefaultTargetTriple();
192   Triple TheTriple(Triple::normalize(TripleName));
193
194   // Get the target specific parser.
195   std::string Error;
196   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
197                                                          Error);
198   if (!TheTarget) {
199     errs() << ProgName << ": " << Error;
200     return nullptr;
201   }
202
203   // Update the triple name and return the found target.
204   TripleName = TheTriple.getTriple();
205   return TheTarget;
206 }
207
208 static std::unique_ptr<tool_output_file> GetOutputStream() {
209   if (OutputFilename == "")
210     OutputFilename = "-";
211
212   std::error_code EC;
213   auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
214                                                  sys::fs::F_None);
215   if (EC) {
216     errs() << EC.message() << '\n';
217     return nullptr;
218   }
219
220   return Out;
221 }
222
223 static std::string DwarfDebugFlags;
224 static void setDwarfDebugFlags(int argc, char **argv) {
225   if (!getenv("RC_DEBUG_OPTIONS"))
226     return;
227   for (int i = 0; i < argc; i++) {
228     DwarfDebugFlags += argv[i];
229     if (i + 1 < argc)
230       DwarfDebugFlags += " ";
231   }
232 }
233
234 static std::string DwarfDebugProducer;
235 static void setDwarfDebugProducer() {
236   if(!getenv("DEBUG_PRODUCER"))
237     return;
238   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
239 }
240
241 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
242                       raw_ostream &OS) {
243
244   AsmLexer Lexer(MAI);
245   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
246
247   bool Error = false;
248   while (Lexer.Lex().isNot(AsmToken::Eof)) {
249     AsmToken Tok = Lexer.getTok();
250
251     switch (Tok.getKind()) {
252     default:
253       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
254                           "unknown token");
255       Error = true;
256       break;
257     case AsmToken::Error:
258       Error = true; // error already printed.
259       break;
260     case AsmToken::Identifier:
261       OS << "identifier: " << Lexer.getTok().getString();
262       break;
263     case AsmToken::Integer:
264       OS << "int: " << Lexer.getTok().getString();
265       break;
266     case AsmToken::Real:
267       OS << "real: " << Lexer.getTok().getString();
268       break;
269     case AsmToken::String:
270       OS << "string: " << Lexer.getTok().getString();
271       break;
272
273     case AsmToken::Amp:            OS << "Amp"; break;
274     case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
275     case AsmToken::At:             OS << "At"; break;
276     case AsmToken::Caret:          OS << "Caret"; break;
277     case AsmToken::Colon:          OS << "Colon"; break;
278     case AsmToken::Comma:          OS << "Comma"; break;
279     case AsmToken::Dollar:         OS << "Dollar"; break;
280     case AsmToken::Dot:            OS << "Dot"; break;
281     case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
282     case AsmToken::Eof:            OS << "Eof"; break;
283     case AsmToken::Equal:          OS << "Equal"; break;
284     case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
285     case AsmToken::Exclaim:        OS << "Exclaim"; break;
286     case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
287     case AsmToken::Greater:        OS << "Greater"; break;
288     case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
289     case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
290     case AsmToken::Hash:           OS << "Hash"; break;
291     case AsmToken::LBrac:          OS << "LBrac"; break;
292     case AsmToken::LCurly:         OS << "LCurly"; break;
293     case AsmToken::LParen:         OS << "LParen"; break;
294     case AsmToken::Less:           OS << "Less"; break;
295     case AsmToken::LessEqual:      OS << "LessEqual"; break;
296     case AsmToken::LessGreater:    OS << "LessGreater"; break;
297     case AsmToken::LessLess:       OS << "LessLess"; break;
298     case AsmToken::Minus:          OS << "Minus"; break;
299     case AsmToken::Percent:        OS << "Percent"; break;
300     case AsmToken::Pipe:           OS << "Pipe"; break;
301     case AsmToken::PipePipe:       OS << "PipePipe"; break;
302     case AsmToken::Plus:           OS << "Plus"; break;
303     case AsmToken::RBrac:          OS << "RBrac"; break;
304     case AsmToken::RCurly:         OS << "RCurly"; break;
305     case AsmToken::RParen:         OS << "RParen"; break;
306     case AsmToken::Slash:          OS << "Slash"; break;
307     case AsmToken::Star:           OS << "Star"; break;
308     case AsmToken::Tilde:          OS << "Tilde"; break;
309     }
310
311     // Print the token string.
312     OS << " (\"";
313     OS.write_escaped(Tok.getString());
314     OS << "\")\n";
315   }
316
317   return Error;
318 }
319
320 static int fillCommandLineSymbols(MCAsmParser &Parser){
321   for(auto &I: DefineSymbol){
322     auto Pair = StringRef(I).split('=');
323     if(Pair.second.empty()){
324       errs() << "error: defsym must be of the form: sym=value: " << I;
325       return 1;
326     }
327     int64_t Value;
328     if(Pair.second.getAsInteger(0, Value)){
329       errs() << "error: Value is not an integer: " << Pair.second;
330       return 1;
331     }
332     auto &Context = Parser.getContext();
333     auto Symbol = Context.getOrCreateSymbol(Pair.first);
334     Parser.getStreamer().EmitAssignment(Symbol,
335                                         MCConstantExpr::create(Value, Context));
336   }
337   return 0;
338 }
339
340 static int AssembleInput(const char *ProgName, const Target *TheTarget,
341                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
342                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
343                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
344   std::unique_ptr<MCAsmParser> Parser(
345       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
346   std::unique_ptr<MCTargetAsmParser> TAP(
347       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
348
349   if (!TAP) {
350     errs() << ProgName
351            << ": error: this target does not support assembly parsing.\n";
352     return 1;
353   }
354
355   int SymbolResult = fillCommandLineSymbols(*Parser);
356   if(SymbolResult)
357     return SymbolResult;
358   Parser->setShowParsedOperands(ShowInstOperands);
359   Parser->setTargetParser(*TAP);
360
361   int Res = Parser->Run(NoInitialTextSection);
362
363   return Res;
364 }
365
366 int main(int argc, char **argv) {
367   // Print a stack trace if we signal out.
368   sys::PrintStackTraceOnErrorSignal();
369   PrettyStackTraceProgram X(argc, argv);
370   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
371
372   // Initialize targets and assembly printers/parsers.
373   llvm::InitializeAllTargetInfos();
374   llvm::InitializeAllTargetMCs();
375   llvm::InitializeAllAsmParsers();
376   llvm::InitializeAllDisassemblers();
377
378   // Register the target printer for --version.
379   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
380
381   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
382   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
383   TripleName = Triple::normalize(TripleName);
384   setDwarfDebugFlags(argc, argv);
385
386   setDwarfDebugProducer();
387
388   const char *ProgName = argv[0];
389   const Target *TheTarget = GetTarget(ProgName);
390   if (!TheTarget)
391     return 1;
392   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
393   // construct the Triple object.
394   Triple TheTriple(TripleName);
395
396   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
397       MemoryBuffer::getFileOrSTDIN(InputFilename);
398   if (std::error_code EC = BufferPtr.getError()) {
399     errs() << InputFilename << ": " << EC.message() << '\n';
400     return 1;
401   }
402   MemoryBuffer *Buffer = BufferPtr->get();
403
404   SourceMgr SrcMgr;
405
406   // Tell SrcMgr about this buffer, which is what the parser will pick up.
407   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
408
409   // Record the location of the include directories so that the lexer can find
410   // it later.
411   SrcMgr.setIncludeDirs(IncludeDirs);
412
413   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
414   assert(MRI && "Unable to create target register info!");
415
416   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
417   assert(MAI && "Unable to create target asm info!");
418
419   if (CompressDebugSections != DebugCompressionType::DCT_None) {
420     if (!zlib::isAvailable()) {
421       errs() << ProgName
422              << ": build tools with zlib to enable -compress-debug-sections";
423       return 1;
424     }
425     MAI->setCompressDebugSections(CompressDebugSections);
426   }
427
428   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
429   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
430   MCObjectFileInfo MOFI;
431   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
432   MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
433
434   if (SaveTempLabels)
435     Ctx.setAllowTemporaryLabels(false);
436
437   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
438   // Default to 4 for dwarf version.
439   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
440   if (DwarfVersion < 2 || DwarfVersion > 4) {
441     errs() << ProgName << ": Dwarf version " << DwarfVersion
442            << " is not supported." << '\n';
443     return 1;
444   }
445   Ctx.setDwarfVersion(DwarfVersion);
446   if (!DwarfDebugFlags.empty())
447     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
448   if (!DwarfDebugProducer.empty())
449     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
450   if (!DebugCompilationDir.empty())
451     Ctx.setCompilationDir(DebugCompilationDir);
452   else {
453     // If no compilation dir is set, try to use the current directory.
454     SmallString<128> CWD;
455     if (!sys::fs::current_path(CWD))
456       Ctx.setCompilationDir(CWD);
457   }
458   if (!MainFileName.empty())
459     Ctx.setMainFileName(MainFileName);
460
461   // Package up features to be passed to target/subtarget
462   std::string FeaturesStr;
463   if (MAttrs.size()) {
464     SubtargetFeatures Features;
465     for (unsigned i = 0; i != MAttrs.size(); ++i)
466       Features.AddFeature(MAttrs[i]);
467     FeaturesStr = Features.getString();
468   }
469
470   std::unique_ptr<tool_output_file> Out = GetOutputStream();
471   if (!Out)
472     return 1;
473
474   std::unique_ptr<buffer_ostream> BOS;
475   raw_pwrite_stream *OS = &Out->os();
476   std::unique_ptr<MCStreamer> Str;
477
478   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
479   std::unique_ptr<MCSubtargetInfo> STI(
480       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
481
482   MCInstPrinter *IP = nullptr;
483   if (FileType == OFT_AssemblyFile) {
484     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
485                                         *MAI, *MCII, *MRI);
486
487     // Set the display preference for hex vs. decimal immediates.
488     IP->setPrintImmHex(PrintImmHex);
489
490     // Set up the AsmStreamer.
491     MCCodeEmitter *CE = nullptr;
492     MCAsmBackend *MAB = nullptr;
493     if (ShowEncoding) {
494       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
495       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
496     }
497     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
498     Str.reset(TheTarget->createAsmStreamer(
499         Ctx, std::move(FOut), /*asmverbose*/ true,
500         /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
501
502   } else if (FileType == OFT_Null) {
503     Str.reset(TheTarget->createNullStreamer(Ctx));
504   } else {
505     assert(FileType == OFT_ObjectFile && "Invalid file type!");
506
507     // Don't waste memory on names of temp labels.
508     Ctx.setUseNamesOnTempLabels(false);
509
510     if (!Out->os().supportsSeeking()) {
511       BOS = make_unique<buffer_ostream>(Out->os());
512       OS = BOS.get();
513     }
514
515     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
516     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
517     Str.reset(TheTarget->createMCObjectStreamer(
518         TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
519         MCOptions.MCIncrementalLinkerCompatible,
520         /*DWARFMustBeAtTheEnd*/ false));
521     if (NoExecStack)
522       Str->InitSections(true);
523   }
524
525   int Res = 1;
526   bool disassemble = false;
527   switch (Action) {
528   case AC_AsLex:
529     Res = AsLexInput(SrcMgr, *MAI, Out->os());
530     break;
531   case AC_Assemble:
532     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
533                         *MCII, MCOptions);
534     break;
535   case AC_MDisassemble:
536     assert(IP && "Expected assembly output");
537     IP->setUseMarkup(1);
538     disassemble = true;
539     break;
540   case AC_Disassemble:
541     disassemble = true;
542     break;
543   }
544   if (disassemble)
545     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
546                                     *Buffer, SrcMgr, Out->os());
547
548   // Keep output if no errors.
549   if (Res == 0) Out->keep();
550   return Res;
551 }