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 "Disassembler.h"
16 #include "llvm/ADT/OwningPtr.h"
17 #include "llvm/MC/MCAsmBackend.h"
18 #include "llvm/MC/MCAsmInfo.h"
19 #include "llvm/MC/MCCodeEmitter.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCInstPrinter.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCObjectFileInfo.h"
24 #include "llvm/MC/MCParser/AsmLexer.h"
25 #include "llvm/MC/MCParser/MCAsmLexer.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSectionMachO.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/MC/SubtargetFeature.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/FileUtilities.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/ToolOutputFile.h"
44 #include "llvm/Support/system_error.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 DisableCFI("disable-cfi", cl::desc("Do not use .cfi_* directives"));
75 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
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::list<std::string>
115 cl::desc("Target specific attributes (-mattr=help for details)"),
116 cl::value_desc("a1,+a2,-a3,..."));
118 static cl::opt<Reloc::Model>
119 RelocModel("relocation-model",
120 cl::desc("Choose relocation model"),
121 cl::init(Reloc::Default),
123 clEnumValN(Reloc::Default, "default",
124 "Target default relocation model"),
125 clEnumValN(Reloc::Static, "static",
126 "Non-relocatable code"),
127 clEnumValN(Reloc::PIC_, "pic",
128 "Fully relocatable, position independent code"),
129 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
130 "Relocatable external references, non-relocatable code"),
133 static cl::opt<llvm::CodeModel::Model>
134 CMModel("code-model",
135 cl::desc("Choose code model"),
136 cl::init(CodeModel::Default),
137 cl::values(clEnumValN(CodeModel::Default, "default",
138 "Target default code model"),
139 clEnumValN(CodeModel::Small, "small",
141 clEnumValN(CodeModel::Kernel, "kernel",
142 "Kernel code model"),
143 clEnumValN(CodeModel::Medium, "medium",
144 "Medium code model"),
145 clEnumValN(CodeModel::Large, "large",
150 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
151 "in the text section"));
154 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
157 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
169 static cl::opt<ActionType>
170 Action(cl::desc("Action to perform:"),
171 cl::init(AC_Assemble),
172 cl::values(clEnumValN(AC_AsLex, "as-lex",
173 "Lex tokens from a .s file"),
174 clEnumValN(AC_Assemble, "assemble",
175 "Assemble a .s file (default)"),
176 clEnumValN(AC_Disassemble, "disassemble",
177 "Disassemble strings of hex bytes"),
178 clEnumValN(AC_EDisassemble, "edis",
179 "Enhanced disassembly of strings of hex bytes"),
180 clEnumValN(AC_MDisassemble, "mdis",
181 "Marked up disassembly of strings of hex bytes"),
182 clEnumValN(AC_HDisassemble, "hdis",
183 "Disassemble strings of hex bytes printing "
184 "immediates as hex"),
187 static const Target *GetTarget(const char *ProgName) {
188 // Figure out the target triple.
189 if (TripleName.empty())
190 TripleName = sys::getDefaultTargetTriple();
191 Triple TheTriple(Triple::normalize(TripleName));
193 // Get the target specific parser.
195 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
198 errs() << ProgName << ": " << Error;
202 // Update the triple name and return the found target.
203 TripleName = TheTriple.getTriple();
207 static tool_output_file *GetOutputStream() {
208 if (OutputFilename == "")
209 OutputFilename = "-";
212 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err,
213 raw_fd_ostream::F_Binary);
215 errs() << Err << '\n';
223 static std::string DwarfDebugFlags;
224 static void setDwarfDebugFlags(int argc, char **argv) {
225 if (!getenv("RC_DEBUG_OPTIONS"))
227 for (int i = 0; i < argc; i++) {
228 DwarfDebugFlags += argv[i];
230 DwarfDebugFlags += " ";
234 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
237 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
240 while (Lexer.Lex().isNot(AsmToken::Eof)) {
241 AsmToken Tok = Lexer.getTok();
243 switch (Tok.getKind()) {
245 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
249 case AsmToken::Error:
250 Error = true; // error already printed.
252 case AsmToken::Identifier:
253 Out->os() << "identifier: " << Lexer.getTok().getString();
255 case AsmToken::Integer:
256 Out->os() << "int: " << Lexer.getTok().getString();
259 Out->os() << "real: " << Lexer.getTok().getString();
261 case AsmToken::Register:
262 Out->os() << "register: " << Lexer.getTok().getRegVal();
264 case AsmToken::String:
265 Out->os() << "string: " << Lexer.getTok().getString();
268 case AsmToken::Amp: Out->os() << "Amp"; break;
269 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
270 case AsmToken::At: Out->os() << "At"; break;
271 case AsmToken::Caret: Out->os() << "Caret"; break;
272 case AsmToken::Colon: Out->os() << "Colon"; break;
273 case AsmToken::Comma: Out->os() << "Comma"; break;
274 case AsmToken::Dollar: Out->os() << "Dollar"; break;
275 case AsmToken::Dot: Out->os() << "Dot"; break;
276 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
277 case AsmToken::Eof: Out->os() << "Eof"; break;
278 case AsmToken::Equal: Out->os() << "Equal"; break;
279 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
280 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
281 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
282 case AsmToken::Greater: Out->os() << "Greater"; break;
283 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
284 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
285 case AsmToken::Hash: Out->os() << "Hash"; break;
286 case AsmToken::LBrac: Out->os() << "LBrac"; break;
287 case AsmToken::LCurly: Out->os() << "LCurly"; break;
288 case AsmToken::LParen: Out->os() << "LParen"; break;
289 case AsmToken::Less: Out->os() << "Less"; break;
290 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
291 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
292 case AsmToken::LessLess: Out->os() << "LessLess"; break;
293 case AsmToken::Minus: Out->os() << "Minus"; break;
294 case AsmToken::Percent: Out->os() << "Percent"; break;
295 case AsmToken::Pipe: Out->os() << "Pipe"; break;
296 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
297 case AsmToken::Plus: Out->os() << "Plus"; break;
298 case AsmToken::RBrac: Out->os() << "RBrac"; break;
299 case AsmToken::RCurly: Out->os() << "RCurly"; break;
300 case AsmToken::RParen: Out->os() << "RParen"; break;
301 case AsmToken::Slash: Out->os() << "Slash"; break;
302 case AsmToken::Star: Out->os() << "Star"; break;
303 case AsmToken::Tilde: Out->os() << "Tilde"; break;
306 // Print the token string.
308 Out->os().write_escaped(Tok.getString());
309 Out->os() << "\")\n";
315 static int AssembleInput(const char *ProgName, const Target *TheTarget,
316 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
317 MCAsmInfo &MAI, MCSubtargetInfo &STI) {
318 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx,
320 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(STI, *Parser));
323 << ": error: this target does not support assembly parsing.\n";
327 Parser->setShowParsedOperands(ShowInstOperands);
328 Parser->setTargetParser(*TAP.get());
330 int Res = Parser->Run(NoInitialTextSection);
335 int main(int argc, char **argv) {
336 // Print a stack trace if we signal out.
337 sys::PrintStackTraceOnErrorSignal();
338 PrettyStackTraceProgram X(argc, argv);
339 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
341 // Initialize targets and assembly printers/parsers.
342 llvm::InitializeAllTargetInfos();
343 llvm::InitializeAllTargetMCs();
344 llvm::InitializeAllAsmParsers();
345 llvm::InitializeAllDisassemblers();
347 // Register the target printer for --version.
348 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
350 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
351 TripleName = Triple::normalize(TripleName);
352 setDwarfDebugFlags(argc, argv);
354 const char *ProgName = argv[0];
355 const Target *TheTarget = GetTarget(ProgName);
359 OwningPtr<MemoryBuffer> BufferPtr;
360 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
361 errs() << ProgName << ": " << ec.message() << '\n';
364 MemoryBuffer *Buffer = BufferPtr.take();
368 // Tell SrcMgr about this buffer, which is what the parser will pick up.
369 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
371 // Record the location of the include directories so that the lexer can find
373 SrcMgr.setIncludeDirs(IncludeDirs);
376 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName));
377 assert(MAI && "Unable to create target asm info!");
379 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
380 assert(MRI && "Unable to create target register info!");
382 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
383 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
384 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
385 MCContext Ctx(*MAI, *MRI, MOFI.get(), &SrcMgr);
386 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
389 Ctx.setAllowTemporaryLabels(false);
391 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
392 if (!DwarfDebugFlags.empty())
393 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
395 // Package up features to be passed to target/subtarget
396 std::string FeaturesStr;
398 SubtargetFeatures Features;
399 for (unsigned i = 0; i != MAttrs.size(); ++i)
400 Features.AddFeature(MAttrs[i]);
401 FeaturesStr = Features.getString();
404 OwningPtr<tool_output_file> Out(GetOutputStream());
408 formatted_raw_ostream FOS(Out->os());
409 OwningPtr<MCStreamer> Str;
411 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
412 OwningPtr<MCSubtargetInfo>
413 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
416 if (FileType == OFT_AssemblyFile) {
418 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
419 MCCodeEmitter *CE = 0;
420 MCAsmBackend *MAB = 0;
422 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
423 MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
425 bool UseCFI = !DisableCFI;
426 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true,
429 /*useDwarfDirectory*/ true,
430 IP, CE, MAB, ShowInst));
432 } else if (FileType == OFT_Null) {
433 Str.reset(createNullStreamer(Ctx));
435 assert(FileType == OFT_ObjectFile && "Invalid file type!");
436 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
437 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName, MCPU);
438 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
444 bool disassemble = false;
447 Res = AsLexInput(SrcMgr, *MAI, Out.get());
450 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI);
452 case AC_MDisassemble:
456 case AC_HDisassemble:
457 IP->setPrintImmHex(1);
463 case AC_EDisassemble:
464 Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, SrcMgr, Out->os());
468 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
469 *Buffer, SrcMgr, Out->os());
471 // Keep output if no errors.
472 if (Res == 0) Out->keep();