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/MC/MCAsmBackend.h"
17 #include "llvm/MC/MCAsmInfo.h"
18 #include "llvm/MC/MCContext.h"
19 #include "llvm/MC/MCInstPrinter.h"
20 #include "llvm/MC/MCInstrInfo.h"
21 #include "llvm/MC/MCObjectFileInfo.h"
22 #include "llvm/MC/MCParser/AsmLexer.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSubtargetInfo.h"
27 #include "llvm/MC/MCTargetAsmParser.h"
28 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Compression.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/FormattedStream.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include "llvm/Support/ToolOutputFile.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 CompressDebugSections("compress-debug-sections", cl::desc("Compress DWARF debug sections"));
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 PrintImmHex("print-imm-hex", cl::init(false),
70 cl::desc("Prefer hex format for immediate values"));
77 static cl::opt<OutputFileType>
78 FileType("filetype", cl::init(OFT_AssemblyFile),
79 cl::desc("Choose an output file type:"),
81 clEnumValN(OFT_AssemblyFile, "asm",
82 "Emit an assembly ('.s') file"),
83 clEnumValN(OFT_Null, "null",
84 "Don't emit anything (for timing purposes)"),
85 clEnumValN(OFT_ObjectFile, "obj",
86 "Emit a native object ('.o') file"),
89 static cl::list<std::string>
90 IncludeDirs("I", cl::desc("Directory of include files"),
91 cl::value_desc("directory"), cl::Prefix);
93 static cl::opt<std::string>
94 ArchName("arch", cl::desc("Target arch to assemble for, "
95 "see -version for available targets"));
97 static cl::opt<std::string>
98 TripleName("triple", cl::desc("Target triple to assemble for, "
99 "see -version for available targets"));
101 static cl::opt<std::string>
103 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
104 cl::value_desc("cpu-name"),
107 static cl::list<std::string>
110 cl::desc("Target specific attributes (-mattr=help for details)"),
111 cl::value_desc("a1,+a2,-a3,..."));
113 static cl::opt<Reloc::Model>
114 RelocModel("relocation-model",
115 cl::desc("Choose relocation model"),
116 cl::init(Reloc::Default),
118 clEnumValN(Reloc::Default, "default",
119 "Target default relocation model"),
120 clEnumValN(Reloc::Static, "static",
121 "Non-relocatable code"),
122 clEnumValN(Reloc::PIC_, "pic",
123 "Fully relocatable, position independent code"),
124 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
125 "Relocatable external references, non-relocatable code"),
128 static cl::opt<llvm::CodeModel::Model>
129 CMModel("code-model",
130 cl::desc("Choose code model"),
131 cl::init(CodeModel::Default),
132 cl::values(clEnumValN(CodeModel::Default, "default",
133 "Target default code model"),
134 clEnumValN(CodeModel::Small, "small",
136 clEnumValN(CodeModel::Kernel, "kernel",
137 "Kernel code model"),
138 clEnumValN(CodeModel::Medium, "medium",
139 "Medium code model"),
140 clEnumValN(CodeModel::Large, "large",
145 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
146 "in the text section"));
149 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
153 DwarfVersion("dwarf-version", cl::desc("Dwarf version"), cl::init(4));
155 static cl::opt<std::string>
156 DebugCompilationDir("fdebug-compilation-dir",
157 cl::desc("Specifies the debug info's compilation dir"));
159 static cl::opt<std::string>
160 MainFileName("main-file-name",
161 cl::desc("Specifies the name we should consider the input file"));
163 static cl::opt<bool> SaveTempLabels("save-temp-labels",
164 cl::desc("Don't discard temporary labels"));
166 static cl::opt<bool> NoExecStack("no-exec-stack",
167 cl::desc("File doesn't need an exec stack"));
176 static cl::opt<ActionType>
177 Action(cl::desc("Action to perform:"),
178 cl::init(AC_Assemble),
179 cl::values(clEnumValN(AC_AsLex, "as-lex",
180 "Lex tokens from a .s file"),
181 clEnumValN(AC_Assemble, "assemble",
182 "Assemble a .s file (default)"),
183 clEnumValN(AC_Disassemble, "disassemble",
184 "Disassemble strings of hex bytes"),
185 clEnumValN(AC_MDisassemble, "mdis",
186 "Marked up disassembly of strings of hex bytes"),
189 static const Target *GetTarget(const char *ProgName) {
190 // Figure out the target triple.
191 if (TripleName.empty())
192 TripleName = sys::getDefaultTargetTriple();
193 Triple TheTriple(Triple::normalize(TripleName));
195 // Get the target specific parser.
197 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
200 errs() << ProgName << ": " << Error;
204 // Update the triple name and return the found target.
205 TripleName = TheTriple.getTriple();
209 static tool_output_file *GetOutputStream() {
210 if (OutputFilename == "")
211 OutputFilename = "-";
214 tool_output_file *Out =
215 new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_None);
217 errs() << Err << '\n';
225 static std::string DwarfDebugFlags;
226 static void setDwarfDebugFlags(int argc, char **argv) {
227 if (!getenv("RC_DEBUG_OPTIONS"))
229 for (int i = 0; i < argc; i++) {
230 DwarfDebugFlags += argv[i];
232 DwarfDebugFlags += " ";
236 static std::string DwarfDebugProducer;
237 static void setDwarfDebugProducer(void) {
238 if(!getenv("DEBUG_PRODUCER"))
240 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
243 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
246 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
249 while (Lexer.Lex().isNot(AsmToken::Eof)) {
250 AsmToken Tok = Lexer.getTok();
252 switch (Tok.getKind()) {
254 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
258 case AsmToken::Error:
259 Error = true; // error already printed.
261 case AsmToken::Identifier:
262 Out->os() << "identifier: " << Lexer.getTok().getString();
264 case AsmToken::Integer:
265 Out->os() << "int: " << Lexer.getTok().getString();
268 Out->os() << "real: " << Lexer.getTok().getString();
270 case AsmToken::String:
271 Out->os() << "string: " << Lexer.getTok().getString();
274 case AsmToken::Amp: Out->os() << "Amp"; break;
275 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
276 case AsmToken::At: Out->os() << "At"; break;
277 case AsmToken::Caret: Out->os() << "Caret"; break;
278 case AsmToken::Colon: Out->os() << "Colon"; break;
279 case AsmToken::Comma: Out->os() << "Comma"; break;
280 case AsmToken::Dollar: Out->os() << "Dollar"; break;
281 case AsmToken::Dot: Out->os() << "Dot"; break;
282 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
283 case AsmToken::Eof: Out->os() << "Eof"; break;
284 case AsmToken::Equal: Out->os() << "Equal"; break;
285 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
286 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
287 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
288 case AsmToken::Greater: Out->os() << "Greater"; break;
289 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
290 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
291 case AsmToken::Hash: Out->os() << "Hash"; break;
292 case AsmToken::LBrac: Out->os() << "LBrac"; break;
293 case AsmToken::LCurly: Out->os() << "LCurly"; break;
294 case AsmToken::LParen: Out->os() << "LParen"; break;
295 case AsmToken::Less: Out->os() << "Less"; break;
296 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
297 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
298 case AsmToken::LessLess: Out->os() << "LessLess"; break;
299 case AsmToken::Minus: Out->os() << "Minus"; break;
300 case AsmToken::Percent: Out->os() << "Percent"; break;
301 case AsmToken::Pipe: Out->os() << "Pipe"; break;
302 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
303 case AsmToken::Plus: Out->os() << "Plus"; break;
304 case AsmToken::RBrac: Out->os() << "RBrac"; break;
305 case AsmToken::RCurly: Out->os() << "RCurly"; break;
306 case AsmToken::RParen: Out->os() << "RParen"; break;
307 case AsmToken::Slash: Out->os() << "Slash"; break;
308 case AsmToken::Star: Out->os() << "Star"; break;
309 case AsmToken::Tilde: Out->os() << "Tilde"; break;
312 // Print the token string.
314 Out->os().write_escaped(Tok.getString());
315 Out->os() << "\")\n";
321 static int AssembleInput(const char *ProgName, const Target *TheTarget,
322 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
323 MCAsmInfo &MAI, MCSubtargetInfo &STI, MCInstrInfo &MCII) {
324 std::unique_ptr<MCAsmParser> Parser(
325 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
326 std::unique_ptr<MCTargetAsmParser> TAP(
327 TheTarget->createMCAsmParser(STI, *Parser, MCII,
328 InitMCTargetOptionsFromFlags()));
331 << ": error: this target does not support assembly parsing.\n";
335 Parser->setShowParsedOperands(ShowInstOperands);
336 Parser->setTargetParser(*TAP.get());
338 int Res = Parser->Run(NoInitialTextSection);
343 int main(int argc, char **argv) {
344 // Print a stack trace if we signal out.
345 sys::PrintStackTraceOnErrorSignal();
346 PrettyStackTraceProgram X(argc, argv);
347 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
349 // Initialize targets and assembly printers/parsers.
350 llvm::InitializeAllTargetInfos();
351 llvm::InitializeAllTargetMCs();
352 llvm::InitializeAllAsmParsers();
353 llvm::InitializeAllDisassemblers();
355 // Register the target printer for --version.
356 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
358 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
359 TripleName = Triple::normalize(TripleName);
360 setDwarfDebugFlags(argc, argv);
362 setDwarfDebugProducer();
364 const char *ProgName = argv[0];
365 const Target *TheTarget = GetTarget(ProgName);
369 std::unique_ptr<MemoryBuffer> BufferPtr;
370 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
371 errs() << ProgName << ": " << ec.message() << '\n';
374 MemoryBuffer *Buffer = BufferPtr.release();
378 // Tell SrcMgr about this buffer, which is what the parser will pick up.
379 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
381 // Record the location of the include directories so that the lexer can find
383 SrcMgr.setIncludeDirs(IncludeDirs);
385 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
386 assert(MRI && "Unable to create target register info!");
388 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
389 assert(MAI && "Unable to create target asm info!");
391 if (CompressDebugSections) {
392 if (!zlib::isAvailable()) {
393 errs() << ProgName << ": build tools with zlib to enable -compress-debug-sections";
396 MAI->setCompressDebugSections(true);
399 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
400 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
401 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
402 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
403 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
406 Ctx.setAllowTemporaryLabels(false);
408 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
409 if (DwarfVersion < 2 || DwarfVersion > 4) {
410 errs() << ProgName << ": Dwarf version " << DwarfVersion
411 << " is not supported." << '\n';
414 Ctx.setDwarfVersion(DwarfVersion);
415 if (!DwarfDebugFlags.empty())
416 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
417 if (!DwarfDebugProducer.empty())
418 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
419 if (!DebugCompilationDir.empty())
420 Ctx.setCompilationDir(DebugCompilationDir);
421 if (!MainFileName.empty())
422 Ctx.setMainFileName(MainFileName);
424 // Package up features to be passed to target/subtarget
425 std::string FeaturesStr;
427 SubtargetFeatures Features;
428 for (unsigned i = 0; i != MAttrs.size(); ++i)
429 Features.AddFeature(MAttrs[i]);
430 FeaturesStr = Features.getString();
433 std::unique_ptr<tool_output_file> Out(GetOutputStream());
437 formatted_raw_ostream FOS(Out->os());
438 std::unique_ptr<MCStreamer> Str;
440 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
441 std::unique_ptr<MCSubtargetInfo> STI(
442 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
444 MCInstPrinter *IP = nullptr;
445 if (FileType == OFT_AssemblyFile) {
447 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
449 // Set the display preference for hex vs. decimal immediates.
450 IP->setPrintImmHex(PrintImmHex);
452 // Set up the AsmStreamer.
453 MCCodeEmitter *CE = nullptr;
454 MCAsmBackend *MAB = nullptr;
456 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
457 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
459 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/ true,
460 /*useDwarfDirectory*/ true, IP, CE,
463 } else if (FileType == OFT_Null) {
464 Str.reset(createNullStreamer(Ctx));
466 assert(FileType == OFT_ObjectFile && "Invalid file type!");
467 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
468 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
469 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
470 FOS, CE, *STI, RelaxAll,
475 bool disassemble = false;
478 Res = AsLexInput(SrcMgr, *MAI, Out.get());
481 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, *MCII);
483 case AC_MDisassemble:
484 assert(IP && "Expected assembly output");
493 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
494 *Buffer, SrcMgr, Out->os());
496 // Keep output if no errors.
497 if (Res == 0) Out->keep();