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/TargetAsmInfo.h" // FIXME.
28 #include "llvm/Target/TargetLowering.h" // FIXME.
29 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
30 #include "llvm/Target/TargetMachine.h" // FIXME.
31 #include "llvm/Target/TargetSelect.h"
32 #include "llvm/ADT/OwningPtr.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "llvm/Support/FormattedStream.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/ToolOutputFile.h"
41 #include "llvm/Support/Host.h"
42 #include "llvm/Support/Signals.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 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
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"),
110 NoInitialTextSection("n", cl::desc(
111 "Don't assume assembly file starts in the text section"));
120 static cl::opt<ActionType>
121 Action(cl::desc("Action to perform:"),
122 cl::init(AC_Assemble),
123 cl::values(clEnumValN(AC_AsLex, "as-lex",
124 "Lex tokens from a .s file"),
125 clEnumValN(AC_Assemble, "assemble",
126 "Assemble a .s file (default)"),
127 clEnumValN(AC_Disassemble, "disassemble",
128 "Disassemble strings of hex bytes"),
129 clEnumValN(AC_EDisassemble, "edis",
130 "Enhanced disassembly of strings of hex bytes"),
133 static const Target *GetTarget(const char *ProgName) {
134 // Figure out the target triple.
135 if (TripleName.empty())
136 TripleName = sys::getHostTriple();
137 if (!ArchName.empty()) {
138 llvm::Triple TT(TripleName);
139 TT.setArchName(ArchName);
140 TripleName = TT.str();
143 // Get the target specific parser.
145 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
149 errs() << ProgName << ": error: unable to get target for '" << TripleName
150 << "', see --version and --triple.\n";
154 static tool_output_file *GetOutputStream() {
155 if (OutputFilename == "")
156 OutputFilename = "-";
159 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
160 raw_fd_ostream::F_Binary);
162 errs() << Err << '\n';
170 static int AsLexInput(const char *ProgName) {
171 OwningPtr<MemoryBuffer> BufferPtr;
172 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
173 errs() << ProgName << ": " << ec.message() << '\n';
176 MemoryBuffer *Buffer = BufferPtr.take();
180 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
181 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
183 // Record the location of the include directories so that the lexer can find
185 SrcMgr.setIncludeDirs(IncludeDirs);
187 const Target *TheTarget = GetTarget(ProgName);
191 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
192 assert(MAI && "Unable to create target asm info!");
194 AsmLexer Lexer(*MAI);
195 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
197 OwningPtr<tool_output_file> Out(GetOutputStream());
202 while (Lexer.Lex().isNot(AsmToken::Eof)) {
203 AsmToken Tok = Lexer.getTok();
205 switch (Tok.getKind()) {
207 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
210 case AsmToken::Error:
211 Error = true; // error already printed.
213 case AsmToken::Identifier:
214 Out->os() << "identifier: " << Lexer.getTok().getString();
216 case AsmToken::Integer:
217 Out->os() << "int: " << Lexer.getTok().getString();
220 Out->os() << "real: " << Lexer.getTok().getString();
222 case AsmToken::Register:
223 Out->os() << "register: " << Lexer.getTok().getRegVal();
225 case AsmToken::String:
226 Out->os() << "string: " << Lexer.getTok().getString();
229 case AsmToken::Amp: Out->os() << "Amp"; break;
230 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
231 case AsmToken::At: Out->os() << "At"; break;
232 case AsmToken::Caret: Out->os() << "Caret"; break;
233 case AsmToken::Colon: Out->os() << "Colon"; break;
234 case AsmToken::Comma: Out->os() << "Comma"; break;
235 case AsmToken::Dollar: Out->os() << "Dollar"; break;
236 case AsmToken::Dot: Out->os() << "Dot"; break;
237 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
238 case AsmToken::Eof: Out->os() << "Eof"; break;
239 case AsmToken::Equal: Out->os() << "Equal"; break;
240 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
241 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
242 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
243 case AsmToken::Greater: Out->os() << "Greater"; break;
244 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
245 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
246 case AsmToken::Hash: Out->os() << "Hash"; break;
247 case AsmToken::LBrac: Out->os() << "LBrac"; break;
248 case AsmToken::LCurly: Out->os() << "LCurly"; break;
249 case AsmToken::LParen: Out->os() << "LParen"; break;
250 case AsmToken::Less: Out->os() << "Less"; break;
251 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
252 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
253 case AsmToken::LessLess: Out->os() << "LessLess"; break;
254 case AsmToken::Minus: Out->os() << "Minus"; break;
255 case AsmToken::Percent: Out->os() << "Percent"; break;
256 case AsmToken::Pipe: Out->os() << "Pipe"; break;
257 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
258 case AsmToken::Plus: Out->os() << "Plus"; break;
259 case AsmToken::RBrac: Out->os() << "RBrac"; break;
260 case AsmToken::RCurly: Out->os() << "RCurly"; break;
261 case AsmToken::RParen: Out->os() << "RParen"; break;
262 case AsmToken::Slash: Out->os() << "Slash"; break;
263 case AsmToken::Star: Out->os() << "Star"; break;
264 case AsmToken::Tilde: Out->os() << "Tilde"; break;
267 // Print the token string.
269 Out->os().write_escaped(Tok.getString());
270 Out->os() << "\")\n";
273 // Keep output if no errors.
274 if (Error == 0) Out->keep();
279 static int AssembleInput(const char *ProgName) {
280 const Target *TheTarget = GetTarget(ProgName);
284 OwningPtr<MemoryBuffer> BufferPtr;
285 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
286 errs() << ProgName << ": " << ec.message() << '\n';
289 MemoryBuffer *Buffer = BufferPtr.take();
293 // Tell SrcMgr about this buffer, which is what the parser will pick up.
294 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
296 // Record the location of the include directories so that the lexer can find
298 SrcMgr.setIncludeDirs(IncludeDirs);
301 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
302 assert(MAI && "Unable to create target asm info!");
304 // Package up features to be passed to target/subtarget
305 std::string FeaturesStr;
307 SubtargetFeatures Features;
308 Features.setCPU(MCPU);
309 FeaturesStr = Features.getString();
312 // FIXME: We shouldn't need to do this (and link in codegen).
313 // When we split this out, we should do it in a way that makes
314 // it straightforward to switch subtargets on the fly (.e.g,
315 // the .cpu and .code16 directives).
316 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
320 errs() << ProgName << ": error: could not create target for triple '"
321 << TripleName << "'.\n";
325 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
326 MCContext Ctx(*MAI, tai);
328 OwningPtr<tool_output_file> Out(GetOutputStream());
332 formatted_raw_ostream FOS(Out->os());
333 OwningPtr<MCStreamer> Str;
335 const TargetLoweringObjectFile &TLOF =
336 TM->getTargetLowering()->getObjFileLowering();
337 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
339 if (FileType == OFT_AssemblyFile) {
341 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
342 MCCodeEmitter *CE = 0;
343 TargetAsmBackend *TAB = 0;
345 CE = TheTarget->createCodeEmitter(*TM, Ctx);
346 TAB = TheTarget->createAsmBackend(TripleName);
348 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
349 /*useLoc*/ true, IP, CE, TAB,
351 } else if (FileType == OFT_Null) {
352 Str.reset(createNullStreamer(Ctx));
354 assert(FileType == OFT_ObjectFile && "Invalid file type!");
355 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx);
356 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
357 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
362 Str.reset(createLoggingStreamer(Str.take(), errs()));
365 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
367 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM));
370 << ": error: this target does not support assembly parsing.\n";
374 Parser->setShowParsedOperands(ShowInstOperands);
375 Parser->setTargetParser(*TAP.get());
377 int Res = Parser->Run(NoInitialTextSection);
379 // Keep output if no errors.
380 if (Res == 0) Out->keep();
385 static int DisassembleInput(const char *ProgName, bool Enhanced) {
386 const Target *TheTarget = GetTarget(ProgName);
390 OwningPtr<MemoryBuffer> Buffer;
391 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
392 errs() << ProgName << ": " << ec.message() << '\n';
396 OwningPtr<tool_output_file> Out(GetOutputStream());
403 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
405 Res = Disassembler::disassemble(*TheTarget, TripleName,
406 *Buffer.take(), Out->os());
408 // Keep output if no errors.
409 if (Res == 0) Out->keep();
415 int main(int argc, char **argv) {
416 // Print a stack trace if we signal out.
417 sys::PrintStackTraceOnErrorSignal();
418 PrettyStackTraceProgram X(argc, argv);
419 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
421 // Initialize targets and assembly printers/parsers.
422 llvm::InitializeAllTargetInfos();
423 // FIXME: We shouldn't need to initialize the Target(Machine)s.
424 llvm::InitializeAllTargets();
425 llvm::InitializeAllAsmPrinters();
426 llvm::InitializeAllAsmParsers();
427 llvm::InitializeAllDisassemblers();
429 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
430 TripleName = Triple::normalize(TripleName);
435 return AsLexInput(argv[0]);
437 return AssembleInput(argv[0]);
439 return DisassembleInput(argv[0], false);
440 case AC_EDisassemble:
441 return DisassembleInput(argv[0], true);