OSDN Git Service

Reapply "[DWARFv5] Emit file 0 to the line table."
[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/MCCodeEmitter.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.h"
23 #include "llvm/MC/MCParser/AsmLexer.h"
24 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
25 #include "llvm/MC/MCRegisterInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.def"
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<bool> RelaxELFRel(
56     "relax-relocations", cl::init(true),
57     cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
58
59 static cl::opt<DebugCompressionType> CompressDebugSections(
60     "compress-debug-sections", cl::ValueOptional,
61     cl::init(DebugCompressionType::None),
62     cl::desc("Choose DWARF debug sections compression:"),
63     cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
64                clEnumValN(DebugCompressionType::Z, "zlib",
65                           "Use zlib compression"),
66                clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
67                           "Use zlib-gnu compression (deprecated)")));
68
69 static cl::opt<bool>
70 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
71
72 static cl::opt<bool>
73 ShowInstOperands("show-inst-operands",
74                  cl::desc("Show instructions operands as parsed"));
75
76 static cl::opt<unsigned>
77 OutputAsmVariant("output-asm-variant",
78                  cl::desc("Syntax variant to use for output printing"));
79
80 static cl::opt<bool>
81 PrintImmHex("print-imm-hex", cl::init(false),
82             cl::desc("Prefer hex format for immediate values"));
83
84 static cl::list<std::string>
85 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
86
87 static cl::opt<bool>
88     PreserveComments("preserve-comments",
89                      cl::desc("Preserve Comments in outputted assembly"));
90
91 enum OutputFileType {
92   OFT_Null,
93   OFT_AssemblyFile,
94   OFT_ObjectFile
95 };
96 static cl::opt<OutputFileType>
97 FileType("filetype", cl::init(OFT_AssemblyFile),
98   cl::desc("Choose an output file type:"),
99   cl::values(
100        clEnumValN(OFT_AssemblyFile, "asm",
101                   "Emit an assembly ('.s') file"),
102        clEnumValN(OFT_Null, "null",
103                   "Don't emit anything (for timing purposes)"),
104        clEnumValN(OFT_ObjectFile, "obj",
105                   "Emit a native object ('.o') file")));
106
107 static cl::list<std::string>
108 IncludeDirs("I", cl::desc("Directory of include files"),
109             cl::value_desc("directory"), cl::Prefix);
110
111 static cl::opt<std::string>
112 ArchName("arch", cl::desc("Target arch to assemble for, "
113                           "see -version for available targets"));
114
115 static cl::opt<std::string>
116 TripleName("triple", cl::desc("Target triple to assemble for, "
117                               "see -version for available targets"));
118
119 static cl::opt<std::string>
120 MCPU("mcpu",
121      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
122      cl::value_desc("cpu-name"),
123      cl::init(""));
124
125 static cl::list<std::string>
126 MAttrs("mattr",
127   cl::CommaSeparated,
128   cl::desc("Target specific attributes (-mattr=help for details)"),
129   cl::value_desc("a1,+a2,-a3,..."));
130
131 static cl::opt<bool> PIC("position-independent",
132                          cl::desc("Position independent"), cl::init(false));
133
134 static cl::opt<bool>
135     LargeCodeModel("large-code-model",
136                    cl::desc("Create cfi directives that assume the code might "
137                             "be more than 2gb away"));
138
139 static cl::opt<bool>
140 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
141                                    "in the text section"));
142
143 static cl::opt<bool>
144 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
145                                   "source files"));
146
147 static cl::opt<std::string>
148 DebugCompilationDir("fdebug-compilation-dir",
149                     cl::desc("Specifies the debug info's compilation dir"));
150
151 static cl::opt<std::string>
152 MainFileName("main-file-name",
153              cl::desc("Specifies the name we should consider the input file"));
154
155 static cl::opt<bool> SaveTempLabels("save-temp-labels",
156                                     cl::desc("Don't discard temporary labels"));
157
158 static cl::opt<bool> NoExecStack("no-exec-stack",
159                                  cl::desc("File doesn't need an exec stack"));
160
161 enum ActionType {
162   AC_AsLex,
163   AC_Assemble,
164   AC_Disassemble,
165   AC_MDisassemble,
166 };
167
168 static cl::opt<ActionType>
169 Action(cl::desc("Action to perform:"),
170        cl::init(AC_Assemble),
171        cl::values(clEnumValN(AC_AsLex, "as-lex",
172                              "Lex tokens from a .s file"),
173                   clEnumValN(AC_Assemble, "assemble",
174                              "Assemble a .s file (default)"),
175                   clEnumValN(AC_Disassemble, "disassemble",
176                              "Disassemble strings of hex bytes"),
177                   clEnumValN(AC_MDisassemble, "mdis",
178                              "Marked up disassembly of strings of hex bytes")));
179
180 static const Target *GetTarget(const char *ProgName) {
181   // Figure out the target triple.
182   if (TripleName.empty())
183     TripleName = sys::getDefaultTargetTriple();
184   Triple TheTriple(Triple::normalize(TripleName));
185
186   // Get the target specific parser.
187   std::string Error;
188   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
189                                                          Error);
190   if (!TheTarget) {
191     errs() << ProgName << ": " << Error;
192     return nullptr;
193   }
194
195   // Update the triple name and return the found target.
196   TripleName = TheTriple.getTriple();
197   return TheTarget;
198 }
199
200 static std::unique_ptr<ToolOutputFile> GetOutputStream() {
201   if (OutputFilename == "")
202     OutputFilename = "-";
203
204   std::error_code EC;
205   auto Out =
206       llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
207   if (EC) {
208     errs() << EC.message() << '\n';
209     return nullptr;
210   }
211
212   return Out;
213 }
214
215 static std::string DwarfDebugFlags;
216 static void setDwarfDebugFlags(int argc, char **argv) {
217   if (!getenv("RC_DEBUG_OPTIONS"))
218     return;
219   for (int i = 0; i < argc; i++) {
220     DwarfDebugFlags += argv[i];
221     if (i + 1 < argc)
222       DwarfDebugFlags += " ";
223   }
224 }
225
226 static std::string DwarfDebugProducer;
227 static void setDwarfDebugProducer() {
228   if(!getenv("DEBUG_PRODUCER"))
229     return;
230   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
231 }
232
233 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
234                       raw_ostream &OS) {
235
236   AsmLexer Lexer(MAI);
237   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
238
239   bool Error = false;
240   while (Lexer.Lex().isNot(AsmToken::Eof)) {
241     Lexer.getTok().dump(OS);
242     OS << "\n";
243     if (Lexer.getTok().getKind() == AsmToken::Error)
244       Error = true;
245   }
246
247   return Error;
248 }
249
250 static int fillCommandLineSymbols(MCAsmParser &Parser) {
251   for (auto &I: DefineSymbol) {
252     auto Pair = StringRef(I).split('=');
253     auto Sym = Pair.first;
254     auto Val = Pair.second;
255
256     if (Sym.empty() || Val.empty()) {
257       errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
258       return 1;
259     }
260     int64_t Value;
261     if (Val.getAsInteger(0, Value)) {
262       errs() << "error: Value is not an integer: " << Val << "\n";
263       return 1;
264     }
265     Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
266   }
267   return 0;
268 }
269
270 static int AssembleInput(const char *ProgName, const Target *TheTarget,
271                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
272                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
273                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
274   std::unique_ptr<MCAsmParser> Parser(
275       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
276   std::unique_ptr<MCTargetAsmParser> TAP(
277       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
278
279   if (!TAP) {
280     errs() << ProgName
281            << ": error: this target does not support assembly parsing.\n";
282     return 1;
283   }
284
285   int SymbolResult = fillCommandLineSymbols(*Parser);
286   if(SymbolResult)
287     return SymbolResult;
288   Parser->setShowParsedOperands(ShowInstOperands);
289   Parser->setTargetParser(*TAP);
290
291   int Res = Parser->Run(NoInitialTextSection);
292
293   return Res;
294 }
295
296 int main(int argc, char **argv) {
297   // Print a stack trace if we signal out.
298   sys::PrintStackTraceOnErrorSignal(argv[0]);
299   PrettyStackTraceProgram X(argc, argv);
300   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
301
302   // Initialize targets and assembly printers/parsers.
303   llvm::InitializeAllTargetInfos();
304   llvm::InitializeAllTargetMCs();
305   llvm::InitializeAllAsmParsers();
306   llvm::InitializeAllDisassemblers();
307
308   // Register the target printer for --version.
309   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
310
311   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
312   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
313   TripleName = Triple::normalize(TripleName);
314   setDwarfDebugFlags(argc, argv);
315
316   setDwarfDebugProducer();
317
318   const char *ProgName = argv[0];
319   const Target *TheTarget = GetTarget(ProgName);
320   if (!TheTarget)
321     return 1;
322   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
323   // construct the Triple object.
324   Triple TheTriple(TripleName);
325
326   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
327       MemoryBuffer::getFileOrSTDIN(InputFilename);
328   if (std::error_code EC = BufferPtr.getError()) {
329     errs() << InputFilename << ": " << EC.message() << '\n';
330     return 1;
331   }
332   MemoryBuffer *Buffer = BufferPtr->get();
333
334   SourceMgr SrcMgr;
335
336   // Tell SrcMgr about this buffer, which is what the parser will pick up.
337   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
338
339   // Record the location of the include directories so that the lexer can find
340   // it later.
341   SrcMgr.setIncludeDirs(IncludeDirs);
342
343   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
344   assert(MRI && "Unable to create target register info!");
345
346   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
347   assert(MAI && "Unable to create target asm info!");
348
349   MAI->setRelaxELFRelocations(RelaxELFRel);
350
351   if (CompressDebugSections != DebugCompressionType::None) {
352     if (!zlib::isAvailable()) {
353       errs() << ProgName
354              << ": build tools with zlib to enable -compress-debug-sections";
355       return 1;
356     }
357     MAI->setCompressDebugSections(CompressDebugSections);
358   }
359   MAI->setPreserveAsmComments(PreserveComments);
360
361   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
362   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
363   MCObjectFileInfo MOFI;
364   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
365   MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
366
367   if (SaveTempLabels)
368     Ctx.setAllowTemporaryLabels(false);
369
370   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
371   // Default to 4 for dwarf version.
372   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
373   if (DwarfVersion < 2 || DwarfVersion > 5) {
374     errs() << ProgName << ": Dwarf version " << DwarfVersion
375            << " is not supported." << '\n';
376     return 1;
377   }
378   Ctx.setDwarfVersion(DwarfVersion);
379   if (!DwarfDebugFlags.empty())
380     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
381   if (!DwarfDebugProducer.empty())
382     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
383   if (!DebugCompilationDir.empty())
384     Ctx.setCompilationDir(DebugCompilationDir);
385   else {
386     // If no compilation dir is set, try to use the current directory.
387     SmallString<128> CWD;
388     if (!sys::fs::current_path(CWD))
389       Ctx.setCompilationDir(CWD);
390   }
391   if (!MainFileName.empty())
392     Ctx.setMainFileName(MainFileName);
393   if (DwarfVersion >= 5) {
394     // DWARF v5 needs the root file as well as the compilation directory.
395     // If we find a '.file 0' directive that will supersede these values.
396     MD5 Hash;
397     MD5::MD5Result *Cksum =
398         (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
399     Hash.update(Buffer->getBuffer());
400     Hash.final(*Cksum);
401     Ctx.setMCLineTableRootFile(
402         /*CUID=*/0, Ctx.getCompilationDir(),
403         !MainFileName.empty() ? MainFileName : InputFilename, Cksum, None);
404   }
405
406   // Package up features to be passed to target/subtarget
407   std::string FeaturesStr;
408   if (MAttrs.size()) {
409     SubtargetFeatures Features;
410     for (unsigned i = 0; i != MAttrs.size(); ++i)
411       Features.AddFeature(MAttrs[i]);
412     FeaturesStr = Features.getString();
413   }
414
415   std::unique_ptr<ToolOutputFile> Out = GetOutputStream();
416   if (!Out)
417     return 1;
418
419   std::unique_ptr<buffer_ostream> BOS;
420   raw_pwrite_stream *OS = &Out->os();
421   std::unique_ptr<MCStreamer> Str;
422
423   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
424   std::unique_ptr<MCSubtargetInfo> STI(
425       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
426
427   MCInstPrinter *IP = nullptr;
428   if (FileType == OFT_AssemblyFile) {
429     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
430                                         *MAI, *MCII, *MRI);
431
432     if (!IP) {
433       errs()
434           << "error: unable to create instruction printer for target triple '"
435           << TheTriple.normalize() << "' with assembly variant "
436           << OutputAsmVariant << ".\n";
437       return 1;
438     }
439
440     // Set the display preference for hex vs. decimal immediates.
441     IP->setPrintImmHex(PrintImmHex);
442
443     // Set up the AsmStreamer.
444     MCCodeEmitter *CE = nullptr;
445     MCAsmBackend *MAB = nullptr;
446     if (ShowEncoding) {
447       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
448       MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
449     }
450     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
451     Str.reset(TheTarget->createAsmStreamer(
452         Ctx, std::move(FOut), /*asmverbose*/ true,
453         /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
454
455   } else if (FileType == OFT_Null) {
456     Str.reset(TheTarget->createNullStreamer(Ctx));
457   } else {
458     assert(FileType == OFT_ObjectFile && "Invalid file type!");
459
460     // Don't waste memory on names of temp labels.
461     Ctx.setUseNamesOnTempLabels(false);
462
463     if (!Out->os().supportsSeeking()) {
464       BOS = make_unique<buffer_ostream>(Out->os());
465       OS = BOS.get();
466     }
467
468     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
469     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
470     Str.reset(TheTarget->createMCObjectStreamer(
471         TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *OS,
472         std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
473         MCOptions.MCIncrementalLinkerCompatible,
474         /*DWARFMustBeAtTheEnd*/ false));
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 }