blob: 986fe3f686912aeb971d6941bdeef7b4556172f7 [file] [log] [blame]
Eugene Zelenkoffec81c2015-11-04 22:32:32 +00001//===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===//
Chris Lattner8dd8a522009-06-18 23:04:45 +00002//
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//
Chris Lattnerc7ab9532009-06-18 23:05:21 +000010// This utility is a simple driver that allows command line hacking on machine
11// code.
Chris Lattner8dd8a522009-06-18 23:04:45 +000012//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000015#include "Disassembler.h"
Evan Cheng5928e692011-07-25 23:24:55 +000016#include "llvm/MC/MCAsmBackend.h"
Craig Toppera6e377f2012-04-15 22:00:22 +000017#include "llvm/MC/MCAsmInfo.h"
Lang Hames2241ffa2017-10-11 23:34:47 +000018#include "llvm/MC/MCCodeEmitter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000019#include "llvm/MC/MCContext.h"
Chris Lattner11b2fc92009-09-14 03:02:37 +000020#include "llvm/MC/MCInstPrinter.h"
Evan Chengc5e6d2f2011-07-11 03:57:24 +000021#include "llvm/MC/MCInstrInfo.h"
Evan Cheng76792992011-07-20 05:58:47 +000022#include "llvm/MC/MCObjectFileInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000023#include "llvm/MC/MCParser/AsmLexer.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000024#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000025#include "llvm/MC/MCRegisterInfo.h"
Chris Lattner6c203912009-08-10 18:15:01 +000026#include "llvm/MC/MCSectionMachO.h"
Chris Lattner92ffdd12009-06-24 00:52:40 +000027#include "llvm/MC/MCStreamer.h"
Evan Cheng91111d22011-07-09 05:47:46 +000028#include "llvm/MC/MCSubtargetInfo.h"
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +000029#include "llvm/MC/MCTargetOptionsCommandFlags.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000030#include "llvm/Support/CommandLine.h"
David Blaikie9c3857c2014-03-28 21:00:25 +000031#include "llvm/Support/Compression.h"
Dan Gohman268b0f42010-08-20 01:07:01 +000032#include "llvm/Support/FileUtilities.h"
Daniel Dunbar80d484e2009-08-14 03:48:55 +000033#include "llvm/Support/FormattedStream.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000034#include "llvm/Support/Host.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000035#include "llvm/Support/ManagedStatic.h"
36#include "llvm/Support/MemoryBuffer.h"
37#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000038#include "llvm/Support/Signals.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000040#include "llvm/Support/TargetRegistry.h"
41#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000042#include "llvm/Support/ToolOutputFile.h"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000043
Chris Lattner8dd8a522009-06-18 23:04:45 +000044using namespace llvm;
45
46static cl::opt<std::string>
47InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
48
49static cl::opt<std::string>
50OutputFilename("o", cl::desc("Output filename"),
51 cl::value_desc("filename"));
52
Daniel Dunbard18dd1d2009-08-27 07:56:39 +000053static cl::opt<bool>
54ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
55
Rafael Espindolae021e852016-06-17 17:04:56 +000056static cl::opt<bool> RelaxELFRel(
57 "relax-relocations", cl::init(true),
58 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
Rafael Espindola9768d732016-05-29 01:11:00 +000059
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +000060static cl::opt<DebugCompressionType> CompressDebugSections(
61 "compress-debug-sections", cl::ValueOptional,
62 cl::init(DebugCompressionType::None),
63 cl::desc("Choose DWARF debug sections compression:"),
64 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
65 clEnumValN(DebugCompressionType::Z, "zlib",
66 "Use zlib compression"),
67 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
68 "Use zlib-gnu compression (deprecated)")));
David Blaikie7400a972014-03-27 20:45:58 +000069
70static cl::opt<bool>
Daniel Dunbare3ee3322010-02-03 18:18:30 +000071ShowInst("show-inst", cl::desc("Show internal instruction representation"));
72
Daniel Dunbar2eca0252010-08-11 06:37:09 +000073static cl::opt<bool>
74ShowInstOperands("show-inst-operands",
75 cl::desc("Show instructions operands as parsed"));
76
Chris Lattner44790342009-09-20 07:17:49 +000077static cl::opt<unsigned>
78OutputAsmVariant("output-asm-variant",
79 cl::desc("Syntax variant to use for output printing"));
80
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +000081static cl::opt<bool>
82PrintImmHex("print-imm-hex", cl::init(false),
83 cl::desc("Prefer hex format for immediate values"));
84
Colin LeMahieu229a1e62015-06-07 01:46:24 +000085static cl::list<std::string>
86DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
87
Nirav Dave53a72f42016-07-11 12:42:14 +000088static cl::opt<bool>
89 PreserveComments("preserve-comments",
90 cl::desc("Preserve Comments in outputted assembly"));
91
Daniel Dunbar3016db32009-08-21 09:11:24 +000092enum OutputFileType {
Daniel Dunbarb09b8902010-03-23 23:47:12 +000093 OFT_Null,
Daniel Dunbar3016db32009-08-21 09:11:24 +000094 OFT_AssemblyFile,
95 OFT_ObjectFile
96};
97static cl::opt<OutputFileType>
98FileType("filetype", cl::init(OFT_AssemblyFile),
99 cl::desc("Choose an output file type:"),
100 cl::values(
101 clEnumValN(OFT_AssemblyFile, "asm",
102 "Emit an assembly ('.s') file"),
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000103 clEnumValN(OFT_Null, "null",
104 "Don't emit anything (for timing purposes)"),
Daniel Dunbar3016db32009-08-21 09:11:24 +0000105 clEnumValN(OFT_ObjectFile, "obj",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000106 "Emit a native object ('.o') file")));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000107
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000108static cl::list<std::string>
109IncludeDirs("I", cl::desc("Directory of include files"),
110 cl::value_desc("directory"), cl::Prefix);
Chris Lattner8dd8a522009-06-18 23:04:45 +0000111
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000112static cl::opt<std::string>
Daniel Dunbar46892112010-03-13 02:20:38 +0000113ArchName("arch", cl::desc("Target arch to assemble for, "
Bill Wendlinge3031142011-06-17 20:35:21 +0000114 "see -version for available targets"));
Daniel Dunbar46892112010-03-13 02:20:38 +0000115
116static cl::opt<std::string>
Nick Lewyckyb2449092009-11-01 22:07:54 +0000117TripleName("triple", cl::desc("Target triple to assemble for, "
Daniel Dunbar46892112010-03-13 02:20:38 +0000118 "see -version for available targets"));
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000119
Jim Grosbach685b7732010-10-30 15:57:50 +0000120static cl::opt<std::string>
121MCPU("mcpu",
122 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
123 cl::value_desc("cpu-name"),
124 cl::init(""));
125
James Molloy4c493e82011-09-07 17:24:38 +0000126static cl::list<std::string>
127MAttrs("mattr",
128 cl::CommaSeparated,
129 cl::desc("Target specific attributes (-mattr=help for details)"),
130 cl::value_desc("a1,+a2,-a3,..."));
131
Rafael Espindola699281c2016-05-18 11:58:50 +0000132static cl::opt<bool> PIC("position-independent",
133 cl::desc("Position independent"), cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000134
Rafael Espindola9f929952017-08-02 20:32:26 +0000135static cl::opt<bool>
136 LargeCodeModel("large-code-model",
137 cl::desc("Create cfi directives that assume the code might "
138 "be more than 2gb away"));
Evan Chengefd9b422011-07-20 07:51:56 +0000139
Daniel Dunbar322fec62010-03-13 02:20:57 +0000140static cl::opt<bool>
Bill Wendlinge3031142011-06-17 20:35:21 +0000141NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
142 "in the text section"));
Daniel Dunbar322fec62010-03-13 02:20:57 +0000143
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000144static cl::opt<bool>
Kevin Enderby6469fc22011-11-01 22:27:22 +0000145GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
146 "source files"));
147
Chandler Carruth10700aad2012-12-17 21:32:42 +0000148static cl::opt<std::string>
149DebugCompilationDir("fdebug-compilation-dir",
150 cl::desc("Specifies the debug info's compilation dir"));
151
Eric Christopher906da232012-12-18 00:31:01 +0000152static cl::opt<std::string>
153MainFileName("main-file-name",
154 cl::desc("Specifies the name we should consider the input file"));
155
Eric Christopherdc3e9c72014-05-21 00:20:01 +0000156static cl::opt<bool> SaveTempLabels("save-temp-labels",
157 cl::desc("Don't discard temporary labels"));
158
Eric Christopher472cee32014-05-21 21:05:09 +0000159static cl::opt<bool> NoExecStack("no-exec-stack",
160 cl::desc("File doesn't need an exec stack"));
161
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000162enum ActionType {
Chris Lattnerb0133452009-06-21 20:16:42 +0000163 AC_AsLex,
Sean Callanan7e645502009-12-17 01:49:59 +0000164 AC_Assemble,
Sean Callanan2d03d3a2010-04-12 19:43:00 +0000165 AC_Disassemble,
Kevin Enderby168ffb32012-12-05 18:13:19 +0000166 AC_MDisassemble,
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000167};
Chris Lattner8dd8a522009-06-18 23:04:45 +0000168
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000169static cl::opt<ActionType>
170Action(cl::desc("Action to perform:"),
Chris Lattnerb0133452009-06-21 20:16:42 +0000171 cl::init(AC_Assemble),
172 cl::values(clEnumValN(AC_AsLex, "as-lex",
173 "Lex tokens from a .s file"),
174 clEnumValN(AC_Assemble, "assemble",
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000175 "Assemble a .s file (default)"),
Sean Callanan7e645502009-12-17 01:49:59 +0000176 clEnumValN(AC_Disassemble, "disassemble",
177 "Disassemble strings of hex bytes"),
Kevin Enderby62183c42012-10-22 22:31:46 +0000178 clEnumValN(AC_MDisassemble, "mdis",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000179 "Marked up disassembly of strings of hex bytes")));
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000180
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000181static const Target *GetTarget(const char *ProgName) {
Daniel Dunbar46892112010-03-13 02:20:38 +0000182 // Figure out the target triple.
183 if (TripleName.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000184 TripleName = sys::getDefaultTargetTriple();
Evan Chenge64f0e52011-07-26 19:02:16 +0000185 Triple TheTriple(Triple::normalize(TripleName));
186
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000187 // Get the target specific parser.
188 std::string Error;
189 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
190 Error);
191 if (!TheTarget) {
192 errs() << ProgName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000193 return nullptr;
Daniel Dunbar46892112010-03-13 02:20:38 +0000194 }
195
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000196 // Update the triple name and return the found target.
Evan Chenge64f0e52011-07-26 19:02:16 +0000197 TripleName = TheTriple.getTriple();
198 return TheTarget;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000199}
200
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000201static std::unique_ptr<ToolOutputFile> GetOutputStream() {
Dan Gohman268b0f42010-08-20 01:07:01 +0000202 if (OutputFilename == "")
203 OutputFilename = "-";
204
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000205 std::error_code EC;
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000206 auto Out =
207 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000208 if (EC) {
209 errs() << EC.message() << '\n';
Craig Toppere6cb63e2014-04-25 04:24:47 +0000210 return nullptr;
Dan Gohman268b0f42010-08-20 01:07:01 +0000211 }
Dan Gohmana2233f22010-09-01 14:20:41 +0000212
213 return Out;
Dan Gohman268b0f42010-08-20 01:07:01 +0000214}
215
Kevin Enderbye7739d42011-12-09 18:09:40 +0000216static std::string DwarfDebugFlags;
217static void setDwarfDebugFlags(int argc, char **argv) {
218 if (!getenv("RC_DEBUG_OPTIONS"))
219 return;
220 for (int i = 0; i < argc; i++) {
221 DwarfDebugFlags += argv[i];
222 if (i + 1 < argc)
223 DwarfDebugFlags += " ";
224 }
225}
226
Kevin Enderbye82ada62013-01-16 17:46:23 +0000227static std::string DwarfDebugProducer;
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000228static void setDwarfDebugProducer() {
Kevin Enderbye82ada62013-01-16 17:46:23 +0000229 if(!getenv("DEBUG_PRODUCER"))
230 return;
231 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
232}
233
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000234static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
Craig Topper4e05fc32014-12-12 07:52:19 +0000235 raw_ostream &OS) {
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000236
Richard Bartondef81b92012-04-16 11:32:10 +0000237 AsmLexer Lexer(MAI);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000238 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
Daniel Dunbar7a85f9c2010-07-18 18:31:28 +0000239
Chris Lattnerb0133452009-06-21 20:16:42 +0000240 bool Error = false;
Daniel Dunbarbc798162009-07-28 16:56:42 +0000241 while (Lexer.Lex().isNot(AsmToken::Eof)) {
Benjamin Kramer4ca41fd2016-06-12 17:30:47 +0000242 const AsmToken &Tok = Lexer.getTok();
Daniel Dunbar1601f552010-10-25 20:18:46 +0000243
244 switch (Tok.getKind()) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000245 default:
Chris Lattner03b80a42011-10-16 05:43:57 +0000246 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
247 "unknown token");
Chris Lattnerb0133452009-06-21 20:16:42 +0000248 Error = true;
249 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000250 case AsmToken::Error:
Chris Lattnerb0133452009-06-21 20:16:42 +0000251 Error = true; // error already printed.
Chris Lattnerd0765612009-06-21 19:21:25 +0000252 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000253 case AsmToken::Identifier:
Craig Topper4e05fc32014-12-12 07:52:19 +0000254 OS << "identifier: " << Lexer.getTok().getString();
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000255 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000256 case AsmToken::Integer:
Craig Topper4e05fc32014-12-12 07:52:19 +0000257 OS << "int: " << Lexer.getTok().getString();
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000258 break;
Daniel Dunbar3068a932010-09-24 01:59:31 +0000259 case AsmToken::Real:
Craig Topper4e05fc32014-12-12 07:52:19 +0000260 OS << "real: " << Lexer.getTok().getString();
Daniel Dunbar3068a932010-09-24 01:59:31 +0000261 break;
Daniel Dunbar25c2c622010-09-16 00:42:35 +0000262 case AsmToken::String:
Craig Topper4e05fc32014-12-12 07:52:19 +0000263 OS << "string: " << Lexer.getTok().getString();
Daniel Dunbar25c2c622010-09-16 00:42:35 +0000264 break;
Daniel Dunbar9c4809a2009-07-01 06:56:54 +0000265
Craig Topper4e05fc32014-12-12 07:52:19 +0000266 case AsmToken::Amp: OS << "Amp"; break;
267 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
268 case AsmToken::At: OS << "At"; break;
269 case AsmToken::Caret: OS << "Caret"; break;
270 case AsmToken::Colon: OS << "Colon"; break;
271 case AsmToken::Comma: OS << "Comma"; break;
272 case AsmToken::Dollar: OS << "Dollar"; break;
273 case AsmToken::Dot: OS << "Dot"; break;
274 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
275 case AsmToken::Eof: OS << "Eof"; break;
276 case AsmToken::Equal: OS << "Equal"; break;
277 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
278 case AsmToken::Exclaim: OS << "Exclaim"; break;
279 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
280 case AsmToken::Greater: OS << "Greater"; break;
281 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
282 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
283 case AsmToken::Hash: OS << "Hash"; break;
284 case AsmToken::LBrac: OS << "LBrac"; break;
285 case AsmToken::LCurly: OS << "LCurly"; break;
286 case AsmToken::LParen: OS << "LParen"; break;
287 case AsmToken::Less: OS << "Less"; break;
288 case AsmToken::LessEqual: OS << "LessEqual"; break;
289 case AsmToken::LessGreater: OS << "LessGreater"; break;
290 case AsmToken::LessLess: OS << "LessLess"; break;
291 case AsmToken::Minus: OS << "Minus"; break;
292 case AsmToken::Percent: OS << "Percent"; break;
293 case AsmToken::Pipe: OS << "Pipe"; break;
294 case AsmToken::PipePipe: OS << "PipePipe"; break;
295 case AsmToken::Plus: OS << "Plus"; break;
296 case AsmToken::RBrac: OS << "RBrac"; break;
297 case AsmToken::RCurly: OS << "RCurly"; break;
298 case AsmToken::RParen: OS << "RParen"; break;
299 case AsmToken::Slash: OS << "Slash"; break;
300 case AsmToken::Star: OS << "Star"; break;
301 case AsmToken::Tilde: OS << "Tilde"; break;
Daniel Sanders3feeb9c2016-08-08 11:50:25 +0000302 case AsmToken::PercentCall16:
303 OS << "PercentCall16";
304 break;
305 case AsmToken::PercentCall_Hi:
306 OS << "PercentCall_Hi";
307 break;
308 case AsmToken::PercentCall_Lo:
309 OS << "PercentCall_Lo";
310 break;
311 case AsmToken::PercentDtprel_Hi:
312 OS << "PercentDtprel_Hi";
313 break;
314 case AsmToken::PercentDtprel_Lo:
315 OS << "PercentDtprel_Lo";
316 break;
317 case AsmToken::PercentGot:
318 OS << "PercentGot";
319 break;
320 case AsmToken::PercentGot_Disp:
321 OS << "PercentGot_Disp";
322 break;
323 case AsmToken::PercentGot_Hi:
324 OS << "PercentGot_Hi";
325 break;
326 case AsmToken::PercentGot_Lo:
327 OS << "PercentGot_Lo";
328 break;
329 case AsmToken::PercentGot_Ofst:
330 OS << "PercentGot_Ofst";
331 break;
332 case AsmToken::PercentGot_Page:
333 OS << "PercentGot_Page";
334 break;
335 case AsmToken::PercentGottprel:
336 OS << "PercentGottprel";
337 break;
338 case AsmToken::PercentGp_Rel:
339 OS << "PercentGp_Rel";
340 break;
341 case AsmToken::PercentHi:
342 OS << "PercentHi";
343 break;
344 case AsmToken::PercentHigher:
345 OS << "PercentHigher";
346 break;
347 case AsmToken::PercentHighest:
348 OS << "PercentHighest";
349 break;
350 case AsmToken::PercentLo:
351 OS << "PercentLo";
352 break;
353 case AsmToken::PercentNeg:
354 OS << "PercentNeg";
355 break;
356 case AsmToken::PercentPcrel_Hi:
357 OS << "PercentPcrel_Hi";
358 break;
359 case AsmToken::PercentPcrel_Lo:
360 OS << "PercentPcrel_Lo";
361 break;
362 case AsmToken::PercentTlsgd:
363 OS << "PercentTlsgd";
364 break;
365 case AsmToken::PercentTlsldm:
366 OS << "PercentTlsldm";
367 break;
368 case AsmToken::PercentTprel_Hi:
369 OS << "PercentTprel_Hi";
370 break;
371 case AsmToken::PercentTprel_Lo:
372 OS << "PercentTprel_Lo";
373 break;
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000374 }
Daniel Dunbar1601f552010-10-25 20:18:46 +0000375
376 // Print the token string.
Craig Topper4e05fc32014-12-12 07:52:19 +0000377 OS << " (\"";
378 OS.write_escaped(Tok.getString());
379 OS << "\")\n";
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000380 }
Dan Gohman268b0f42010-08-20 01:07:01 +0000381
Chris Lattnerb0133452009-06-21 20:16:42 +0000382 return Error;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000383}
384
Mandeep Singh Grang32360072016-12-01 18:42:04 +0000385static int fillCommandLineSymbols(MCAsmParser &Parser) {
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000386 for (auto &I: DefineSymbol) {
387 auto Pair = StringRef(I).split('=');
388 auto Sym = Pair.first;
389 auto Val = Pair.second;
390
391 if (Sym.empty() || Val.empty()) {
392 errs() << "error: defsym must be of the form: sym=value: " << I << "\n";
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000393 return 1;
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000394 }
395 int64_t Value;
396 if (Val.getAsInteger(0, Value)) {
397 errs() << "error: Value is not an integer: " << Val << "\n";
398 return 1;
399 }
400 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
401 }
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000402 return 0;
403}
404
NAKAMURA Takumi89b8c172014-01-22 03:12:43 +0000405static int AssembleInput(const char *ProgName, const Target *TheTarget,
Richard Bartondef81b92012-04-16 11:32:10 +0000406 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000407 MCAsmInfo &MAI, MCSubtargetInfo &STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000408 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000409 std::unique_ptr<MCAsmParser> Parser(
410 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000411 std::unique_ptr<MCTargetAsmParser> TAP(
Eric Christopher4c5bff32014-06-19 06:22:08 +0000412 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
413
Richard Bartondef81b92012-04-16 11:32:10 +0000414 if (!TAP) {
415 errs() << ProgName
416 << ": error: this target does not support assembly parsing.\n";
417 return 1;
418 }
419
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000420 int SymbolResult = fillCommandLineSymbols(*Parser);
421 if(SymbolResult)
422 return SymbolResult;
Richard Bartondef81b92012-04-16 11:32:10 +0000423 Parser->setShowParsedOperands(ShowInstOperands);
Craig Topper4e05fc32014-12-12 07:52:19 +0000424 Parser->setTargetParser(*TAP);
Richard Bartondef81b92012-04-16 11:32:10 +0000425
426 int Res = Parser->Run(NoInitialTextSection);
427
428 return Res;
429}
430
431int main(int argc, char **argv) {
432 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000433 sys::PrintStackTraceOnErrorSignal(argv[0]);
Richard Bartondef81b92012-04-16 11:32:10 +0000434 PrettyStackTraceProgram X(argc, argv);
435 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
436
437 // Initialize targets and assembly printers/parsers.
438 llvm::InitializeAllTargetInfos();
439 llvm::InitializeAllTargetMCs();
440 llvm::InitializeAllAsmParsers();
441 llvm::InitializeAllDisassemblers();
442
443 // Register the target printer for --version.
444 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
445
446 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
Eric Christopher4c5bff32014-06-19 06:22:08 +0000447 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Richard Bartondef81b92012-04-16 11:32:10 +0000448 TripleName = Triple::normalize(TripleName);
449 setDwarfDebugFlags(argc, argv);
450
Kevin Enderbye82ada62013-01-16 17:46:23 +0000451 setDwarfDebugProducer();
452
Richard Bartondef81b92012-04-16 11:32:10 +0000453 const char *ProgName = argv[0];
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000454 const Target *TheTarget = GetTarget(ProgName);
455 if (!TheTarget)
456 return 1;
Daniel Sandersc535d932015-06-16 09:57:38 +0000457 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
458 // construct the Triple object.
459 Triple TheTriple(TripleName);
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000460
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000461 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
462 MemoryBuffer::getFileOrSTDIN(InputFilename);
463 if (std::error_code EC = BufferPtr.getError()) {
Davide Italiano2c007d02015-09-14 17:10:01 +0000464 errs() << InputFilename << ": " << EC.message() << '\n';
Chris Lattnerb0133452009-06-21 20:16:42 +0000465 return 1;
466 }
David Blaikie1961f142014-08-21 20:44:56 +0000467 MemoryBuffer *Buffer = BufferPtr->get();
Jim Grosbach112a2de2011-05-09 20:05:25 +0000468
Chris Lattnerb0133452009-06-21 20:16:42 +0000469 SourceMgr SrcMgr;
Jim Grosbach112a2de2011-05-09 20:05:25 +0000470
Daniel Dunbar5c947db2009-08-19 16:25:53 +0000471 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie1961f142014-08-21 20:44:56 +0000472 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
Jim Grosbach112a2de2011-05-09 20:05:25 +0000473
Chris Lattnerb0133452009-06-21 20:16:42 +0000474 // Record the location of the include directories so that the lexer can find
475 // it later.
476 SrcMgr.setIncludeDirs(IncludeDirs);
Jim Grosbach112a2de2011-05-09 20:05:25 +0000477
Ahmed Charles56440fd2014-03-06 05:51:42 +0000478 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Evan Chengd60fa58b2011-07-18 20:57:22 +0000479 assert(MRI && "Unable to create target register info!");
480
Ahmed Charles56440fd2014-03-06 05:51:42 +0000481 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Rafael Espindola227144c2013-05-13 01:16:13 +0000482 assert(MAI && "Unable to create target asm info!");
483
Rafael Espindola9768d732016-05-29 01:11:00 +0000484 MAI->setRelaxELFRelocations(RelaxELFRel);
485
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000486 if (CompressDebugSections != DebugCompressionType::None) {
David Blaikie9b620b42014-03-28 20:45:24 +0000487 if (!zlib::isAvailable()) {
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000488 errs() << ProgName
489 << ": build tools with zlib to enable -compress-debug-sections";
David Blaikie9b620b42014-03-28 20:45:24 +0000490 return 1;
491 }
George Rimarc91e38c2016-05-27 12:27:32 +0000492 MAI->setCompressDebugSections(CompressDebugSections);
David Blaikie9b620b42014-03-28 20:45:24 +0000493 }
Nirav Dave53a72f42016-07-11 12:42:14 +0000494 MAI->setPreserveAsmComments(PreserveComments);
David Blaikie7400a972014-03-27 20:45:58 +0000495
Evan Cheng76792992011-07-20 05:58:47 +0000496 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
497 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Rafael Espindola75556bc2014-06-28 17:46:19 +0000498 MCObjectFileInfo MOFI;
499 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
Rafael Espindola9f929952017-08-02 20:32:26 +0000500 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
Evan Cheng76792992011-07-20 05:58:47 +0000501
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000502 if (SaveTempLabels)
503 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola0a017a62010-12-10 07:39:47 +0000504
Kevin Enderby6469fc22011-11-01 22:27:22 +0000505 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
Eric Christopher4c5bff32014-06-19 06:22:08 +0000506 // Default to 4 for dwarf version.
507 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
Paul Robinsondccb4fe2017-02-28 23:40:46 +0000508 if (DwarfVersion < 2 || DwarfVersion > 5) {
Oliver Stannard7eacbd52014-05-01 08:46:02 +0000509 errs() << ProgName << ": Dwarf version " << DwarfVersion
510 << " is not supported." << '\n';
511 return 1;
512 }
513 Ctx.setDwarfVersion(DwarfVersion);
Chandler Carruth10700aad2012-12-17 21:32:42 +0000514 if (!DwarfDebugFlags.empty())
Kevin Enderbye7739d42011-12-09 18:09:40 +0000515 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
Kevin Enderbye82ada62013-01-16 17:46:23 +0000516 if (!DwarfDebugProducer.empty())
517 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
Chandler Carruth10700aad2012-12-17 21:32:42 +0000518 if (!DebugCompilationDir.empty())
519 Ctx.setCompilationDir(DebugCompilationDir);
Justin Bogner8809c402016-03-22 22:24:29 +0000520 else {
521 // If no compilation dir is set, try to use the current directory.
522 SmallString<128> CWD;
523 if (!sys::fs::current_path(CWD))
524 Ctx.setCompilationDir(CWD);
525 }
Eric Christopher906da232012-12-18 00:31:01 +0000526 if (!MainFileName.empty())
527 Ctx.setMainFileName(MainFileName);
Kevin Enderby6469fc22011-11-01 22:27:22 +0000528
James Molloy4c493e82011-09-07 17:24:38 +0000529 // Package up features to be passed to target/subtarget
530 std::string FeaturesStr;
531 if (MAttrs.size()) {
532 SubtargetFeatures Features;
533 for (unsigned i = 0; i != MAttrs.size(); ++i)
534 Features.AddFeature(MAttrs[i]);
535 FeaturesStr = Features.getString();
536 }
537
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000538 std::unique_ptr<ToolOutputFile> Out = GetOutputStream();
Dan Gohman268b0f42010-08-20 01:07:01 +0000539 if (!Out)
540 return 1;
541
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000542 std::unique_ptr<buffer_ostream> BOS;
543 raw_pwrite_stream *OS = &Out->os();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000544 std::unique_ptr<MCStreamer> Str;
Chris Lattnera61e93d2009-08-17 04:23:44 +0000545
Ahmed Charles56440fd2014-03-06 05:51:42 +0000546 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
547 std::unique_ptr<MCSubtargetInfo> STI(
548 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Evan Cheng91111d22011-07-09 05:47:46 +0000549
Craig Toppere6cb63e2014-04-25 04:24:47 +0000550 MCInstPrinter *IP = nullptr;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000551 if (FileType == OFT_AssemblyFile) {
Daniel Sanders50f17232015-09-15 16:17:27 +0000552 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
553 *MAI, *MCII, *MRI);
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000554
Nirav Davea9395af2016-10-31 18:36:31 +0000555 if (!IP) {
556 errs()
557 << "error: unable to create instruction printer for target triple '"
558 << TheTriple.normalize() << "' with assembly variant "
559 << OutputAsmVariant << ".\n";
560 return 1;
561 }
562
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000563 // Set the display preference for hex vs. decimal immediates.
564 IP->setPrintImmHex(PrintImmHex);
565
566 // Set up the AsmStreamer.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000567 MCCodeEmitter *CE = nullptr;
568 MCAsmBackend *MAB = nullptr;
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000569 if (ShowEncoding) {
Eric Christopher0169e422015-03-10 22:03:14 +0000570 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Joel Jones373d7d32016-07-25 17:18:28 +0000571 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU, MCOptions);
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000572 }
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000573 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
Rafael Espindola5682ce22015-04-09 21:06:08 +0000574 Str.reset(TheTarget->createAsmStreamer(
575 Ctx, std::move(FOut), /*asmverbose*/ true,
576 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
Jim Grosbach78309c42011-12-05 23:20:14 +0000577
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000578 } else if (FileType == OFT_Null) {
Peter Collingbournef4498a42015-02-19 00:45:04 +0000579 Str.reset(TheTarget->createNullStreamer(Ctx));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000580 } else {
581 assert(FileType == OFT_ObjectFile && "Invalid file type!");
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000582
Rafael Espindolaf27fa2b2015-06-17 16:26:47 +0000583 // Don't waste memory on names of temp labels.
584 Ctx.setUseNamesOnTempLabels(false);
585
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000586 if (!Out->os().supportsSeeking()) {
587 BOS = make_unique<buffer_ostream>(Out->os());
588 OS = BOS.get();
589 }
590
Eric Christopher0169e422015-03-10 22:03:14 +0000591 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Joel Jones373d7d32016-07-25 17:18:28 +0000592 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU,
593 MCOptions);
David Majnemer03e2cc32015-12-21 22:09:27 +0000594 Str.reset(TheTarget->createMCObjectStreamer(
Lang Hames2241ffa2017-10-11 23:34:47 +0000595 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), *OS,
596 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
597 MCOptions.MCIncrementalLinkerCompatible,
David Majnemer03e2cc32015-12-21 22:09:27 +0000598 /*DWARFMustBeAtTheEnd*/ false));
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000599 if (NoExecStack)
600 Str->InitSections(true);
Daniel Dunbar3016db32009-08-21 09:11:24 +0000601 }
Daniel Dunbara10e5192009-06-24 23:30:00 +0000602
Richard Bartondef81b92012-04-16 11:32:10 +0000603 int Res = 1;
Kevin Enderby168ffb32012-12-05 18:13:19 +0000604 bool disassemble = false;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000605 switch (Action) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000606 case AC_AsLex:
Craig Topper4e05fc32014-12-12 07:52:19 +0000607 Res = AsLexInput(SrcMgr, *MAI, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000608 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000609 case AC_Assemble:
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000610 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000611 *MCII, MCOptions);
Richard Bartondef81b92012-04-16 11:32:10 +0000612 break;
Kevin Enderby62183c42012-10-22 22:31:46 +0000613 case AC_MDisassemble:
Eli Bendersky6f5d70e2013-02-26 23:04:17 +0000614 assert(IP && "Expected assembly output");
Kevin Enderby62183c42012-10-22 22:31:46 +0000615 IP->setUseMarkup(1);
Kevin Enderby168ffb32012-12-05 18:13:19 +0000616 disassemble = true;
617 break;
Sean Callanan7e645502009-12-17 01:49:59 +0000618 case AC_Disassemble:
Kevin Enderby168ffb32012-12-05 18:13:19 +0000619 disassemble = true;
Richard Bartondef81b92012-04-16 11:32:10 +0000620 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000621 }
Kevin Enderby168ffb32012-12-05 18:13:19 +0000622 if (disassemble)
623 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
624 *Buffer, SrcMgr, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000625
626 // Keep output if no errors.
627 if (Res == 0) Out->keep();
628 return Res;
Chris Lattner8dd8a522009-06-18 23:04:45 +0000629}