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/Support/CommandLine.h"
29 #include "llvm/Support/FileUtilities.h"
30 #include "llvm/Support/FormattedStream.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/ToolOutputFile.h"
42 static cl::opt<std::string>
43 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
45 static cl::opt<std::string>
46 OutputFilename("o", cl::desc("Output filename"),
47 cl::value_desc("filename"));
50 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
53 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
56 ShowInstOperands("show-inst-operands",
57 cl::desc("Show instructions operands as parsed"));
59 static cl::opt<unsigned>
60 OutputAsmVariant("output-asm-variant",
61 cl::desc("Syntax variant to use for output printing"));
64 RelaxAll("mc-relax-all", cl::desc("Relax all fixups"));
67 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack"));
74 static cl::opt<OutputFileType>
75 FileType("filetype", cl::init(OFT_AssemblyFile),
76 cl::desc("Choose an output file type:"),
78 clEnumValN(OFT_AssemblyFile, "asm",
79 "Emit an assembly ('.s') file"),
80 clEnumValN(OFT_Null, "null",
81 "Don't emit anything (for timing purposes)"),
82 clEnumValN(OFT_ObjectFile, "obj",
83 "Emit a native object ('.o') file"),
86 static cl::list<std::string>
87 IncludeDirs("I", cl::desc("Directory of include files"),
88 cl::value_desc("directory"), cl::Prefix);
90 static cl::opt<std::string>
91 ArchName("arch", cl::desc("Target arch to assemble for, "
92 "see -version for available targets"));
94 static cl::opt<std::string>
95 TripleName("triple", cl::desc("Target triple to assemble for, "
96 "see -version for available targets"));
98 static cl::opt<std::string>
100 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
101 cl::value_desc("cpu-name"),
104 static cl::list<std::string>
107 cl::desc("Target specific attributes (-mattr=help for details)"),
108 cl::value_desc("a1,+a2,-a3,..."));
110 static cl::opt<Reloc::Model>
111 RelocModel("relocation-model",
112 cl::desc("Choose relocation model"),
113 cl::init(Reloc::Default),
115 clEnumValN(Reloc::Default, "default",
116 "Target default relocation model"),
117 clEnumValN(Reloc::Static, "static",
118 "Non-relocatable code"),
119 clEnumValN(Reloc::PIC_, "pic",
120 "Fully relocatable, position independent code"),
121 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
122 "Relocatable external references, non-relocatable code"),
125 static cl::opt<llvm::CodeModel::Model>
126 CMModel("code-model",
127 cl::desc("Choose code model"),
128 cl::init(CodeModel::Default),
129 cl::values(clEnumValN(CodeModel::Default, "default",
130 "Target default code model"),
131 clEnumValN(CodeModel::Small, "small",
133 clEnumValN(CodeModel::Kernel, "kernel",
134 "Kernel code model"),
135 clEnumValN(CodeModel::Medium, "medium",
136 "Medium code model"),
137 clEnumValN(CodeModel::Large, "large",
142 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
143 "in the text section"));
146 SaveTempLabels("L", cl::desc("Don't discard temporary labels"));
149 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
152 static cl::opt<std::string>
153 DebugCompilationDir("fdebug-compilation-dir",
154 cl::desc("Specifies the debug info's compilation dir"));
156 static cl::opt<std::string>
157 MainFileName("main-file-name",
158 cl::desc("Specifies the name we should consider the input file"));
168 static cl::opt<ActionType>
169 Action(cl::desc("Action to perform:"),
170 cl::init(AC_Assemble),
171 cl::values(clEnumValN(AC_AsLex, "as-lex",
172 "Lex tokens from a .s file"),
173 clEnumValN(AC_Assemble, "assemble",
174 "Assemble a .s file (default)"),
175 clEnumValN(AC_Disassemble, "disassemble",
176 "Disassemble strings of hex bytes"),
177 clEnumValN(AC_MDisassemble, "mdis",
178 "Marked up disassembly of strings of hex bytes"),
179 clEnumValN(AC_HDisassemble, "hdis",
180 "Disassemble strings of hex bytes printing "
181 "immediates as hex"),
184 static const Target *GetTarget(const char *ProgName) {
185 // Figure out the target triple.
186 if (TripleName.empty())
187 TripleName = sys::getDefaultTargetTriple();
188 Triple TheTriple(Triple::normalize(TripleName));
190 // Get the target specific parser.
192 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
195 errs() << ProgName << ": " << Error;
199 // Update the triple name and return the found target.
200 TripleName = TheTriple.getTriple();
204 static tool_output_file *GetOutputStream() {
205 if (OutputFilename == "")
206 OutputFilename = "-";
209 tool_output_file *Out =
210 new tool_output_file(OutputFilename.c_str(), Err, sys::fs::F_None);
212 errs() << Err << '\n';
220 static std::string DwarfDebugFlags;
221 static void setDwarfDebugFlags(int argc, char **argv) {
222 if (!getenv("RC_DEBUG_OPTIONS"))
224 for (int i = 0; i < argc; i++) {
225 DwarfDebugFlags += argv[i];
227 DwarfDebugFlags += " ";
231 static std::string DwarfDebugProducer;
232 static void setDwarfDebugProducer(void) {
233 if(!getenv("DEBUG_PRODUCER"))
235 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
238 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, tool_output_file *Out) {
241 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0));
244 while (Lexer.Lex().isNot(AsmToken::Eof)) {
245 AsmToken Tok = Lexer.getTok();
247 switch (Tok.getKind()) {
249 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
253 case AsmToken::Error:
254 Error = true; // error already printed.
256 case AsmToken::Identifier:
257 Out->os() << "identifier: " << Lexer.getTok().getString();
259 case AsmToken::Integer:
260 Out->os() << "int: " << Lexer.getTok().getString();
263 Out->os() << "real: " << Lexer.getTok().getString();
265 case AsmToken::String:
266 Out->os() << "string: " << Lexer.getTok().getString();
269 case AsmToken::Amp: Out->os() << "Amp"; break;
270 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break;
271 case AsmToken::At: Out->os() << "At"; break;
272 case AsmToken::Caret: Out->os() << "Caret"; break;
273 case AsmToken::Colon: Out->os() << "Colon"; break;
274 case AsmToken::Comma: Out->os() << "Comma"; break;
275 case AsmToken::Dollar: Out->os() << "Dollar"; break;
276 case AsmToken::Dot: Out->os() << "Dot"; break;
277 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break;
278 case AsmToken::Eof: Out->os() << "Eof"; break;
279 case AsmToken::Equal: Out->os() << "Equal"; break;
280 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break;
281 case AsmToken::Exclaim: Out->os() << "Exclaim"; break;
282 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break;
283 case AsmToken::Greater: Out->os() << "Greater"; break;
284 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break;
285 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break;
286 case AsmToken::Hash: Out->os() << "Hash"; break;
287 case AsmToken::LBrac: Out->os() << "LBrac"; break;
288 case AsmToken::LCurly: Out->os() << "LCurly"; break;
289 case AsmToken::LParen: Out->os() << "LParen"; break;
290 case AsmToken::Less: Out->os() << "Less"; break;
291 case AsmToken::LessEqual: Out->os() << "LessEqual"; break;
292 case AsmToken::LessGreater: Out->os() << "LessGreater"; break;
293 case AsmToken::LessLess: Out->os() << "LessLess"; break;
294 case AsmToken::Minus: Out->os() << "Minus"; break;
295 case AsmToken::Percent: Out->os() << "Percent"; break;
296 case AsmToken::Pipe: Out->os() << "Pipe"; break;
297 case AsmToken::PipePipe: Out->os() << "PipePipe"; break;
298 case AsmToken::Plus: Out->os() << "Plus"; break;
299 case AsmToken::RBrac: Out->os() << "RBrac"; break;
300 case AsmToken::RCurly: Out->os() << "RCurly"; break;
301 case AsmToken::RParen: Out->os() << "RParen"; break;
302 case AsmToken::Slash: Out->os() << "Slash"; break;
303 case AsmToken::Star: Out->os() << "Star"; break;
304 case AsmToken::Tilde: Out->os() << "Tilde"; break;
307 // Print the token string.
309 Out->os().write_escaped(Tok.getString());
310 Out->os() << "\")\n";
316 static int AssembleInput(const char *ProgName, const Target *TheTarget,
317 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
318 MCAsmInfo &MAI, MCSubtargetInfo &STI, MCInstrInfo &MCII) {
319 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
320 std::unique_ptr<MCTargetAsmParser> TAP(
321 TheTarget->createMCAsmParser(STI, *Parser, MCII));
324 << ": error: this target does not support assembly parsing.\n";
328 Parser->setShowParsedOperands(ShowInstOperands);
329 Parser->setTargetParser(*TAP.get());
331 int Res = Parser->Run(NoInitialTextSection);
336 int main(int argc, char **argv) {
337 // Print a stack trace if we signal out.
338 sys::PrintStackTraceOnErrorSignal();
339 PrettyStackTraceProgram X(argc, argv);
340 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
342 // Initialize targets and assembly printers/parsers.
343 llvm::InitializeAllTargetInfos();
344 llvm::InitializeAllTargetMCs();
345 llvm::InitializeAllAsmParsers();
346 llvm::InitializeAllDisassemblers();
348 // Register the target printer for --version.
349 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
351 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
352 TripleName = Triple::normalize(TripleName);
353 setDwarfDebugFlags(argc, argv);
355 setDwarfDebugProducer();
357 const char *ProgName = argv[0];
358 const Target *TheTarget = GetTarget(ProgName);
362 std::unique_ptr<MemoryBuffer> BufferPtr;
363 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) {
364 errs() << ProgName << ": " << ec.message() << '\n';
367 MemoryBuffer *Buffer = BufferPtr.release();
371 // Tell SrcMgr about this buffer, which is what the parser will pick up.
372 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
374 // Record the location of the include directories so that the lexer can find
376 SrcMgr.setIncludeDirs(IncludeDirs);
378 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
379 assert(MRI && "Unable to create target register info!");
381 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
382 assert(MAI && "Unable to create target asm info!");
384 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
385 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
386 std::unique_ptr<MCObjectFileInfo> MOFI(new MCObjectFileInfo());
387 MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &SrcMgr);
388 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx);
391 Ctx.setAllowTemporaryLabels(false);
393 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
394 if (!DwarfDebugFlags.empty())
395 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
396 if (!DwarfDebugProducer.empty())
397 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
398 if (!DebugCompilationDir.empty())
399 Ctx.setCompilationDir(DebugCompilationDir);
400 if (!MainFileName.empty())
401 Ctx.setMainFileName(MainFileName);
403 // Package up features to be passed to target/subtarget
404 std::string FeaturesStr;
406 SubtargetFeatures Features;
407 for (unsigned i = 0; i != MAttrs.size(); ++i)
408 Features.AddFeature(MAttrs[i]);
409 FeaturesStr = Features.getString();
412 std::unique_ptr<tool_output_file> Out(GetOutputStream());
416 formatted_raw_ostream FOS(Out->os());
417 std::unique_ptr<MCStreamer> Str;
419 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
420 std::unique_ptr<MCSubtargetInfo> STI(
421 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
423 MCInstPrinter *IP = NULL;
424 if (FileType == OFT_AssemblyFile) {
426 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI, *MCII, *MRI, *STI);
427 MCCodeEmitter *CE = 0;
428 MCAsmBackend *MAB = 0;
430 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
431 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
433 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/ true,
435 /*useDwarfDirectory*/
436 true, IP, CE, MAB, ShowInst));
438 } else if (FileType == OFT_Null) {
439 Str.reset(createNullStreamer(Ctx));
441 assert(FileType == OFT_ObjectFile && "Invalid file type!");
442 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, *STI, Ctx);
443 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
444 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB,
445 FOS, CE, *STI, RelaxAll,
450 bool disassemble = false;
453 Res = AsLexInput(SrcMgr, *MAI, Out.get());
456 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, *MCII);
458 case AC_MDisassemble:
459 assert(IP && "Expected assembly output");
463 case AC_HDisassemble:
464 assert(IP && "Expected assembly output");
465 IP->setPrintImmHex(1);
473 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
474 *Buffer, SrcMgr, Out->os());
476 // Keep output if no errors.
477 if (Res == 0) Out->keep();