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