xref: /llvm-project/llvm/tools/llvm-mc/llvm-mc.cpp (revision 699281cce7adec546a52d986928513f91272e723)
1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is a simple driver that allows command line hacking on machine
11 // code.
12 //
13 //===----------------------------------------------------------------------===//
14 
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"
42 
43 using namespace llvm;
44 
45 static cl::opt<std::string>
46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47 
48 static cl::opt<std::string>
49 OutputFilename("o", cl::desc("Output filename"),
50                cl::value_desc("filename"));
51 
52 static cl::opt<bool>
53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
54 
55 static cl::opt<bool>
56 CompressDebugSections("compress-debug-sections",
57                       cl::desc("Compress DWARF debug sections"));
58 
59 static cl::opt<bool>
60 ShowInst("show-inst", cl::desc("Show internal instruction representation"));
61 
62 static cl::opt<bool>
63 ShowInstOperands("show-inst-operands",
64                  cl::desc("Show instructions operands as parsed"));
65 
66 static cl::opt<unsigned>
67 OutputAsmVariant("output-asm-variant",
68                  cl::desc("Syntax variant to use for output printing"));
69 
70 static cl::opt<bool>
71 PrintImmHex("print-imm-hex", cl::init(false),
72             cl::desc("Prefer hex format for immediate values"));
73 
74 static cl::list<std::string>
75 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
76 
77 enum OutputFileType {
78   OFT_Null,
79   OFT_AssemblyFile,
80   OFT_ObjectFile
81 };
82 static cl::opt<OutputFileType>
83 FileType("filetype", cl::init(OFT_AssemblyFile),
84   cl::desc("Choose an output file type:"),
85   cl::values(
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"),
92        clEnumValEnd));
93 
94 static cl::list<std::string>
95 IncludeDirs("I", cl::desc("Directory of include files"),
96             cl::value_desc("directory"), cl::Prefix);
97 
98 static cl::opt<std::string>
99 ArchName("arch", cl::desc("Target arch to assemble for, "
100                           "see -version for available targets"));
101 
102 static cl::opt<std::string>
103 TripleName("triple", cl::desc("Target triple to assemble for, "
104                               "see -version for available targets"));
105 
106 static cl::opt<std::string>
107 MCPU("mcpu",
108      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
109      cl::value_desc("cpu-name"),
110      cl::init(""));
111 
112 static cl::list<std::string>
113 MAttrs("mattr",
114   cl::CommaSeparated,
115   cl::desc("Target specific attributes (-mattr=help for details)"),
116   cl::value_desc("a1,+a2,-a3,..."));
117 
118 static cl::opt<bool> PIC("position-independent",
119                          cl::desc("Position independent"), cl::init(false));
120 
121 static cl::opt<llvm::CodeModel::Model>
122 CMModel("code-model",
123         cl::desc("Choose code model"),
124         cl::init(CodeModel::Default),
125         cl::values(clEnumValN(CodeModel::Default, "default",
126                               "Target default code model"),
127                    clEnumValN(CodeModel::Small, "small",
128                               "Small code model"),
129                    clEnumValN(CodeModel::Kernel, "kernel",
130                               "Kernel code model"),
131                    clEnumValN(CodeModel::Medium, "medium",
132                               "Medium code model"),
133                    clEnumValN(CodeModel::Large, "large",
134                               "Large code model"),
135                    clEnumValEnd));
136 
137 static cl::opt<bool>
138 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
139                                    "in the text section"));
140 
141 static cl::opt<bool>
142 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
143                                   "source files"));
144 
145 static cl::opt<std::string>
146 DebugCompilationDir("fdebug-compilation-dir",
147                     cl::desc("Specifies the debug info's compilation dir"));
148 
149 static cl::opt<std::string>
150 MainFileName("main-file-name",
151              cl::desc("Specifies the name we should consider the input file"));
152 
153 static cl::opt<bool> SaveTempLabels("save-temp-labels",
154                                     cl::desc("Don't discard temporary labels"));
155 
156 static cl::opt<bool> NoExecStack("no-exec-stack",
157                                  cl::desc("File doesn't need an exec stack"));
158 
159 enum ActionType {
160   AC_AsLex,
161   AC_Assemble,
162   AC_Disassemble,
163   AC_MDisassemble,
164 };
165 
166 static cl::opt<ActionType>
167 Action(cl::desc("Action to perform:"),
168        cl::init(AC_Assemble),
169        cl::values(clEnumValN(AC_AsLex, "as-lex",
170                              "Lex tokens from a .s file"),
171                   clEnumValN(AC_Assemble, "assemble",
172                              "Assemble a .s file (default)"),
173                   clEnumValN(AC_Disassemble, "disassemble",
174                              "Disassemble strings of hex bytes"),
175                   clEnumValN(AC_MDisassemble, "mdis",
176                              "Marked up disassembly of strings of hex bytes"),
177                   clEnumValEnd));
178 
179 static const Target *GetTarget(const char *ProgName) {
180   // Figure out the target triple.
181   if (TripleName.empty())
182     TripleName = sys::getDefaultTargetTriple();
183   Triple TheTriple(Triple::normalize(TripleName));
184 
185   // Get the target specific parser.
186   std::string Error;
187   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
188                                                          Error);
189   if (!TheTarget) {
190     errs() << ProgName << ": " << Error;
191     return nullptr;
192   }
193 
194   // Update the triple name and return the found target.
195   TripleName = TheTriple.getTriple();
196   return TheTarget;
197 }
198 
199 static std::unique_ptr<tool_output_file> GetOutputStream() {
200   if (OutputFilename == "")
201     OutputFilename = "-";
202 
203   std::error_code EC;
204   auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
205                                                  sys::fs::F_None);
206   if (EC) {
207     errs() << EC.message() << '\n';
208     return nullptr;
209   }
210 
211   return Out;
212 }
213 
214 static std::string DwarfDebugFlags;
215 static void setDwarfDebugFlags(int argc, char **argv) {
216   if (!getenv("RC_DEBUG_OPTIONS"))
217     return;
218   for (int i = 0; i < argc; i++) {
219     DwarfDebugFlags += argv[i];
220     if (i + 1 < argc)
221       DwarfDebugFlags += " ";
222   }
223 }
224 
225 static std::string DwarfDebugProducer;
226 static void setDwarfDebugProducer() {
227   if(!getenv("DEBUG_PRODUCER"))
228     return;
229   DwarfDebugProducer += getenv("DEBUG_PRODUCER");
230 }
231 
232 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
233                       raw_ostream &OS) {
234 
235   AsmLexer Lexer(MAI);
236   Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
237 
238   bool Error = false;
239   while (Lexer.Lex().isNot(AsmToken::Eof)) {
240     AsmToken Tok = Lexer.getTok();
241 
242     switch (Tok.getKind()) {
243     default:
244       SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
245                           "unknown token");
246       Error = true;
247       break;
248     case AsmToken::Error:
249       Error = true; // error already printed.
250       break;
251     case AsmToken::Identifier:
252       OS << "identifier: " << Lexer.getTok().getString();
253       break;
254     case AsmToken::Integer:
255       OS << "int: " << Lexer.getTok().getString();
256       break;
257     case AsmToken::Real:
258       OS << "real: " << Lexer.getTok().getString();
259       break;
260     case AsmToken::String:
261       OS << "string: " << Lexer.getTok().getString();
262       break;
263 
264     case AsmToken::Amp:            OS << "Amp"; break;
265     case AsmToken::AmpAmp:         OS << "AmpAmp"; break;
266     case AsmToken::At:             OS << "At"; break;
267     case AsmToken::Caret:          OS << "Caret"; break;
268     case AsmToken::Colon:          OS << "Colon"; break;
269     case AsmToken::Comma:          OS << "Comma"; break;
270     case AsmToken::Dollar:         OS << "Dollar"; break;
271     case AsmToken::Dot:            OS << "Dot"; break;
272     case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
273     case AsmToken::Eof:            OS << "Eof"; break;
274     case AsmToken::Equal:          OS << "Equal"; break;
275     case AsmToken::EqualEqual:     OS << "EqualEqual"; break;
276     case AsmToken::Exclaim:        OS << "Exclaim"; break;
277     case AsmToken::ExclaimEqual:   OS << "ExclaimEqual"; break;
278     case AsmToken::Greater:        OS << "Greater"; break;
279     case AsmToken::GreaterEqual:   OS << "GreaterEqual"; break;
280     case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
281     case AsmToken::Hash:           OS << "Hash"; break;
282     case AsmToken::LBrac:          OS << "LBrac"; break;
283     case AsmToken::LCurly:         OS << "LCurly"; break;
284     case AsmToken::LParen:         OS << "LParen"; break;
285     case AsmToken::Less:           OS << "Less"; break;
286     case AsmToken::LessEqual:      OS << "LessEqual"; break;
287     case AsmToken::LessGreater:    OS << "LessGreater"; break;
288     case AsmToken::LessLess:       OS << "LessLess"; break;
289     case AsmToken::Minus:          OS << "Minus"; break;
290     case AsmToken::Percent:        OS << "Percent"; break;
291     case AsmToken::Pipe:           OS << "Pipe"; break;
292     case AsmToken::PipePipe:       OS << "PipePipe"; break;
293     case AsmToken::Plus:           OS << "Plus"; break;
294     case AsmToken::RBrac:          OS << "RBrac"; break;
295     case AsmToken::RCurly:         OS << "RCurly"; break;
296     case AsmToken::RParen:         OS << "RParen"; break;
297     case AsmToken::Slash:          OS << "Slash"; break;
298     case AsmToken::Star:           OS << "Star"; break;
299     case AsmToken::Tilde:          OS << "Tilde"; break;
300     }
301 
302     // Print the token string.
303     OS << " (\"";
304     OS.write_escaped(Tok.getString());
305     OS << "\")\n";
306   }
307 
308   return Error;
309 }
310 
311 static int fillCommandLineSymbols(MCAsmParser &Parser){
312   for(auto &I: DefineSymbol){
313     auto Pair = StringRef(I).split('=');
314     if(Pair.second.empty()){
315       errs() << "error: defsym must be of the form: sym=value: " << I;
316       return 1;
317     }
318     int64_t Value;
319     if(Pair.second.getAsInteger(0, Value)){
320       errs() << "error: Value is not an integer: " << Pair.second;
321       return 1;
322     }
323     auto &Context = Parser.getContext();
324     auto Symbol = Context.getOrCreateSymbol(Pair.first);
325     Parser.getStreamer().EmitAssignment(Symbol,
326                                         MCConstantExpr::create(Value, Context));
327   }
328   return 0;
329 }
330 
331 static int AssembleInput(const char *ProgName, const Target *TheTarget,
332                          SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
333                          MCAsmInfo &MAI, MCSubtargetInfo &STI,
334                          MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
335   std::unique_ptr<MCAsmParser> Parser(
336       createMCAsmParser(SrcMgr, Ctx, Str, MAI));
337   std::unique_ptr<MCTargetAsmParser> TAP(
338       TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
339 
340   if (!TAP) {
341     errs() << ProgName
342            << ": error: this target does not support assembly parsing.\n";
343     return 1;
344   }
345 
346   int SymbolResult = fillCommandLineSymbols(*Parser);
347   if(SymbolResult)
348     return SymbolResult;
349   Parser->setShowParsedOperands(ShowInstOperands);
350   Parser->setTargetParser(*TAP);
351 
352   int Res = Parser->Run(NoInitialTextSection);
353 
354   return Res;
355 }
356 
357 int main(int argc, char **argv) {
358   // Print a stack trace if we signal out.
359   sys::PrintStackTraceOnErrorSignal();
360   PrettyStackTraceProgram X(argc, argv);
361   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
362 
363   // Initialize targets and assembly printers/parsers.
364   llvm::InitializeAllTargetInfos();
365   llvm::InitializeAllTargetMCs();
366   llvm::InitializeAllAsmParsers();
367   llvm::InitializeAllDisassemblers();
368 
369   // Register the target printer for --version.
370   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
371 
372   cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
373   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
374   TripleName = Triple::normalize(TripleName);
375   setDwarfDebugFlags(argc, argv);
376 
377   setDwarfDebugProducer();
378 
379   const char *ProgName = argv[0];
380   const Target *TheTarget = GetTarget(ProgName);
381   if (!TheTarget)
382     return 1;
383   // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
384   // construct the Triple object.
385   Triple TheTriple(TripleName);
386 
387   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
388       MemoryBuffer::getFileOrSTDIN(InputFilename);
389   if (std::error_code EC = BufferPtr.getError()) {
390     errs() << InputFilename << ": " << EC.message() << '\n';
391     return 1;
392   }
393   MemoryBuffer *Buffer = BufferPtr->get();
394 
395   SourceMgr SrcMgr;
396 
397   // Tell SrcMgr about this buffer, which is what the parser will pick up.
398   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
399 
400   // Record the location of the include directories so that the lexer can find
401   // it later.
402   SrcMgr.setIncludeDirs(IncludeDirs);
403 
404   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
405   assert(MRI && "Unable to create target register info!");
406 
407   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
408   assert(MAI && "Unable to create target asm info!");
409 
410   if (CompressDebugSections) {
411     if (!zlib::isAvailable()) {
412       errs() << ProgName
413              << ": build tools with zlib to enable -compress-debug-sections";
414       return 1;
415     }
416     MAI->setCompressDebugSections(true);
417   }
418 
419   // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
420   // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
421   MCObjectFileInfo MOFI;
422   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
423   MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx);
424 
425   if (SaveTempLabels)
426     Ctx.setAllowTemporaryLabels(false);
427 
428   Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
429   // Default to 4 for dwarf version.
430   unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
431   if (DwarfVersion < 2 || DwarfVersion > 4) {
432     errs() << ProgName << ": Dwarf version " << DwarfVersion
433            << " is not supported." << '\n';
434     return 1;
435   }
436   Ctx.setDwarfVersion(DwarfVersion);
437   if (!DwarfDebugFlags.empty())
438     Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
439   if (!DwarfDebugProducer.empty())
440     Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
441   if (!DebugCompilationDir.empty())
442     Ctx.setCompilationDir(DebugCompilationDir);
443   else {
444     // If no compilation dir is set, try to use the current directory.
445     SmallString<128> CWD;
446     if (!sys::fs::current_path(CWD))
447       Ctx.setCompilationDir(CWD);
448   }
449   if (!MainFileName.empty())
450     Ctx.setMainFileName(MainFileName);
451 
452   // Package up features to be passed to target/subtarget
453   std::string FeaturesStr;
454   if (MAttrs.size()) {
455     SubtargetFeatures Features;
456     for (unsigned i = 0; i != MAttrs.size(); ++i)
457       Features.AddFeature(MAttrs[i]);
458     FeaturesStr = Features.getString();
459   }
460 
461   std::unique_ptr<tool_output_file> Out = GetOutputStream();
462   if (!Out)
463     return 1;
464 
465   std::unique_ptr<buffer_ostream> BOS;
466   raw_pwrite_stream *OS = &Out->os();
467   std::unique_ptr<MCStreamer> Str;
468 
469   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
470   std::unique_ptr<MCSubtargetInfo> STI(
471       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
472 
473   MCInstPrinter *IP = nullptr;
474   if (FileType == OFT_AssemblyFile) {
475     IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
476                                         *MAI, *MCII, *MRI);
477 
478     // Set the display preference for hex vs. decimal immediates.
479     IP->setPrintImmHex(PrintImmHex);
480 
481     // Set up the AsmStreamer.
482     MCCodeEmitter *CE = nullptr;
483     MCAsmBackend *MAB = nullptr;
484     if (ShowEncoding) {
485       CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
486       MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
487     }
488     auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
489     Str.reset(TheTarget->createAsmStreamer(
490         Ctx, std::move(FOut), /*asmverbose*/ true,
491         /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
492 
493   } else if (FileType == OFT_Null) {
494     Str.reset(TheTarget->createNullStreamer(Ctx));
495   } else {
496     assert(FileType == OFT_ObjectFile && "Invalid file type!");
497 
498     // Don't waste memory on names of temp labels.
499     Ctx.setUseNamesOnTempLabels(false);
500 
501     if (!Out->os().supportsSeeking()) {
502       BOS = make_unique<buffer_ostream>(Out->os());
503       OS = BOS.get();
504     }
505 
506     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
507     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
508     Str.reset(TheTarget->createMCObjectStreamer(
509         TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll,
510         MCOptions.MCIncrementalLinkerCompatible,
511         /*DWARFMustBeAtTheEnd*/ false));
512     if (NoExecStack)
513       Str->InitSections(true);
514   }
515 
516   int Res = 1;
517   bool disassemble = false;
518   switch (Action) {
519   case AC_AsLex:
520     Res = AsLexInput(SrcMgr, *MAI, Out->os());
521     break;
522   case AC_Assemble:
523     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
524                         *MCII, MCOptions);
525     break;
526   case AC_MDisassemble:
527     assert(IP && "Expected assembly output");
528     IP->setUseMarkup(1);
529     disassemble = true;
530     break;
531   case AC_Disassemble:
532     disassemble = true;
533     break;
534   }
535   if (disassemble)
536     Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
537                                     *Buffer, SrcMgr, Out->os());
538 
539   // Keep output if no errors.
540   if (Res == 0) Out->keep();
541   return Res;
542 }
543