1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
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/MCParser/MCTargetAsmParser.h"
24 #include "llvm/MC/MCRegisterInfo.h"
25 #include "llvm/MC/MCSectionMachO.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.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"
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50 cl::value_desc("filename"));
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55 static cl::opt<DebugCompressionType>
56 CompressDebugSections("compress-debug-sections", cl::ValueOptional,
57 cl::init(DebugCompressionType::DCT_None),
58 cl::desc("Choose DWARF debug sections compression:"),
60 clEnumValN(DebugCompressionType::DCT_None, "none",
62 clEnumValN(DebugCompressionType::DCT_Zlib, "zlib",
63 "Use zlib compression"),
64 clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu",
65 "Use zlib-gnu compression (depricated)"),
69 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
72 ShowInstOperands("show-inst-operands",
73 cl::desc("Show instructions operands as parsed"));
75 static cl::opt<unsigned>
76 OutputAsmVariant("output-asm-variant",
77 cl::desc("Syntax variant to use for output printing"));
80 PrintImmHex("print-imm-hex", cl::init(false),
81 cl::desc("Prefer hex format for immediate values"));
83 static cl::list<std::string>
84 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
91 static cl::opt<OutputFileType>
92 FileType("filetype", cl::init(OFT_AssemblyFile),
93 cl::desc("Choose an output file type:"),
95 clEnumValN(OFT_AssemblyFile, "asm",
96 "Emit an assembly ('.s') file"),
97 clEnumValN(OFT_Null, "null",
98 "Don't emit anything (for timing purposes)"),
99 clEnumValN(OFT_ObjectFile, "obj",
100 "Emit a native object ('.o') file"),
103 static cl::list<std::string>
104 IncludeDirs("I", cl::desc("Directory of include files"),
105 cl::value_desc("directory"), cl::Prefix);
107 static cl::opt<std::string>
108 ArchName("arch", cl::desc("Target arch to assemble for, "
109 "see -version for available targets"));
111 static cl::opt<std::string>
112 TripleName("triple", cl::desc("Target triple to assemble for, "
113 "see -version for available targets"));
115 static cl::opt<std::string>
117 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
118 cl::value_desc("cpu-name"),
121 static cl::list<std::string>
124 cl::desc("Target specific attributes (-mattr=help for details)"),
125 cl::value_desc("a1,+a2,-a3,..."));
127 static cl::opt<bool> PIC("position-independent",
128 cl::desc("Position independent"), cl::init(false));
130 static cl::opt<llvm::CodeModel::Model>
131 CMModel("code-model",
132 cl::desc("Choose code model"),
133 cl::init(CodeModel::Default),
134 cl::values(clEnumValN(CodeModel::Default, "default",
135 "Target default code model"),
136 clEnumValN(CodeModel::Small, "small",
138 clEnumValN(CodeModel::Kernel, "kernel",
139 "Kernel code model"),
140 clEnumValN(CodeModel::Medium, "medium",
141 "Medium code model"),
142 clEnumValN(CodeModel::Large, "large",
147 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
148 "in the text section"));
151 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
154 static cl::opt<std::string>
155 DebugCompilationDir("fdebug-compilation-dir",
156 cl::desc("Specifies the debug info's compilation dir"));
158 static cl::opt<std::string>
159 MainFileName("main-file-name",
160 cl::desc("Specifies the name we should consider the input file"));
162 static cl::opt<bool> SaveTempLabels("save-temp-labels",
163 cl::desc("Don't discard temporary labels"));
165 static cl::opt<bool> NoExecStack("no-exec-stack",
166 cl::desc("File doesn't need an exec stack"));
175 static cl::opt<ActionType>
176 Action(cl::desc("Action to perform:"),
177 cl::init(AC_Assemble),
178 cl::values(clEnumValN(AC_AsLex, "as-lex",
179 "Lex tokens from a .s file"),
180 clEnumValN(AC_Assemble, "assemble",
181 "Assemble a .s file (default)"),
182 clEnumValN(AC_Disassemble, "disassemble",
183 "Disassemble strings of hex bytes"),
184 clEnumValN(AC_MDisassemble, "mdis",
185 "Marked up disassembly of strings of hex bytes"),
188 static const Target *GetTarget(const char *ProgName) {
189 // Figure out the target triple.
190 if (TripleName.empty())
191 TripleName = sys::getDefaultTargetTriple();
192 Triple TheTriple(Triple::normalize(TripleName));
194 // Get the target specific parser.
196 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
199 errs() << ProgName << ": " << Error;
203 // Update the triple name and return the found target.
204 TripleName = TheTriple.getTriple();
208 static std::unique_ptr<tool_output_file> GetOutputStream() {
209 if (OutputFilename == "")
210 OutputFilename = "-";
213 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
216 errs() << EC.message() << '\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 std::string DwarfDebugProducer;
235 static void setDwarfDebugProducer() {
236 if(!getenv("DEBUG_PRODUCER"))
238 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
241 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
245 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
248 while (Lexer.Lex().isNot(AsmToken::Eof)) {
249 AsmToken Tok = Lexer.getTok();
251 switch (Tok.getKind()) {
253 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
257 case AsmToken::Error:
258 Error = true; // error already printed.
260 case AsmToken::Identifier:
261 OS << "identifier: " << Lexer.getTok().getString();
263 case AsmToken::Integer:
264 OS << "int: " << Lexer.getTok().getString();
267 OS << "real: " << Lexer.getTok().getString();
269 case AsmToken::String:
270 OS << "string: " << Lexer.getTok().getString();
273 case AsmToken::Amp: OS << "Amp"; break;
274 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
275 case AsmToken::At: OS << "At"; break;
276 case AsmToken::Caret: OS << "Caret"; break;
277 case AsmToken::Colon: OS << "Colon"; break;
278 case AsmToken::Comma: OS << "Comma"; break;
279 case AsmToken::Dollar: OS << "Dollar"; break;
280 case AsmToken::Dot: OS << "Dot"; break;
281 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
282 case AsmToken::Eof: OS << "Eof"; break;
283 case AsmToken::Equal: OS << "Equal"; break;
284 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
285 case AsmToken::Exclaim: OS << "Exclaim"; break;
286 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
287 case AsmToken::Greater: OS << "Greater"; break;
288 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
289 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
290 case AsmToken::Hash: OS << "Hash"; break;
291 case AsmToken::LBrac: OS << "LBrac"; break;
292 case AsmToken::LCurly: OS << "LCurly"; break;
293 case AsmToken::LParen: OS << "LParen"; break;
294 case AsmToken::Less: OS << "Less"; break;
295 case AsmToken::LessEqual: OS << "LessEqual"; break;
296 case AsmToken::LessGreater: OS << "LessGreater"; break;
297 case AsmToken::LessLess: OS << "LessLess"; break;
298 case AsmToken::Minus: OS << "Minus"; break;
299 case AsmToken::Percent: OS << "Percent"; break;
300 case AsmToken::Pipe: OS << "Pipe"; break;
301 case AsmToken::PipePipe: OS << "PipePipe"; break;
302 case AsmToken::Plus: OS << "Plus"; break;
303 case AsmToken::RBrac: OS << "RBrac"; break;
304 case AsmToken::RCurly: OS << "RCurly"; break;
305 case AsmToken::RParen: OS << "RParen"; break;
306 case AsmToken::Slash: OS << "Slash"; break;
307 case AsmToken::Star: OS << "Star"; break;
308 case AsmToken::Tilde: OS << "Tilde"; break;
311 // Print the token string.
313 OS.write_escaped(Tok.getString());
320 static int fillCommandLineSymbols(MCAsmParser &Parser){
321 for(auto &I: DefineSymbol){
322 auto Pair = StringRef(I).split('=');
323 if(Pair.second.empty()){
324 errs() << "error: defsym must be of the form: sym=value: " << I;
328 if(Pair.second.getAsInteger(0, Value)){
329 errs() << "error: Value is not an integer: " << Pair.second;
332 auto &Context = Parser.getContext();
333 auto Symbol = Context.getOrCreateSymbol(Pair.first);
334 Parser.getStreamer().EmitAssignment(Symbol,
335 MCConstantExpr::create(Value, Context));
340 static int AssembleInput(const char *ProgName, const Target *TheTarget,
341 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
342 MCAsmInfo &MAI, MCSubtargetInfo &STI,
343 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
344 std::unique_ptr<MCAsmParser> Parser(
345 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
346 std::unique_ptr<MCTargetAsmParser> TAP(
347 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
351 << ": error: this target does not support assembly parsing.\n";
355 int SymbolResult = fillCommandLineSymbols(*Parser);
358 Parser->setShowParsedOperands(ShowInstOperands);
359 Parser->setTargetParser(*TAP);
361 int Res = Parser->Run(NoInitialTextSection);
366 int main(int argc, char **argv) {
367 // Print a stack trace if we signal out.
368 sys::PrintStackTraceOnErrorSignal();
369 PrettyStackTraceProgram X(argc, argv);
370 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
372 // Initialize targets and assembly printers/parsers.
373 llvm::InitializeAllTargetInfos();
374 llvm::InitializeAllTargetMCs();
375 llvm::InitializeAllAsmParsers();
376 llvm::InitializeAllDisassemblers();
378 // Register the target printer for --version.
379 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
381 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
382 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
383 TripleName = Triple::normalize(TripleName);
384 setDwarfDebugFlags(argc, argv);
386 setDwarfDebugProducer();
388 const char *ProgName = argv[0];
389 const Target *TheTarget = GetTarget(ProgName);
392 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
393 // construct the Triple object.
394 Triple TheTriple(TripleName);
396 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
397 MemoryBuffer::getFileOrSTDIN(InputFilename);
398 if (std::error_code EC = BufferPtr.getError()) {
399 errs() << InputFilename << ": " << EC.message() << '\n';
402 MemoryBuffer *Buffer = BufferPtr->get();
406 // Tell SrcMgr about this buffer, which is what the parser will pick up.
407 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
409 // Record the location of the include directories so that the lexer can find
411 SrcMgr.setIncludeDirs(IncludeDirs);
413 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
414 assert(MRI && "Unable to create target register info!");
416 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
417 assert(MAI && "Unable to create target asm info!");
419 if (CompressDebugSections != DebugCompressionType::DCT_None) {
420 if (!zlib::isAvailable()) {
422 << ": build tools with zlib to enable -compress-debug-sections";
425 MAI->setCompressDebugSections(CompressDebugSections);
428 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
429 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
430 MCObjectFileInfo MOFI;
431 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
432 MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
435 Ctx.setAllowTemporaryLabels(false);
437 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
438 // Default to 4 for dwarf version.
439 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
440 if (DwarfVersion < 2 || DwarfVersion > 4) {
441 errs() << ProgName << ": Dwarf version " << DwarfVersion
442 << " is not supported." << '\n';
445 Ctx.setDwarfVersion(DwarfVersion);
446 if (!DwarfDebugFlags.empty())
447 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
448 if (!DwarfDebugProducer.empty())
449 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
450 if (!DebugCompilationDir.empty())
451 Ctx.setCompilationDir(DebugCompilationDir);
453 // If no compilation dir is set, try to use the current directory.
454 SmallString<128> CWD;
455 if (!sys::fs::current_path(CWD))
456 Ctx.setCompilationDir(CWD);
458 if (!MainFileName.empty())
459 Ctx.setMainFileName(MainFileName);
461 // Package up features to be passed to target/subtarget
462 std::string FeaturesStr;
464 SubtargetFeatures Features;
465 for (unsigned i = 0; i != MAttrs.size(); ++i)
466 Features.AddFeature(MAttrs[i]);
467 FeaturesStr = Features.getString();
470 std::unique_ptr<tool_output_file> Out = GetOutputStream();
474 std::unique_ptr<buffer_ostream> BOS;
475 raw_pwrite_stream *OS = &Out->os();
476 std::unique_ptr<MCStreamer> Str;
478 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
479 std::unique_ptr<MCSubtargetInfo> STI(
480 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
482 MCInstPrinter *IP = nullptr;
483 if (FileType == OFT_AssemblyFile) {
484 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
487 // Set the display preference for hex vs. decimal immediates.
488 IP->setPrintImmHex(PrintImmHex);
490 // Set up the AsmStreamer.
491 MCCodeEmitter *CE = nullptr;
492 MCAsmBackend *MAB = nullptr;
494 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
495 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
497 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
498 Str.reset(TheTarget->createAsmStreamer(
499 Ctx, std::move(FOut), /*asmverbose*/ true,
500 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
502 } else if (FileType == OFT_Null) {
503 Str.reset(TheTarget->createNullStreamer(Ctx));
505 assert(FileType == OFT_ObjectFile && "Invalid file type!");
507 // Don't waste memory on names of temp labels.
508 Ctx.setUseNamesOnTempLabels(false);
510 if (!Out->os().supportsSeeking()) {
511 BOS = make_unique<buffer_ostream>(Out->os());
515 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
516 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
517 Str.reset(TheTarget->createMCObjectStreamer(
518 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
519 MCOptions.MCIncrementalLinkerCompatible,
520 /*DWARFMustBeAtTheEnd*/ false));
522 Str->InitSections(true);
526 bool disassemble = false;
529 Res = AsLexInput(SrcMgr, *MAI, Out->os());
532 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
535 case AC_MDisassemble:
536 assert(IP && "Expected assembly output");
545 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
546 *Buffer, SrcMgr, Out->os());
548 // Keep output if no errors.
549 if (Res == 0) Out->keep();