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