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/Support/Host.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/system_error.h"
41 #include "Disassembler.h"
44 static cl::opt<std::string>
45 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47 static cl::opt<std::string>
48 OutputFilename("o", cl::desc("Output filename"),
49 cl::value_desc("filename"));
52 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
58 ShowInstOperands("show-inst-operands",
59 cl::desc("Show instructions operands as parsed"));
61 static cl::opt<unsigned>
62 OutputAsmVariant("output-asm-variant",
63 cl::desc("Syntax variant to use for output printing"));
66 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
69 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
76 static cl::opt<OutputFileType>
77 FileType("filetype", cl::init(OFT_AssemblyFile),
78 cl::desc("Choose an output file type:"),
80 clEnumValN(OFT_AssemblyFile, "asm",
81 "Emit an assembly ('.s') file"),
82 clEnumValN(OFT_Null, "null",
83 "Don't emit anything (for timing purposes)"),
84 clEnumValN(OFT_ObjectFile, "obj",
85 "Emit a native object ('.o') file"),
88 static cl::list<std::string>
89 IncludeDirs("I", cl::desc("Directory of include files"),
90 cl::value_desc("directory"), cl::Prefix);
92 static cl::opt<std::string>
93 ArchName("arch", cl::desc("Target arch to assemble for, "
94 "see -version for available targets"));
96 static cl::opt<std::string>
97 TripleName("triple", cl::desc("Target triple to assemble for, "
98 "see -version for available targets"));
100 static cl::opt<std::string>
102 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
103 cl::value_desc("cpu-name"),
107 NoInitialTextSection("n", cl::desc(
108 "Don't assume assembly file starts in the text section"));
117 static cl::opt<ActionType>
118 Action(cl::desc("Action to perform:"),
119 cl::init(AC_Assemble),
120 cl::values(clEnumValN(AC_AsLex, "as-lex",
121 "Lex tokens from a .s file"),
122 clEnumValN(AC_Assemble, "assemble",
123 "Assemble a .s file (default)"),
124 clEnumValN(AC_Disassemble, "disassemble",
125 "Disassemble strings of hex bytes"),
126 clEnumValN(AC_EDisassemble, "edis",
127 "Enhanced disassembly of strings of hex bytes"),
130 static const Target *GetTarget(const char *ProgName) {
131 // Figure out the target triple.
132 if (TripleName.empty())
133 TripleName = sys::getHostTriple();
134 if (!ArchName.empty()) {
135 llvm::Triple TT(TripleName);
136 TT.setArchName(ArchName);
137 TripleName = TT.str();
140 // Get the target specific parser.
142 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
146 errs() << ProgName << ": error: unable to get target for '" << TripleName
147 << "', see --version and --triple.\n";
151 static tool_output_file *GetOutputStream() {
152 if (OutputFilename == "")
153 OutputFilename = "-";
156 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
157 raw_fd_ostream::F_Binary);
159 errs() << Err << '\n';
167 static int AsLexInput(const char *ProgName) {
169 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, ec);
171 errs() << ProgName << ": " << ec.message() << '\n';
177 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
178 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
180 // Record the location of the include directories so that the lexer can find
182 SrcMgr.setIncludeDirs(IncludeDirs);
184 const Target *TheTarget = GetTarget(ProgName);
188 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
189 assert(MAI && "Unable to create target asm info!");
191 AsmLexer Lexer(*MAI);
192 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
194 OwningPtr<tool_output_file> Out(GetOutputStream());
199 while (Lexer.Lex().isNot(AsmToken::Eof)) {
200 AsmToken Tok = Lexer.getTok();
202 switch (Tok.getKind()) {
204 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
207 case AsmToken::Error:
208 Error = true; // error already printed.
210 case AsmToken::Identifier:
211 Out->os() << "identifier: " << Lexer.getTok().getString();
213 case AsmToken::Integer:
214 Out->os() << "int: " << Lexer.getTok().getString();
217 Out->os() << "real: " << Lexer.getTok().getString();
219 case AsmToken::Register:
220 Out->os() << "register: " << Lexer.getTok().getRegVal();
222 case AsmToken::String:
223 Out->os() << "string: " << Lexer.getTok().getString();
226 case AsmToken::Amp: Out->os() << "Amp"; break;
227 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
228 case AsmToken::At: Out->os() << "At"; break;
229 case AsmToken::Caret: Out->os() << "Caret"; break;
230 case AsmToken::Colon: Out->os() << "Colon"; break;
231 case AsmToken::Comma: Out->os() << "Comma"; break;
232 case AsmToken::Dollar: Out->os() << "Dollar"; break;
233 case AsmToken::Dot: Out->os() << "Dot"; break;
234 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
235 case AsmToken::Eof: Out->os() << "Eof"; break;
236 case AsmToken::Equal: Out->os() << "Equal"; break;
237 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
238 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
239 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
240 case AsmToken::Greater: Out->os() << "Greater"; break;
241 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
242 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
243 case AsmToken::Hash: Out->os() << "Hash"; break;
244 case AsmToken::LBrac: Out->os() << "LBrac"; break;
245 case AsmToken::LCurly: Out->os() << "LCurly"; break;
246 case AsmToken::LParen: Out->os() << "LParen"; break;
247 case AsmToken::Less: Out->os() << "Less"; break;
248 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
249 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
250 case AsmToken::LessLess: Out->os() << "LessLess"; break;
251 case AsmToken::Minus: Out->os() << "Minus"; break;
252 case AsmToken::Percent: Out->os() << "Percent"; break;
253 case AsmToken::Pipe: Out->os() << "Pipe"; break;
254 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
255 case AsmToken::Plus: Out->os() << "Plus"; break;
256 case AsmToken::RBrac: Out->os() << "RBrac"; break;
257 case AsmToken::RCurly: Out->os() << "RCurly"; break;
258 case AsmToken::RParen: Out->os() << "RParen"; break;
259 case AsmToken::Slash: Out->os() << "Slash"; break;
260 case AsmToken::Star: Out->os() << "Star"; break;
261 case AsmToken::Tilde: Out->os() << "Tilde"; break;
264 // Print the token string.
266 Out->os().write_escaped(Tok.getString());
267 Out->os() << "\")\n";
270 // Keep output if no errors.
271 if (Error == 0) Out->keep();
276 static int AssembleInput(const char *ProgName) {
277 const Target *TheTarget = GetTarget(ProgName);
282 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, ec);
284 errs() << ProgName << ": " << ec.message() << '\n';
290 // Tell SrcMgr about this buffer, which is what the parser will pick up.
291 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
293 // Record the location of the include directories so that the lexer can find
295 SrcMgr.setIncludeDirs(IncludeDirs);
298 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
299 assert(MAI && "Unable to create target asm info!");
303 // Package up features to be passed to target/subtarget
304 std::string FeaturesStr;
306 SubtargetFeatures Features;
307 Features.setCPU(MCPU);
308 FeaturesStr = Features.getString();
311 // FIXME: We shouldn't need to do this (and link in codegen).
312 // When we split this out, we should do it in a way that makes
313 // it straightforward to switch subtargets on the fly (.e.g,
314 // the .cpu and .code16 directives).
315 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
319 errs() << ProgName << ": error: could not create target for triple '"
320 << TripleName << "'.\n";
324 OwningPtr<tool_output_file> Out(GetOutputStream());
328 formatted_raw_ostream FOS(Out->os());
329 OwningPtr<MCStreamer> Str;
331 if (FileType == OFT_AssemblyFile) {
333 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
334 MCCodeEmitter *CE = 0;
336 CE = TheTarget->createCodeEmitter(*TM, Ctx);
337 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS,
338 TM->getTargetData()->isLittleEndian(),
339 /*asmverbose*/true, IP, CE, ShowInst));
340 } else if (FileType == OFT_Null) {
341 Str.reset(createNullStreamer(Ctx));
343 assert(FileType == OFT_ObjectFile && "Invalid file type!");
344 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
345 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
346 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
351 Str.reset(createLoggingStreamer(Str.take(), errs()));
354 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
356 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
359 << ": error: this target does not support assembly parsing.\n";
363 Parser->setShowParsedOperands(ShowInstOperands);
364 Parser->setTargetParser(*TAP.get());
366 int Res = Parser->Run(NoInitialTextSection);
368 // Keep output if no errors.
369 if (Res == 0) Out->keep();
374 static int DisassembleInput(const char *ProgName, bool Enhanced) {
375 const Target *TheTarget = GetTarget(ProgName);
380 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, ec);
382 errs() << ProgName << ": " << ec.message() << '\n';
386 OwningPtr<tool_output_file> Out(GetOutputStream());
392 Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, Out->os());
394 Res = Disassembler::disassemble(*TheTarget, TripleName, *Buffer, Out->os());
396 // Keep output if no errors.
397 if (Res == 0) Out->keep();
403 int main(int argc, char **argv) {
404 // Print a stack trace if we signal out.
405 sys::PrintStackTraceOnErrorSignal();
406 PrettyStackTraceProgram X(argc, argv);
407 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
409 // Initialize targets and assembly printers/parsers.
410 llvm::InitializeAllTargetInfos();
411 // FIXME: We shouldn't need to initialize the Target(Machine)s.
412 llvm::InitializeAllTargets();
413 llvm::InitializeAllAsmPrinters();
414 llvm::InitializeAllAsmParsers();
415 llvm::InitializeAllDisassemblers();
417 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
418 TripleName = Triple::normalize(TripleName);
423 return AsLexInput(argv[0]);
425 return AssembleInput(argv[0]);
427 return DisassembleInput(argv[0], false);
428 case AC_EDisassemble:
429 return DisassembleInput(argv[0], true);