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/MCContext.h"
18 #include "llvm/MC/MCCodeEmitter.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCSectionMachO.h"
21 #include "llvm/MC/MCStreamer.h"
22 #include "llvm/Target/TargetAsmBackend.h"
23 #include "llvm/Target/TargetAsmParser.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/SubtargetFeature.h" // FIXME.
27 #include "llvm/Target/TargetMachine.h" // FIXME.
28 #include "llvm/Target/TargetSelect.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/System/Host.h"
39 #include "llvm/System/Signals.h"
40 #include "Disassembler.h"
43 static cl::opt<std::string>
44 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
46 static cl::opt<std::string>
47 OutputFilename("o", cl::desc("Output filename"),
48 cl::value_desc("filename"));
51 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
57 ShowInstOperands("show-inst-operands",
58 cl::desc("Show instructions operands as parsed"));
60 static cl::opt<unsigned>
61 OutputAsmVariant("output-asm-variant",
62 cl::desc("Syntax variant to use for output printing"));
65 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
68 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
75 static cl::opt<OutputFileType>
76 FileType("filetype", cl::init(OFT_AssemblyFile),
77 cl::desc("Choose an output file type:"),
79 clEnumValN(OFT_AssemblyFile, "asm",
80 "Emit an assembly ('.s') file"),
81 clEnumValN(OFT_Null, "null",
82 "Don't emit anything (for timing purposes)"),
83 clEnumValN(OFT_ObjectFile, "obj",
84 "Emit a native object ('.o') file"),
87 static cl::list<std::string>
88 IncludeDirs("I", cl::desc("Directory of include files"),
89 cl::value_desc("directory"), cl::Prefix);
91 static cl::opt<std::string>
92 ArchName("arch", cl::desc("Target arch to assemble for, "
93 "see -version for available targets"));
95 static cl::opt<std::string>
96 TripleName("triple", cl::desc("Target triple to assemble for, "
97 "see -version for available targets"));
99 static cl::opt<std::string>
101 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
102 cl::value_desc("cpu-name"),
106 NoInitialTextSection("n", cl::desc(
107 "Don't assume assembly file starts in the text section"));
116 static cl::opt<ActionType>
117 Action(cl::desc("Action to perform:"),
118 cl::init(AC_Assemble),
119 cl::values(clEnumValN(AC_AsLex, "as-lex",
120 "Lex tokens from a .s file"),
121 clEnumValN(AC_Assemble, "assemble",
122 "Assemble a .s file (default)"),
123 clEnumValN(AC_Disassemble, "disassemble",
124 "Disassemble strings of hex bytes"),
125 clEnumValN(AC_EDisassemble, "edis",
126 "Enhanced disassembly of strings of hex bytes"),
129 static const Target *GetTarget(const char *ProgName) {
130 // Figure out the target triple.
131 if (TripleName.empty())
132 TripleName = sys::getHostTriple();
133 if (!ArchName.empty()) {
134 llvm::Triple TT(TripleName);
135 TT.setArchName(ArchName);
136 TripleName = TT.str();
139 // Get the target specific parser.
141 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
145 errs() << ProgName << ": error: unable to get target for '" << TripleName
146 << "', see --version and --triple.\n";
150 static tool_output_file *GetOutputStream() {
151 if (OutputFilename == "")
152 OutputFilename = "-";
155 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
156 raw_fd_ostream::F_Binary);
158 errs() << Err << '\n';
166 static int AsLexInput(const char *ProgName) {
167 std::string ErrorMessage;
168 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
171 errs() << ProgName << ": ";
172 if (ErrorMessage.size())
173 errs() << ErrorMessage << "\n";
175 errs() << "input file didn't read correctly.\n";
181 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
182 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
184 // Record the location of the include directories so that the lexer can find
186 SrcMgr.setIncludeDirs(IncludeDirs);
188 const Target *TheTarget = GetTarget(ProgName);
192 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
193 assert(MAI && "Unable to create target asm info!");
195 AsmLexer Lexer(*MAI);
196 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
198 OwningPtr<tool_output_file> Out(GetOutputStream());
203 while (Lexer.Lex().isNot(AsmToken::Eof)) {
204 AsmToken Tok = Lexer.getTok();
206 switch (Tok.getKind()) {
208 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
211 case AsmToken::Error:
212 Error = true; // error already printed.
214 case AsmToken::Identifier:
215 Out->os() << "identifier: " << Lexer.getTok().getString();
217 case AsmToken::Integer:
218 Out->os() << "int: " << Lexer.getTok().getString();
221 Out->os() << "real: " << Lexer.getTok().getString();
223 case AsmToken::Register:
224 Out->os() << "register: " << Lexer.getTok().getRegVal();
226 case AsmToken::String:
227 Out->os() << "string: " << Lexer.getTok().getString();
230 case AsmToken::Amp: Out->os() << "Amp"; break;
231 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
232 case AsmToken::At: Out->os() << "At"; break;
233 case AsmToken::Caret: Out->os() << "Caret"; break;
234 case AsmToken::Colon: Out->os() << "Colon"; break;
235 case AsmToken::Comma: Out->os() << "Comma"; break;
236 case AsmToken::Dollar: Out->os() << "Dollar"; break;
237 case AsmToken::Dot: Out->os() << "Dot"; break;
238 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
239 case AsmToken::Eof: Out->os() << "Eof"; break;
240 case AsmToken::Equal: Out->os() << "Equal"; break;
241 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
242 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
243 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
244 case AsmToken::Greater: Out->os() << "Greater"; break;
245 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
246 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
247 case AsmToken::Hash: Out->os() << "Hash"; break;
248 case AsmToken::LBrac: Out->os() << "LBrac"; break;
249 case AsmToken::LCurly: Out->os() << "LCurly"; break;
250 case AsmToken::LParen: Out->os() << "LParen"; break;
251 case AsmToken::Less: Out->os() << "Less"; break;
252 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
253 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
254 case AsmToken::LessLess: Out->os() << "LessLess"; break;
255 case AsmToken::Minus: Out->os() << "Minus"; break;
256 case AsmToken::Percent: Out->os() << "Percent"; break;
257 case AsmToken::Pipe: Out->os() << "Pipe"; break;
258 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
259 case AsmToken::Plus: Out->os() << "Plus"; break;
260 case AsmToken::RBrac: Out->os() << "RBrac"; break;
261 case AsmToken::RCurly: Out->os() << "RCurly"; break;
262 case AsmToken::RParen: Out->os() << "RParen"; break;
263 case AsmToken::Slash: Out->os() << "Slash"; break;
264 case AsmToken::Star: Out->os() << "Star"; break;
265 case AsmToken::Tilde: Out->os() << "Tilde"; break;
268 // Print the token string.
270 Out->os().write_escaped(Tok.getString());
271 Out->os() << "\")\n";
274 // Keep output if no errors.
275 if (Error == 0) Out->keep();
280 static int AssembleInput(const char *ProgName) {
281 const Target *TheTarget = GetTarget(ProgName);
286 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error);
288 errs() << ProgName << ": ";
290 errs() << Error << "\n";
292 errs() << "input file didn't read correctly.\n";
298 // Tell SrcMgr about this buffer, which is what the parser will pick up.
299 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
301 // Record the location of the include directories so that the lexer can find
303 SrcMgr.setIncludeDirs(IncludeDirs);
306 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
307 assert(MAI && "Unable to create target asm info!");
311 // Package up features to be passed to target/subtarget
312 std::string FeaturesStr;
314 SubtargetFeatures Features;
315 Features.setCPU(MCPU);
316 FeaturesStr = Features.getString();
319 // FIXME: We shouldn't need to do this (and link in codegen).
320 // When we split this out, we should do it in a way that makes
321 // it straightforward to switch subtargets on the fly (.e.g,
322 // the .cpu and .code16 directives).
323 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
327 errs() << ProgName << ": error: could not create target for triple '"
328 << TripleName << "'.\n";
332 OwningPtr<tool_output_file> Out(GetOutputStream());
336 formatted_raw_ostream FOS(Out->os());
337 OwningPtr<MCStreamer> Str;
339 if (FileType == OFT_AssemblyFile) {
341 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
342 MCCodeEmitter *CE = 0;
344 CE = TheTarget->createCodeEmitter(*TM, Ctx);
345 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS,
346 TM->getTargetData()->isLittleEndian(),
347 /*asmverbose*/true, IP, CE, ShowInst));
348 } else if (FileType == OFT_Null) {
349 Str.reset(createNullStreamer(Ctx));
351 assert(FileType == OFT_ObjectFile && "Invalid file type!");
352 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
353 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
354 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
359 Str.reset(createLoggingStreamer(Str.take(), errs()));
362 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
364 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
367 << ": error: this target does not support assembly parsing.\n";
371 Parser->setShowParsedOperands(ShowInstOperands);
372 Parser->setTargetParser(*TAP.get());
374 int Res = Parser->Run(NoInitialTextSection);
376 // Keep output if no errors.
377 if (Res == 0) Out->keep();
382 static int DisassembleInput(const char *ProgName, bool Enhanced) {
383 const Target *TheTarget = GetTarget(ProgName);
387 std::string ErrorMessage;
389 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename,
393 errs() << ProgName << ": ";
394 if (ErrorMessage.size())
395 errs() << ErrorMessage << "\n";
397 errs() << "input file didn't read correctly.\n";
401 OwningPtr<tool_output_file> Out(GetOutputStream());
407 Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, Out->os());
409 Res = Disassembler::disassemble(*TheTarget, TripleName, *Buffer, Out->os());
411 // Keep output if no errors.
412 if (Res == 0) Out->keep();
418 int main(int argc, char **argv) {
419 // Print a stack trace if we signal out.
420 sys::PrintStackTraceOnErrorSignal();
421 PrettyStackTraceProgram X(argc, argv);
422 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
424 // Initialize targets and assembly printers/parsers.
425 llvm::InitializeAllTargetInfos();
426 // FIXME: We shouldn't need to initialize the Target(Machine)s.
427 llvm::InitializeAllTargets();
428 llvm::InitializeAllAsmPrinters();
429 llvm::InitializeAllAsmParsers();
430 llvm::InitializeAllDisassemblers();
432 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
433 TripleName = Triple::normalize(TripleName);
438 return AsLexInput(argv[0]);
440 return AssembleInput(argv[0]);
442 return DisassembleInput(argv[0], false);
443 case AC_EDisassemble:
444 return DisassembleInput(argv[0], true);