blob: 38c4861c480ae45eab91f35cac737b08f3fc3a5e [file] [log] [blame]
Eric Astor5f6dfa82020-01-20 09:18:25 -05001//===-- llvm-ml.cpp - masm-compatible assembler -----------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// A simple driver around MasmParser; based on llvm-mc.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Disassembler.h"
14
15#include "llvm/MC/MCAsmBackend.h"
16#include "llvm/MC/MCAsmInfo.h"
17#include "llvm/MC/MCCodeEmitter.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/MCObjectWriter.h"
23#include "llvm/MC/MCParser/AsmLexer.h"
24#include "llvm/MC/MCParser/MCTargetAsmParser.h"
25#include "llvm/MC/MCRegisterInfo.h"
26#include "llvm/MC/MCStreamer.h"
27#include "llvm/MC/MCSubtargetInfo.h"
28#include "llvm/MC/MCTargetOptionsCommandFlags.inc"
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/InitLLVM.h"
35#include "llvm/Support/MemoryBuffer.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"
40#include "llvm/Support/WithColor.h"
41
42using namespace llvm;
43
44static cl::opt<std::string>
45InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
46
47static cl::opt<std::string>
48OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
49 cl::init("-"));
50
51static cl::opt<bool>
52ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
53
54static cl::opt<bool>
55ShowInst("show-inst", cl::desc("Show internal instruction representation"));
56
57static cl::opt<bool>
58ShowInstOperands("show-inst-operands",
59 cl::desc("Show instructions operands as parsed"));
60
61static cl::opt<bool>
62OutputATTAsm("output-att-asm", cl::desc("Use ATT syntax for output printing"));
63
64static cl::opt<bool>
65PrintImmHex("print-imm-hex", cl::init(false),
66 cl::desc("Prefer hex format for immediate values"));
67
68static cl::opt<bool>
69PreserveComments("preserve-comments",
70 cl::desc("Preserve Comments in outputted assembly"));
71
72enum OutputFileType {
73 OFT_Null,
74 OFT_AssemblyFile,
75 OFT_ObjectFile
76};
77static cl::opt<OutputFileType>
78FileType("filetype", cl::init(OFT_ObjectFile),
79 cl::desc("Choose an output file type:"),
80 cl::values(
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")));
87
88static cl::list<std::string>
89IncludeDirs("I", cl::desc("Directory of include files"),
90 cl::value_desc("directory"), cl::Prefix);
91
92enum BitnessType {
93 m32,
94 m64,
95};
96cl::opt<BitnessType> Bitness(cl::desc("Choose bitness:"), cl::init(m64),
97 cl::values(clEnumVal(m32, "32-bit"),
98 clEnumVal(m64, "64-bit (default)")));
99
100static cl::opt<std::string>
101TripleName("triple", cl::desc("Target triple to assemble for, "
102 "see -version for available targets"));
103
104static cl::opt<std::string>
105DebugCompilationDir("fdebug-compilation-dir",
106 cl::desc("Specifies the debug info's compilation dir"));
107
108static cl::list<std::string>
109DebugPrefixMap("fdebug-prefix-map",
110 cl::desc("Map file source paths in debug info"),
111 cl::value_desc("= separated key-value pairs"));
112
113static cl::opt<std::string>
114MainFileName("main-file-name",
115 cl::desc("Specifies the name we should consider the input file"));
116
117static cl::opt<bool> SaveTempLabels("save-temp-labels",
118 cl::desc("Don't discard temporary labels"));
119
120enum ActionType {
121 AC_AsLex,
122 AC_Assemble,
123 AC_Disassemble,
124 AC_MDisassemble,
125};
126
127static cl::opt<ActionType>
128Action(cl::desc("Action to perform:"),
129 cl::init(AC_Assemble),
130 cl::values(clEnumValN(AC_AsLex, "as-lex",
131 "Lex tokens from a .asm file"),
132 clEnumValN(AC_Assemble, "assemble",
133 "Assemble a .asm file (default)"),
134 clEnumValN(AC_Disassemble, "disassemble",
135 "Disassemble strings of hex bytes"),
136 clEnumValN(AC_MDisassemble, "mdis",
137 "Marked up disassembly of strings of hex bytes")));
138
139static const Target *GetTarget(const char *ProgName) {
140 // Figure out the target triple.
141 if (TripleName.empty()) {
142 if (Bitness == m32)
143 TripleName = "i386-pc-windows";
144 else if (Bitness == m64)
145 TripleName = "x86_64-pc-windows";
146 }
147 Triple TheTriple(Triple::normalize(TripleName));
148
149 // Get the target specific parser.
150 std::string Error;
151 const Target *TheTarget = TargetRegistry::lookupTarget("", TheTriple, Error);
152 if (!TheTarget) {
153 WithColor::error(errs(), ProgName) << Error;
154 return nullptr;
155 }
156
157 // Update the triple name and return the found target.
158 TripleName = TheTriple.getTriple();
159 return TheTarget;
160}
161
162static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path) {
163 std::error_code EC;
164 auto Out = std::make_unique<ToolOutputFile>(Path, EC, sys::fs::F_None);
165 if (EC) {
166 WithColor::error() << EC.message() << '\n';
167 return nullptr;
168 }
169
170 return Out;
171}
172
173static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, raw_ostream &OS) {
174 AsmLexer Lexer(MAI);
175 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
176
177 bool Error = false;
178 while (Lexer.Lex().isNot(AsmToken::Eof)) {
179 Lexer.getTok().dump(OS);
180 OS << "\n";
181 if (Lexer.getTok().getKind() == AsmToken::Error)
182 Error = true;
183 }
184
185 return Error;
186}
187
188static int AssembleInput(const char *ProgName, const Target *TheTarget,
189 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
190 MCAsmInfo &MAI, MCSubtargetInfo &STI,
191 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
192 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
193 std::unique_ptr<MCTargetAsmParser> TAP(
194 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
195
196 if (!TAP) {
197 WithColor::error(errs(), ProgName)
198 << "this target does not support assembly parsing.\n";
199 return 1;
200 }
201
202 Parser->setShowParsedOperands(ShowInstOperands);
203 Parser->setTargetParser(*TAP);
204 Parser->getLexer().setLexMasmIntegers(true);
205
206 int Res = Parser->Run(/*NoInitialTextSection=*/true);
207
208 return Res;
209}
210
211int main(int argc, char **argv) {
212 InitLLVM X(argc, argv);
213
214 // Initialize targets and assembly printers/parsers.
215 llvm::InitializeAllTargetInfos();
216 llvm::InitializeAllTargetMCs();
217 llvm::InitializeAllAsmParsers();
218 llvm::InitializeAllDisassemblers();
219
220 // Register the target printer for --version.
221 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
222
223 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
224 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
225
226 const char *ProgName = argv[0];
227 const Target *TheTarget = GetTarget(ProgName);
228 if (!TheTarget)
229 return 1;
230 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
231 // construct the Triple object.
232 Triple TheTriple(TripleName);
233
234 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
235 MemoryBuffer::getFileOrSTDIN(InputFilename);
236 if (std::error_code EC = BufferPtr.getError()) {
237 WithColor::error(errs(), ProgName)
238 << InputFilename << ": " << EC.message() << '\n';
239 return 1;
240 }
241 MemoryBuffer *Buffer = BufferPtr->get();
242
243 SourceMgr SrcMgr;
244
245 // Tell SrcMgr about this buffer, which is what the parser will pick up.
246 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
247
248 // Record the location of the include directories so that the lexer can find
249 // it later.
250 SrcMgr.setIncludeDirs(IncludeDirs);
251
252 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
253 assert(MRI && "Unable to create target register info!");
254
255 std::unique_ptr<MCAsmInfo> MAI(
256 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
257 assert(MAI && "Unable to create target asm info!");
258
259 MAI->setPreserveAsmComments(PreserveComments);
260
261 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
262 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
263 MCObjectFileInfo MOFI;
264 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
265 MOFI.InitMCObjectFileInfo(TheTriple, /*PIC=*/false, Ctx,
266 /*LargeCodeModel=*/true);
267
268 if (SaveTempLabels)
269 Ctx.setAllowTemporaryLabels(false);
270
271 if (!DebugCompilationDir.empty()) {
272 Ctx.setCompilationDir(DebugCompilationDir);
273 } else {
274 // If no compilation dir is set, try to use the current directory.
275 SmallString<128> CWD;
276 if (!sys::fs::current_path(CWD))
277 Ctx.setCompilationDir(CWD);
278 }
279 for (const auto &Arg : DebugPrefixMap) {
280 const auto &KV = StringRef(Arg).split('=');
281 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
282 }
283 if (!MainFileName.empty())
284 Ctx.setMainFileName(MainFileName);
285
286 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename);
287 if (!Out)
288 return 1;
289
290 std::unique_ptr<buffer_ostream> BOS;
291 raw_pwrite_stream *OS = &Out->os();
292 std::unique_ptr<MCStreamer> Str;
293
294 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
295 std::unique_ptr<MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(
296 TripleName, /*CPU=*/"", /*Features=*/""));
297
298 MCInstPrinter *IP = nullptr;
299 if (FileType == OFT_AssemblyFile) {
300 const unsigned OutputAsmVariant = OutputATTAsm ? 0U // ATT dialect
301 : 1U; // Intel dialect
302 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
303 *MAI, *MCII, *MRI);
304
305 if (!IP) {
306 WithColor::error()
307 << "unable to create instruction printer for target triple '"
308 << TheTriple.normalize() << "' with "
309 << (OutputATTAsm ? "ATT" : "Intel") << " assembly variant.\n";
310 return 1;
311 }
312
313 // Set the display preference for hex vs. decimal immediates.
314 IP->setPrintImmHex(PrintImmHex);
315
316 // Set up the AsmStreamer.
317 std::unique_ptr<MCCodeEmitter> CE;
318 if (ShowEncoding)
319 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
320
321 std::unique_ptr<MCAsmBackend> MAB(
322 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
323 auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
324 Str.reset(
325 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
326 /*useDwarfDirectory*/ true, IP,
327 std::move(CE), std::move(MAB), ShowInst));
328
329 } else if (FileType == OFT_Null) {
330 Str.reset(TheTarget->createNullStreamer(Ctx));
331 } else {
332 assert(FileType == OFT_ObjectFile && "Invalid file type!");
333
334 // Don't waste memory on names of temp labels.
335 Ctx.setUseNamesOnTempLabels(false);
336
337 if (!Out->os().supportsSeeking()) {
338 BOS = std::make_unique<buffer_ostream>(Out->os());
339 OS = BOS.get();
340 }
341
342 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
343 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
344 Str.reset(TheTarget->createMCObjectStreamer(
345 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
346 MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(CE), *STI,
347 MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
348 /*DWARFMustBeAtTheEnd*/ false));
349 }
350
351 // Use Assembler information for parsing.
352 Str->setUseAssemblerInfoForParsing(true);
353
354 int Res = 1;
355 bool disassemble = false;
356 switch (Action) {
357 case AC_AsLex:
358 Res = AsLexInput(SrcMgr, *MAI, Out->os());
359 break;
360 case AC_Assemble:
361 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
362 *MCII, MCOptions);
363 break;
364 case AC_MDisassemble:
365 assert(IP && "Expected assembly output");
366 IP->setUseMarkup(1);
367 disassemble = true;
368 break;
369 case AC_Disassemble:
370 disassemble = true;
371 break;
372 }
373 if (disassemble)
374 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer,
375 SrcMgr, Out->os());
376
377 // Keep output if no errors.
378 if (Res == 0)
379 Out->keep();
380 return Res;
381}