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/MCInstrInfo.h"
21 #include "llvm/MC/MCSectionMachO.h"
22 #include "llvm/MC/MCStreamer.h"
23 #include "llvm/MC/MCSubtargetInfo.h"
24 #include "llvm/MC/SubtargetFeature.h"
25 #include "llvm/Target/TargetAsmBackend.h"
26 #include "llvm/Target/TargetAsmParser.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetAsmInfo.h" // FIXME.
30 #include "llvm/Target/TargetLowering.h" // FIXME.
31 #include "llvm/Target/TargetLoweringObjectFile.h" // FIXME.
32 #include "llvm/Target/TargetMachine.h" // FIXME.
33 #include "llvm/Target/TargetSelect.h"
34 #include "llvm/ADT/OwningPtr.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/FileUtilities.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/Support/ManagedStatic.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/ToolOutputFile.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/system_error.h"
46 #include "Disassembler.h"
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
52 static cl::opt<std::string>
53 OutputFilename("o", cl::desc("Output filename"),
54 cl::value_desc("filename"));
57 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
60 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
63 ShowInstOperands("show-inst-operands",
64 cl::desc("Show instructions operands as parsed"));
66 static cl::opt<unsigned>
67 OutputAsmVariant("output-asm-variant",
68 cl::desc("Syntax variant to use for output printing"));
71 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
74 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
77 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
84 static cl::opt<OutputFileType>
85 FileType("filetype", cl::init(OFT_AssemblyFile),
86 cl::desc("Choose an output file type:"),
88 clEnumValN(OFT_AssemblyFile, "asm",
89 "Emit an assembly ('.s') file"),
90 clEnumValN(OFT_Null, "null",
91 "Don't emit anything (for timing purposes)"),
92 clEnumValN(OFT_ObjectFile, "obj",
93 "Emit a native object ('.o') file"),
96 static cl::list<std::string>
97 IncludeDirs("I", cl::desc("Directory of include files"),
98 cl::value_desc("directory"), cl::Prefix);
100 static cl::opt<std::string>
101 ArchName("arch", cl::desc("Target arch to assemble for, "
102 "see -version for available targets"));
104 static cl::opt<std::string>
105 TripleName("triple", cl::desc("Target triple to assemble for, "
106 "see -version for available targets"));
108 static cl::opt<std::string>
110 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
111 cl::value_desc("cpu-name"),
115 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
116 "in the text section"));
119 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
128 static cl::opt<ActionType>
129 Action(cl::desc("Action to perform:"),
130 cl::init(AC_Assemble),
131 cl::values(clEnumValN(AC_AsLex, "as-lex",
132 "Lex tokens from a .s file"),
133 clEnumValN(AC_Assemble, "assemble",
134 "Assemble a .s file (default)"),
135 clEnumValN(AC_Disassemble, "disassemble",
136 "Disassemble strings of hex bytes"),
137 clEnumValN(AC_EDisassemble, "edis",
138 "Enhanced disassembly of strings of hex bytes"),
141 static const Target *GetTarget(const char *ProgName) {
142 // Figure out the target triple.
143 if (TripleName.empty())
144 TripleName = sys::getHostTriple();
145 if (!ArchName.empty()) {
146 llvm::Triple TT(TripleName);
147 TT.setArchName(ArchName);
148 TripleName = TT.str();
151 // Get the target specific parser.
153 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
157 errs() << ProgName << ": error: unable to get target for '" << TripleName
158 << "', see --version and --triple.\n";
162 static tool_output_file *GetOutputStream() {
163 if (OutputFilename == "")
164 OutputFilename = "-";
167 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
168 raw_fd_ostream::F_Binary);
170 errs() << Err << '\n';
178 static int AsLexInput(const char *ProgName) {
179 OwningPtr<MemoryBuffer> BufferPtr;
180 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
181 errs() << ProgName << ": " << ec.message() << '\n';
184 MemoryBuffer *Buffer = BufferPtr.take();
188 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
189 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
191 // Record the location of the include directories so that the lexer can find
193 SrcMgr.setIncludeDirs(IncludeDirs);
195 const Target *TheTarget = GetTarget(ProgName);
199 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
200 assert(MAI && "Unable to create target asm info!");
202 AsmLexer Lexer(*MAI);
203 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
205 OwningPtr<tool_output_file> Out(GetOutputStream());
210 while (Lexer.Lex().isNot(AsmToken::Eof)) {
211 AsmToken Tok = Lexer.getTok();
213 switch (Tok.getKind()) {
215 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
218 case AsmToken::Error:
219 Error = true; // error already printed.
221 case AsmToken::Identifier:
222 Out->os() << "identifier: " << Lexer.getTok().getString();
224 case AsmToken::Integer:
225 Out->os() << "int: " << Lexer.getTok().getString();
228 Out->os() << "real: " << Lexer.getTok().getString();
230 case AsmToken::Register:
231 Out->os() << "register: " << Lexer.getTok().getRegVal();
233 case AsmToken::String:
234 Out->os() << "string: " << Lexer.getTok().getString();
237 case AsmToken::Amp: Out->os() << "Amp"; break;
238 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
239 case AsmToken::At: Out->os() << "At"; break;
240 case AsmToken::Caret: Out->os() << "Caret"; break;
241 case AsmToken::Colon: Out->os() << "Colon"; break;
242 case AsmToken::Comma: Out->os() << "Comma"; break;
243 case AsmToken::Dollar: Out->os() << "Dollar"; break;
244 case AsmToken::Dot: Out->os() << "Dot"; break;
245 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
246 case AsmToken::Eof: Out->os() << "Eof"; break;
247 case AsmToken::Equal: Out->os() << "Equal"; break;
248 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
249 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
250 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
251 case AsmToken::Greater: Out->os() << "Greater"; break;
252 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
253 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
254 case AsmToken::Hash: Out->os() << "Hash"; break;
255 case AsmToken::LBrac: Out->os() << "LBrac"; break;
256 case AsmToken::LCurly: Out->os() << "LCurly"; break;
257 case AsmToken::LParen: Out->os() << "LParen"; break;
258 case AsmToken::Less: Out->os() << "Less"; break;
259 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
260 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
261 case AsmToken::LessLess: Out->os() << "LessLess"; break;
262 case AsmToken::Minus: Out->os() << "Minus"; break;
263 case AsmToken::Percent: Out->os() << "Percent"; break;
264 case AsmToken::Pipe: Out->os() << "Pipe"; break;
265 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
266 case AsmToken::Plus: Out->os() << "Plus"; break;
267 case AsmToken::RBrac: Out->os() << "RBrac"; break;
268 case AsmToken::RCurly: Out->os() << "RCurly"; break;
269 case AsmToken::RParen: Out->os() << "RParen"; break;
270 case AsmToken::Slash: Out->os() << "Slash"; break;
271 case AsmToken::Star: Out->os() << "Star"; break;
272 case AsmToken::Tilde: Out->os() << "Tilde"; break;
275 // Print the token string.
277 Out->os().write_escaped(Tok.getString());
278 Out->os() << "\")\n";
281 // Keep output if no errors.
282 if (Error == 0) Out->keep();
287 static int AssembleInput(const char *ProgName) {
288 const Target *TheTarget = GetTarget(ProgName);
292 OwningPtr<MemoryBuffer> BufferPtr;
293 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
294 errs() << ProgName << ": " << ec.message() << '\n';
297 MemoryBuffer *Buffer = BufferPtr.take();
301 // Tell SrcMgr about this buffer, which is what the parser will pick up.
302 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
304 // Record the location of the include directories so that the lexer can find
306 SrcMgr.setIncludeDirs(IncludeDirs);
309 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName));
310 assert(MAI && "Unable to create target asm info!");
312 // Package up features to be passed to target/subtarget
313 std::string FeaturesStr;
315 // FIXME: We shouldn't need to do this (and link in codegen).
316 // When we split this out, we should do it in a way that makes
317 // it straightforward to switch subtargets on the fly (.e.g,
318 // the .cpu and .code16 directives).
319 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
324 errs() << ProgName << ": error: could not create target for triple '"
325 << TripleName << "'.\n";
329 const TargetAsmInfo *tai = new TargetAsmInfo(*TM);
330 MCContext Ctx(*MAI, tai);
332 Ctx.setAllowTemporaryLabels(false);
334 OwningPtr<tool_output_file> Out(GetOutputStream());
338 formatted_raw_ostream FOS(Out->os());
339 OwningPtr<MCStreamer> Str;
341 const TargetLoweringObjectFile &TLOF =
342 TM->getTargetLowering()->getObjFileLowering();
343 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(Ctx, *TM);
345 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
346 OwningPtr<MCSubtargetInfo>
347 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
349 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
350 if (FileType == OFT_AssemblyFile) {
352 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
353 MCCodeEmitter *CE = 0;
354 TargetAsmBackend *TAB = 0;
356 CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
357 TAB = TheTarget->createAsmBackend(TripleName);
359 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
361 /*useCFI*/ true, IP, CE, TAB,
363 } else if (FileType == OFT_Null) {
364 Str.reset(createNullStreamer(Ctx));
366 assert(FileType == OFT_ObjectFile && "Invalid file type!");
367 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
368 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
369 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
375 Str.reset(createLoggingStreamer(Str.take(), errs()));
378 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
380 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
383 << ": error: this target does not support assembly parsing.\n";
387 Parser->setShowParsedOperands(ShowInstOperands);
388 Parser->setTargetParser(*TAP.get());
390 int Res = Parser->Run(NoInitialTextSection);
392 // Keep output if no errors.
393 if (Res == 0) Out->keep();
398 static int DisassembleInput(const char *ProgName, bool Enhanced) {
399 const Target *TheTarget = GetTarget(ProgName);
403 OwningPtr<MemoryBuffer> Buffer;
404 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
405 errs() << ProgName << ": " << ec.message() << '\n';
409 OwningPtr<tool_output_file> Out(GetOutputStream());
416 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
418 // Package up features to be passed to target/subtarget
419 std::string FeaturesStr;
421 // FIXME: We shouldn't need to do this (and link in codegen).
422 // When we split this out, we should do it in a way that makes
423 // it straightforward to switch subtargets on the fly (.e.g,
424 // the .cpu and .code16 directives).
425 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName,
430 errs() << ProgName << ": error: could not create target for triple '"
431 << TripleName << "'.\n";
435 Res = Disassembler::disassemble(*TheTarget, TripleName,
436 *Buffer.take(), Out->os());
439 // Keep output if no errors.
440 if (Res == 0) Out->keep();
446 int main(int argc, char **argv) {
447 // Print a stack trace if we signal out.
448 sys::PrintStackTraceOnErrorSignal();
449 PrettyStackTraceProgram X(argc, argv);
450 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
452 // Initialize targets and assembly printers/parsers.
453 llvm::InitializeAllTargetInfos();
454 // FIXME: We shouldn't need to initialize the Target(Machine)s.
455 llvm::InitializeAllTargets();
456 llvm::InitializeAllMCInstrInfos();
457 llvm::InitializeAllMCSubtargetInfos();
458 llvm::InitializeAllAsmPrinters();
459 llvm::InitializeAllAsmParsers();
460 llvm::InitializeAllDisassemblers();
462 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
463 TripleName = Triple::normalize(TripleName);
468 return AsLexInput(argv[0]);
470 return AssembleInput(argv[0]);
472 return DisassembleInput(argv[0], false);
473 case AC_EDisassemble:
474 return DisassembleInput(argv[0], true);