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/MCContext.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCInstPrinter.h"
21 #include "llvm/MC/MCInstrInfo.h"
22 #include "llvm/MC/MCObjectFileInfo.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/MC/SubtargetFeature.h"
29 #include "llvm/ADT/OwningPtr.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/ToolOutputFile.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/system_error.h"
43 #include "Disassembler.h"
46 static cl::opt<std::string>
47 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
49 static cl::opt<std::string>
50 OutputFilename("o", cl::desc("Output filename"),
51 cl::value_desc("filename"));
54 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
57 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
60 ShowInstOperands("show-inst-operands",
61 cl::desc("Show instructions operands as parsed"));
63 static cl::opt<unsigned>
64 OutputAsmVariant("output-asm-variant",
65 cl::desc("Syntax variant to use for output printing"));
68 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
71 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
74 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
81 static cl::opt<OutputFileType>
82 FileType("filetype", cl::init(OFT_AssemblyFile),
83 cl::desc("Choose an output file type:"),
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"),
93 static cl::list<std::string>
94 IncludeDirs("I", cl::desc("Directory of include files"),
95 cl::value_desc("directory"), cl::Prefix);
97 static cl::opt<std::string>
98 ArchName("arch", cl::desc("Target arch to assemble for, "
99 "see -version for available targets"));
101 static cl::opt<std::string>
102 TripleName("triple", cl::desc("Target triple to assemble for, "
103 "see -version for available targets"));
105 static cl::opt<std::string>
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
111 static cl::list<std::string>
114 cl::desc("Target specific attributes (-mattr=help for details)"),
115 cl::value_desc("a1,+a2,-a3,..."));
117 static cl::opt<Reloc::Model>
118 RelocModel("relocation-model",
119 cl::desc("Choose relocation model"),
120 cl::init(Reloc::Default),
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"),
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",
140 clEnumValN(CodeModel::Kernel, "kernel",
141 "Kernel code model"),
142 clEnumValN(CodeModel::Medium, "medium",
143 "Medium code model"),
144 clEnumValN(CodeModel::Large, "large",
149 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
150 "in the text section"));
153 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
162 static cl::opt<ActionType>
163 Action(cl::desc("Action to perform:"),
164 cl::init(AC_Assemble),
165 cl::values(clEnumValN(AC_AsLex, "as-lex",
166 "Lex tokens from a .s file"),
167 clEnumValN(AC_Assemble, "assemble",
168 "Assemble a .s file (default)"),
169 clEnumValN(AC_Disassemble, "disassemble",
170 "Disassemble strings of hex bytes"),
171 clEnumValN(AC_EDisassemble, "edis",
172 "Enhanced disassembly of strings of hex bytes"),
175 static const Target *GetTarget(const char *ProgName) {
176 // Figure out the target triple.
177 if (TripleName.empty())
178 TripleName = sys::getHostTriple();
179 Triple TheTriple(Triple::normalize(TripleName));
181 const Target *TheTarget = 0;
182 if (!ArchName.empty()) {
183 for (TargetRegistry::iterator it = TargetRegistry::begin(),
184 ie = TargetRegistry::end(); it != ie; ++it) {
185 if (ArchName == it->getName()) {
192 errs() << ProgName << ": error: invalid target '" << ArchName << "'.\n";
196 // Adjust the triple to match (if known), otherwise stick with the
197 // module/host triple.
198 Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName);
199 if (Type != Triple::UnknownArch)
200 TheTriple.setArch(Type);
202 // Get the target specific parser.
204 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error);
205 if (TheTarget == 0) {
206 errs() << ProgName << ": error: unable to get target for '"
207 << TheTriple.getTriple()
208 << "', see --version and --triple.\n";
213 TripleName = TheTriple.getTriple();
217 static tool_output_file *GetOutputStream() {
218 if (OutputFilename == "")
219 OutputFilename = "-";
222 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
223 raw_fd_ostream::F_Binary);
225 errs() << Err << '\n';
233 static int AsLexInput(const char *ProgName) {
234 OwningPtr<MemoryBuffer> BufferPtr;
235 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
236 errs() << ProgName << ": " << ec.message() << '\n';
239 MemoryBuffer *Buffer = BufferPtr.take();
243 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
244 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
246 // Record the location of the include directories so that the lexer can find
248 SrcMgr.setIncludeDirs(IncludeDirs);
250 const Target *TheTarget = GetTarget(ProgName);
254 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
255 assert(MAI && "Unable to create target asm info!");
257 AsmLexer Lexer(*MAI);
258 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
260 OwningPtr<tool_output_file> Out(GetOutputStream());
265 while (Lexer.Lex().isNot(AsmToken::Eof)) {
266 AsmToken Tok = Lexer.getTok();
268 switch (Tok.getKind()) {
270 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
274 case AsmToken::Error:
275 Error = true; // error already printed.
277 case AsmToken::Identifier:
278 Out->os() << "identifier: " << Lexer.getTok().getString();
280 case AsmToken::Integer:
281 Out->os() << "int: " << Lexer.getTok().getString();
284 Out->os() << "real: " << Lexer.getTok().getString();
286 case AsmToken::Register:
287 Out->os() << "register: " << Lexer.getTok().getRegVal();
289 case AsmToken::String:
290 Out->os() << "string: " << Lexer.getTok().getString();
293 case AsmToken::Amp: Out->os() << "Amp"; break;
294 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
295 case AsmToken::At: Out->os() << "At"; break;
296 case AsmToken::Caret: Out->os() << "Caret"; break;
297 case AsmToken::Colon: Out->os() << "Colon"; break;
298 case AsmToken::Comma: Out->os() << "Comma"; break;
299 case AsmToken::Dollar: Out->os() << "Dollar"; break;
300 case AsmToken::Dot: Out->os() << "Dot"; break;
301 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
302 case AsmToken::Eof: Out->os() << "Eof"; break;
303 case AsmToken::Equal: Out->os() << "Equal"; break;
304 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
305 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
306 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
307 case AsmToken::Greater: Out->os() << "Greater"; break;
308 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
309 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
310 case AsmToken::Hash: Out->os() << "Hash"; break;
311 case AsmToken::LBrac: Out->os() << "LBrac"; break;
312 case AsmToken::LCurly: Out->os() << "LCurly"; break;
313 case AsmToken::LParen: Out->os() << "LParen"; break;
314 case AsmToken::Less: Out->os() << "Less"; break;
315 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
316 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
317 case AsmToken::LessLess: Out->os() << "LessLess"; break;
318 case AsmToken::Minus: Out->os() << "Minus"; break;
319 case AsmToken::Percent: Out->os() << "Percent"; break;
320 case AsmToken::Pipe: Out->os() << "Pipe"; break;
321 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
322 case AsmToken::Plus: Out->os() << "Plus"; break;
323 case AsmToken::RBrac: Out->os() << "RBrac"; break;
324 case AsmToken::RCurly: Out->os() << "RCurly"; break;
325 case AsmToken::RParen: Out->os() << "RParen"; break;
326 case AsmToken::Slash: Out->os() << "Slash"; break;
327 case AsmToken::Star: Out->os() << "Star"; break;
328 case AsmToken::Tilde: Out->os() << "Tilde"; break;
331 // Print the token string.
333 Out->os().write_escaped(Tok.getString());
334 Out->os() << "\")\n";
337 // Keep output if no errors.
338 if (Error == 0) Out->keep();
343 static int AssembleInput(const char *ProgName) {
344 const Target *TheTarget = GetTarget(ProgName);
348 OwningPtr<MemoryBuffer> BufferPtr;
349 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
350 errs() << ProgName << ": " << ec.message() << '\n';
353 MemoryBuffer *Buffer = BufferPtr.take();
357 // Tell SrcMgr about this buffer, which is what the parser will pick up.
358 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
360 // Record the location of the include directories so that the lexer can find
362 SrcMgr.setIncludeDirs(IncludeDirs);
365 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
366 assert(MAI && "Unable to create target asm info!");
368 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
369 assert(MRI && "Unable to create target register info!");
371 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
372 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
373 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
374 MCContext Ctx(*MAI, *MRI, MOFI.get());
375 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
378 Ctx.setAllowTemporaryLabels(false);
380 // Package up features to be passed to target/subtarget
381 std::string FeaturesStr;
383 SubtargetFeatures Features;
384 for (unsigned i = 0; i != MAttrs.size(); ++i)
385 Features.AddFeature(MAttrs[i]);
386 FeaturesStr = Features.getString();
389 OwningPtr<tool_output_file> Out(GetOutputStream());
393 formatted_raw_ostream FOS(Out->os());
394 OwningPtr<MCStreamer> Str;
396 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
397 OwningPtr<MCSubtargetInfo>
398 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
400 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
401 if (FileType == OFT_AssemblyFile) {
403 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *STI);
404 MCCodeEmitter *CE = 0;
405 MCAsmBackend *MAB = 0;
407 CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
408 MAB = TheTarget->createMCAsmBackend(TripleName);
410 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
413 /*useDwarfDirectory*/ true,
414 IP, CE, MAB, ShowInst));
416 } else if (FileType == OFT_Null) {
417 Str.reset(createNullStreamer(Ctx));
419 assert(FileType == OFT_ObjectFile && "Invalid file type!");
420 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx);
421 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName);
422 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
428 Str.reset(createLoggingStreamer(Str.take(), errs()));
431 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
433 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser));
436 << ": error: this target does not support assembly parsing.\n";
440 Parser->setShowParsedOperands(ShowInstOperands);
441 Parser->setTargetParser(*TAP.get());
443 int Res = Parser->Run(NoInitialTextSection);
445 // Keep output if no errors.
446 if (Res == 0) Out->keep();
451 static int DisassembleInput(const char *ProgName, bool Enhanced) {
452 const Target *TheTarget = GetTarget(ProgName);
456 OwningPtr<MemoryBuffer> Buffer;
457 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
458 errs() << ProgName << ": " << ec.message() << '\n';
462 OwningPtr<tool_output_file> Out(GetOutputStream());
469 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
471 // Package up features to be passed to target/subtarget
472 std::string FeaturesStr;
474 SubtargetFeatures Features;
475 for (unsigned i = 0; i != MAttrs.size(); ++i)
476 Features.AddFeature(MAttrs[i]);
477 FeaturesStr = Features.getString();
480 Res = Disassembler::disassemble(*TheTarget, TripleName, MCPU, FeaturesStr,
481 *Buffer.take(), Out->os());
484 // Keep output if no errors.
485 if (Res == 0) Out->keep();
491 int main(int argc, char **argv) {
492 // Print a stack trace if we signal out.
493 sys::PrintStackTraceOnErrorSignal();
494 PrettyStackTraceProgram X(argc, argv);
495 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
497 // Initialize targets and assembly printers/parsers.
498 llvm::InitializeAllTargetInfos();
499 llvm::InitializeAllTargetMCs();
500 llvm::InitializeAllAsmParsers();
501 llvm::InitializeAllDisassemblers();
503 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
504 TripleName = Triple::normalize(TripleName);
509 return AsLexInput(argv[0]);
511 return AssembleInput(argv[0]);
513 return DisassembleInput(argv[0], false);
514 case AC_EDisassemble:
515 return DisassembleInput(argv[0], true);