1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows command line hacking on machine
13 //===----------------------------------------------------------------------===//
15 #include "llvm/MC/MCParser/AsmLexer.h"
16 #include "llvm/MC/MCParser/MCAsmLexer.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCCodeEmitter.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.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/MCTargetAsmParser.h"
29 #include "llvm/MC/SubtargetFeature.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/FormattedStream.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/ToolOutputFile.h"
39 #include "llvm/Support/Host.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/system_error.h"
44 #include "Disassembler.h"
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
50 static cl::opt<std::string>
51 OutputFilename("o", cl::desc("Output filename"),
52 cl::value_desc("filename"));
55 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
58 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
61 ShowInstOperands("show-inst-operands",
62 cl::desc("Show instructions operands as parsed"));
64 static cl::opt<unsigned>
65 OutputAsmVariant("output-asm-variant",
66 cl::desc("Syntax variant to use for output printing"));
69 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
72 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
79 static cl::opt<OutputFileType>
80 FileType("filetype", cl::init(OFT_AssemblyFile),
81 cl::desc("Choose an output file type:"),
83 clEnumValN(OFT_AssemblyFile, "asm",
84 "Emit an assembly ('.s') file"),
85 clEnumValN(OFT_Null, "null",
86 "Don't emit anything (for timing purposes)"),
87 clEnumValN(OFT_ObjectFile, "obj",
88 "Emit a native object ('.o') file"),
91 static cl::list<std::string>
92 IncludeDirs("I", cl::desc("Directory of include files"),
93 cl::value_desc("directory"), cl::Prefix);
95 static cl::opt<std::string>
96 ArchName("arch", cl::desc("Target arch to assemble for, "
97 "see -version for available targets"));
99 static cl::opt<std::string>
100 TripleName("triple", cl::desc("Target triple to assemble for, "
101 "see -version for available targets"));
103 static cl::opt<std::string>
105 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
106 cl::value_desc("cpu-name"),
109 static cl::list<std::string>
112 cl::desc("Target specific attributes (-mattr=help for details)"),
113 cl::value_desc("a1,+a2,-a3,..."));
115 static cl::opt<Reloc::Model>
116 RelocModel("relocation-model",
117 cl::desc("Choose relocation model"),
118 cl::init(Reloc::Default),
120 clEnumValN(Reloc::Default, "default",
121 "Target default relocation model"),
122 clEnumValN(Reloc::Static, "static",
123 "Non-relocatable code"),
124 clEnumValN(Reloc::PIC_, "pic",
125 "Fully relocatable, position independent code"),
126 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
127 "Relocatable external references, non-relocatable code"),
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",
138 clEnumValN(CodeModel::Kernel, "kernel",
139 "Kernel code model"),
140 clEnumValN(CodeModel::Medium, "medium",
141 "Medium code model"),
142 clEnumValN(CodeModel::Large, "large",
147 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
148 "in the text section"));
151 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
154 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
164 static cl::opt<ActionType>
165 Action(cl::desc("Action to perform:"),
166 cl::init(AC_Assemble),
167 cl::values(clEnumValN(AC_AsLex, "as-lex",
168 "Lex tokens from a .s file"),
169 clEnumValN(AC_Assemble, "assemble",
170 "Assemble a .s file (default)"),
171 clEnumValN(AC_Disassemble, "disassemble",
172 "Disassemble strings of hex bytes"),
173 clEnumValN(AC_EDisassemble, "edis",
174 "Enhanced disassembly of strings of hex bytes"),
177 static const Target *GetTarget(const char *ProgName) {
178 // Figure out the target triple.
179 if (TripleName.empty())
180 TripleName = sys::getDefaultTargetTriple();
181 Triple TheTriple(Triple::normalize(TripleName));
183 const Target *TheTarget = 0;
184 if (!ArchName.empty()) {
185 for (TargetRegistry::iterator it = TargetRegistry::begin(),
186 ie = TargetRegistry::end(); it != ie; ++it) {
187 if (ArchName == it->getName()) {
194 errs() << ProgName << ": error: invalid target '" << ArchName << "'.\n";
198 // Adjust the triple to match (if known), otherwise stick with the
199 // module/host triple.
200 Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName);
201 if (Type != Triple::UnknownArch)
202 TheTriple.setArch(Type);
204 // Get the target specific parser.
206 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
207 if (TheTarget == 0) {
208 errs() << ProgName << ": error: unable to get target for '"
209 << TheTriple.getTriple()
210 << "', see --version and --triple.\n";
215 TripleName = TheTriple.getTriple();
219 static tool_output_file *GetOutputStream() {
220 if (OutputFilename == "")
221 OutputFilename = "-";
224 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
225 raw_fd_ostream::F_Binary);
227 errs() << Err << '\n';
235 static std::string DwarfDebugFlags;
236 static void setDwarfDebugFlags(int argc, char **argv) {
237 if (!getenv("RC_DEBUG_OPTIONS"))
239 for (int i = 0; i < argc; i++) {
240 DwarfDebugFlags += argv[i];
242 DwarfDebugFlags += " ";
246 static int AsLexInput(const char *ProgName) {
247 OwningPtr<MemoryBuffer> BufferPtr;
248 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
249 errs() << ProgName << ": " << ec.message() << '\n';
252 MemoryBuffer *Buffer = BufferPtr.take();
256 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
257 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
259 // Record the location of the include directories so that the lexer can find
261 SrcMgr.setIncludeDirs(IncludeDirs);
263 const Target *TheTarget = GetTarget(ProgName);
267 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
268 assert(MAI && "Unable to create target asm info!");
270 AsmLexer Lexer(*MAI);
271 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
273 OwningPtr<tool_output_file> Out(GetOutputStream());
278 while (Lexer.Lex().isNot(AsmToken::Eof)) {
279 AsmToken Tok = Lexer.getTok();
281 switch (Tok.getKind()) {
283 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
287 case AsmToken::Error:
288 Error = true; // error already printed.
290 case AsmToken::Identifier:
291 Out->os() << "identifier: " << Lexer.getTok().getString();
293 case AsmToken::Integer:
294 Out->os() << "int: " << Lexer.getTok().getString();
297 Out->os() << "real: " << Lexer.getTok().getString();
299 case AsmToken::Register:
300 Out->os() << "register: " << Lexer.getTok().getRegVal();
302 case AsmToken::String:
303 Out->os() << "string: " << Lexer.getTok().getString();
306 case AsmToken::Amp: Out->os() << "Amp"; break;
307 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
308 case AsmToken::At: Out->os() << "At"; break;
309 case AsmToken::Caret: Out->os() << "Caret"; break;
310 case AsmToken::Colon: Out->os() << "Colon"; break;
311 case AsmToken::Comma: Out->os() << "Comma"; break;
312 case AsmToken::Dollar: Out->os() << "Dollar"; break;
313 case AsmToken::Dot: Out->os() << "Dot"; break;
314 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
315 case AsmToken::Eof: Out->os() << "Eof"; break;
316 case AsmToken::Equal: Out->os() << "Equal"; break;
317 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
318 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
319 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
320 case AsmToken::Greater: Out->os() << "Greater"; break;
321 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
322 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
323 case AsmToken::Hash: Out->os() << "Hash"; break;
324 case AsmToken::LBrac: Out->os() << "LBrac"; break;
325 case AsmToken::LCurly: Out->os() << "LCurly"; break;
326 case AsmToken::LParen: Out->os() << "LParen"; break;
327 case AsmToken::Less: Out->os() << "Less"; break;
328 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
329 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
330 case AsmToken::LessLess: Out->os() << "LessLess"; break;
331 case AsmToken::Minus: Out->os() << "Minus"; break;
332 case AsmToken::Percent: Out->os() << "Percent"; break;
333 case AsmToken::Pipe: Out->os() << "Pipe"; break;
334 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
335 case AsmToken::Plus: Out->os() << "Plus"; break;
336 case AsmToken::RBrac: Out->os() << "RBrac"; break;
337 case AsmToken::RCurly: Out->os() << "RCurly"; break;
338 case AsmToken::RParen: Out->os() << "RParen"; break;
339 case AsmToken::Slash: Out->os() << "Slash"; break;
340 case AsmToken::Star: Out->os() << "Star"; break;
341 case AsmToken::Tilde: Out->os() << "Tilde"; break;
344 // Print the token string.
346 Out->os().write_escaped(Tok.getString());
347 Out->os() << "\")\n";
350 // Keep output if no errors.
351 if (Error == 0) Out->keep();
356 static int AssembleInput(const char *ProgName) {
357 const Target *TheTarget = GetTarget(ProgName);
361 OwningPtr<MemoryBuffer> BufferPtr;
362 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
363 errs() << ProgName << ": " << ec.message() << '\n';
366 MemoryBuffer *Buffer = BufferPtr.take();
370 // Tell SrcMgr about this buffer, which is what the parser will pick up.
371 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
373 // Record the location of the include directories so that the lexer can find
375 SrcMgr.setIncludeDirs(IncludeDirs);
378 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
379 assert(MAI && "Unable to create target asm info!");
381 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
382 assert(MRI && "Unable to create target register info!");
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 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
387 MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
388 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
391 Ctx.setAllowTemporaryLabels(false);
393 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
394 if (!DwarfDebugFlags.empty())
395 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
397 // Package up features to be passed to target/subtarget
398 std::string FeaturesStr;
400 SubtargetFeatures Features;
401 for (unsigned i = 0; i != MAttrs.size(); ++i)
402 Features.AddFeature(MAttrs[i]);
403 FeaturesStr = Features.getString();
406 OwningPtr<tool_output_file> Out(GetOutputStream());
410 formatted_raw_ostream FOS(Out->os());
411 OwningPtr<MCStreamer> Str;
413 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
414 OwningPtr<MCSubtargetInfo>
415 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
417 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
418 if (FileType == OFT_AssemblyFile) {
420 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
421 MCCodeEmitter *CE = 0;
422 MCAsmBackend *MAB = 0;
424 CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
425 MAB = TheTarget->createMCAsmBackend(TripleName);
427 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
430 /*useDwarfDirectory*/ true,
431 IP, CE, MAB, ShowInst));
433 } else if (FileType == OFT_Null) {
434 Str.reset(createNullStreamer(Ctx));
436 assert(FileType == OFT_ObjectFile && "Invalid file type!");
437 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
438 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName);
439 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
444 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
446 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
449 << ": error: this target does not support assembly parsing.\n";
453 Parser->setShowParsedOperands(ShowInstOperands);
454 Parser->setTargetParser(*TAP.get());
456 int Res = Parser->Run(NoInitialTextSection);
458 // Keep output if no errors.
459 if (Res == 0) Out->keep();
464 static int DisassembleInput(const char *ProgName, bool Enhanced) {
465 const Target *TheTarget = GetTarget(ProgName);
469 OwningPtr<MemoryBuffer> Buffer;
470 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
471 errs() << ProgName << ": " << ec.message() << '\n';
475 OwningPtr<tool_output_file> Out(GetOutputStream());
482 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
484 // Package up features to be passed to target/subtarget
485 std::string FeaturesStr;
487 SubtargetFeatures Features;
488 for (unsigned i = 0; i != MAttrs.size(); ++i)
489 Features.AddFeature(MAttrs[i]);
490 FeaturesStr = Features.getString();
493 Res = Disassembler::disassemble(*TheTarget, TripleName, MCPU, FeaturesStr,
494 *Buffer.take(), Out->os());
497 // Keep output if no errors.
498 if (Res == 0) Out->keep();
504 int main(int argc, char **argv) {
505 // Print a stack trace if we signal out.
506 sys::PrintStackTraceOnErrorSignal();
507 PrettyStackTraceProgram X(argc, argv);
508 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
510 // Initialize targets and assembly printers/parsers.
511 llvm::InitializeAllTargetInfos();
512 llvm::InitializeAllTargetMCs();
513 llvm::InitializeAllAsmParsers();
514 llvm::InitializeAllDisassemblers();
516 // Register the target printer for --version.
517 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
519 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
520 TripleName = Triple::normalize(TripleName);
521 setDwarfDebugFlags(argc, argv);
525 return AsLexInput(argv[0]);
527 return AssembleInput(argv[0]);
529 return DisassembleInput(argv[0], false);
530 case AC_EDisassemble:
531 return DisassembleInput(argv[0], true);