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/MCObjectFileInfo.h"
22 #include "llvm/MC/MCRegisterInfo.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCStreamer.h"
25 #include "llvm/MC/MCSubtargetInfo.h"
26 #include "llvm/MC/SubtargetFeature.h"
27 #include "llvm/MC/TargetAsmBackend.h"
28 #include "llvm/MC/TargetAsmParser.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetRegistry.h"
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 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
75 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging"));
82 static cl::opt<OutputFileType>
83 FileType("filetype", cl::init(OFT_AssemblyFile),
84 cl::desc("Choose an output file type:"),
86 clEnumValN(OFT_AssemblyFile, "asm",
87 "Emit an assembly ('.s') file"),
88 clEnumValN(OFT_Null, "null",
89 "Don't emit anything (for timing purposes)"),
90 clEnumValN(OFT_ObjectFile, "obj",
91 "Emit a native object ('.o') file"),
94 static cl::list<std::string>
95 IncludeDirs("I", cl::desc("Directory of include files"),
96 cl::value_desc("directory"), cl::Prefix);
98 static cl::opt<std::string>
99 ArchName("arch", cl::desc("Target arch to assemble for, "
100 "see -version for available targets"));
102 static cl::opt<std::string>
103 TripleName("triple", cl::desc("Target triple to assemble for, "
104 "see -version for available targets"));
106 static cl::opt<std::string>
108 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
109 cl::value_desc("cpu-name"),
112 static cl::opt<Reloc::Model>
113 RelocModel("relocation-model",
114 cl::desc("Choose relocation model"),
115 cl::init(Reloc::Default),
117 clEnumValN(Reloc::Default, "default",
118 "Target default relocation model"),
119 clEnumValN(Reloc::Static, "static",
120 "Non-relocatable code"),
121 clEnumValN(Reloc::PIC_, "pic",
122 "Fully relocatable, position independent code"),
123 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
124 "Relocatable external references, non-relocatable code"),
127 static cl::opt<llvm::CodeModel::Model>
128 CMModel("code-model",
129 cl::desc("Choose code model"),
130 cl::init(CodeModel::Default),
131 cl::values(clEnumValN(CodeModel::Default, "default",
132 "Target default code model"),
133 clEnumValN(CodeModel::Small, "small",
135 clEnumValN(CodeModel::Kernel, "kernel",
136 "Kernel code model"),
137 clEnumValN(CodeModel::Medium, "medium",
138 "Medium code model"),
139 clEnumValN(CodeModel::Large, "large",
144 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
145 "in the text section"));
148 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
157 static cl::opt<ActionType>
158 Action(cl::desc("Action to perform:"),
159 cl::init(AC_Assemble),
160 cl::values(clEnumValN(AC_AsLex, "as-lex",
161 "Lex tokens from a .s file"),
162 clEnumValN(AC_Assemble, "assemble",
163 "Assemble a .s file (default)"),
164 clEnumValN(AC_Disassemble, "disassemble",
165 "Disassemble strings of hex bytes"),
166 clEnumValN(AC_EDisassemble, "edis",
167 "Enhanced disassembly of strings of hex bytes"),
170 static const Target *GetTarget(const char *ProgName) {
171 // Figure out the target triple.
172 if (TripleName.empty())
173 TripleName = sys::getHostTriple();
174 if (!ArchName.empty()) {
175 llvm::Triple TT(TripleName);
176 TT.setArchName(ArchName);
177 TripleName = TT.str();
180 // Get the target specific parser.
182 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
186 errs() << ProgName << ": error: unable to get target for '" << TripleName
187 << "', see --version and --triple.\n";
191 static tool_output_file *GetOutputStream() {
192 if (OutputFilename == "")
193 OutputFilename = "-";
196 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
197 raw_fd_ostream::F_Binary);
199 errs() << Err << '\n';
207 static int AsLexInput(const char *ProgName) {
208 OwningPtr<MemoryBuffer> BufferPtr;
209 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
210 errs() << ProgName << ": " << ec.message() << '\n';
213 MemoryBuffer *Buffer = BufferPtr.take();
217 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
218 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
220 // Record the location of the include directories so that the lexer can find
222 SrcMgr.setIncludeDirs(IncludeDirs);
224 const Target *TheTarget = GetTarget(ProgName);
228 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
229 assert(MAI && "Unable to create target asm info!");
231 AsmLexer Lexer(*MAI);
232 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
234 OwningPtr<tool_output_file> Out(GetOutputStream());
239 while (Lexer.Lex().isNot(AsmToken::Eof)) {
240 AsmToken Tok = Lexer.getTok();
242 switch (Tok.getKind()) {
244 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning");
247 case AsmToken::Error:
248 Error = true; // error already printed.
250 case AsmToken::Identifier:
251 Out->os() << "identifier: " << Lexer.getTok().getString();
253 case AsmToken::Integer:
254 Out->os() << "int: " << Lexer.getTok().getString();
257 Out->os() << "real: " << Lexer.getTok().getString();
259 case AsmToken::Register:
260 Out->os() << "register: " << Lexer.getTok().getRegVal();
262 case AsmToken::String:
263 Out->os() << "string: " << Lexer.getTok().getString();
266 case AsmToken::Amp: Out->os() << "Amp"; break;
267 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
268 case AsmToken::At: Out->os() << "At"; break;
269 case AsmToken::Caret: Out->os() << "Caret"; break;
270 case AsmToken::Colon: Out->os() << "Colon"; break;
271 case AsmToken::Comma: Out->os() << "Comma"; break;
272 case AsmToken::Dollar: Out->os() << "Dollar"; break;
273 case AsmToken::Dot: Out->os() << "Dot"; break;
274 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
275 case AsmToken::Eof: Out->os() << "Eof"; break;
276 case AsmToken::Equal: Out->os() << "Equal"; break;
277 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
278 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
279 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
280 case AsmToken::Greater: Out->os() << "Greater"; break;
281 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
282 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
283 case AsmToken::Hash: Out->os() << "Hash"; break;
284 case AsmToken::LBrac: Out->os() << "LBrac"; break;
285 case AsmToken::LCurly: Out->os() << "LCurly"; break;
286 case AsmToken::LParen: Out->os() << "LParen"; break;
287 case AsmToken::Less: Out->os() << "Less"; break;
288 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
289 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
290 case AsmToken::LessLess: Out->os() << "LessLess"; break;
291 case AsmToken::Minus: Out->os() << "Minus"; break;
292 case AsmToken::Percent: Out->os() << "Percent"; break;
293 case AsmToken::Pipe: Out->os() << "Pipe"; break;
294 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
295 case AsmToken::Plus: Out->os() << "Plus"; break;
296 case AsmToken::RBrac: Out->os() << "RBrac"; break;
297 case AsmToken::RCurly: Out->os() << "RCurly"; break;
298 case AsmToken::RParen: Out->os() << "RParen"; break;
299 case AsmToken::Slash: Out->os() << "Slash"; break;
300 case AsmToken::Star: Out->os() << "Star"; break;
301 case AsmToken::Tilde: Out->os() << "Tilde"; break;
304 // Print the token string.
306 Out->os().write_escaped(Tok.getString());
307 Out->os() << "\")\n";
310 // Keep output if no errors.
311 if (Error == 0) Out->keep();
316 static int AssembleInput(const char *ProgName) {
317 const Target *TheTarget = GetTarget(ProgName);
321 OwningPtr<MemoryBuffer> BufferPtr;
322 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
323 errs() << ProgName << ": " << ec.message() << '\n';
326 MemoryBuffer *Buffer = BufferPtr.take();
330 // Tell SrcMgr about this buffer, which is what the parser will pick up.
331 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
333 // Record the location of the include directories so that the lexer can find
335 SrcMgr.setIncludeDirs(IncludeDirs);
338 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
339 assert(MAI && "Unable to create target asm info!");
341 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
342 assert(MRI && "Unable to create target register info!");
344 // Package up features to be passed to target/subtarget
345 std::string FeaturesStr;
347 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
348 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
349 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
350 MCContext Ctx(*MAI, *MRI, MOFI.get());
351 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
354 Ctx.setAllowTemporaryLabels(false);
356 OwningPtr<tool_output_file> Out(GetOutputStream());
360 formatted_raw_ostream FOS(Out->os());
361 OwningPtr<MCStreamer> Str;
363 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
364 OwningPtr<MCSubtargetInfo>
365 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
367 // FIXME: There is a bit of code duplication with addPassesToEmitFile.
368 if (FileType == OFT_AssemblyFile) {
370 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI);
371 MCCodeEmitter *CE = 0;
372 TargetAsmBackend *TAB = 0;
374 CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
375 TAB = TheTarget->createAsmBackend(TripleName);
377 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
379 /*useCFI*/ true, IP, CE, TAB,
381 } else if (FileType == OFT_Null) {
382 Str.reset(createNullStreamer(Ctx));
384 assert(FileType == OFT_ObjectFile && "Invalid file type!");
385 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*MCII, *STI, Ctx);
386 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName);
387 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB,
393 Str.reset(createLoggingStreamer(Str.take(), errs()));
396 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx,
398 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*STI, *Parser));
401 << ": error: this target does not support assembly parsing.\n";
405 Parser->setShowParsedOperands(ShowInstOperands);
406 Parser->setTargetParser(*TAP.get());
408 int Res = Parser->Run(NoInitialTextSection);
410 // Keep output if no errors.
411 if (Res == 0) Out->keep();
416 static int DisassembleInput(const char *ProgName, bool Enhanced) {
417 const Target *TheTarget = GetTarget(ProgName);
421 OwningPtr<MemoryBuffer> Buffer;
422 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) {
423 errs() << ProgName << ": " << ec.message() << '\n';
427 OwningPtr<tool_output_file> Out(GetOutputStream());
434 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os());
436 Res = Disassembler::disassemble(*TheTarget, TripleName,
437 *Buffer.take(), Out->os());
440 // Keep output if no errors.
441 if (Res == 0) Out->keep();
447 int main(int argc, char **argv) {
448 // Print a stack trace if we signal out.
449 sys::PrintStackTraceOnErrorSignal();
450 PrettyStackTraceProgram X(argc, argv);
451 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
453 // Initialize targets and assembly printers/parsers.
454 llvm::InitializeAllTargetInfos();
455 // FIXME: We shouldn't need to initialize the Target(Machine)s.
456 llvm::InitializeAllTargets();
457 llvm::InitializeAllTargetMCs();
458 llvm::InitializeAllAsmPrinters();
459 llvm::InitializeAllAsmParsers();
460 llvm::InitializeAllDisassemblers();
462 // Register the target printer for --version.
463 // FIXME: Remove when we stop initializing the Target(Machine)s above.
464 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
466 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
467 TripleName = Triple::normalize(TripleName);
472 return AsLexInput(argv[0]);
474 return AssembleInput(argv[0]);
476 return DisassembleInput(argv[0], false);
477 case AC_EDisassemble:
478 return DisassembleInput(argv[0], true);