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