blob: 6e6b748c3d29d7d44cd3f46c2afa06bc8397812e [file] [log] [blame]
Chris Lattnerc7ab9532009-06-18 23:05:21 +00001//===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===//
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"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/MC/MCContext.h"
Chris Lattner11b2fc92009-09-14 03:02:37 +000019#include "llvm/MC/MCInstPrinter.h"
Evan Chengc5e6d2f2011-07-11 03:57:24 +000020#include "llvm/MC/MCInstrInfo.h"
Evan Cheng76792992011-07-20 05:58:47 +000021#include "llvm/MC/MCObjectFileInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000022#include "llvm/MC/MCParser/AsmLexer.h"
Evan Cheng76792992011-07-20 05:58:47 +000023#include "llvm/MC/MCRegisterInfo.h"
Chris Lattner6c203912009-08-10 18:15:01 +000024#include "llvm/MC/MCSectionMachO.h"
Chris Lattner92ffdd12009-06-24 00:52:40 +000025#include "llvm/MC/MCStreamer.h"
Evan Cheng91111d22011-07-09 05:47:46 +000026#include "llvm/MC/MCSubtargetInfo.h"
Evan Cheng11424442011-07-26 00:24:13 +000027#include "llvm/MC/MCTargetAsmParser.h"
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +000028#include "llvm/MC/MCTargetOptionsCommandFlags.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000029#include "llvm/Support/CommandLine.h"
David Blaikie9c3857c2014-03-28 21:00:25 +000030#include "llvm/Support/Compression.h"
Dan Gohman268b0f42010-08-20 01:07:01 +000031#include "llvm/Support/FileUtilities.h"
Daniel Dunbar80d484e2009-08-14 03:48:55 +000032#include "llvm/Support/FormattedStream.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000033#include "llvm/Support/Host.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000034#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
36#include "llvm/Support/PrettyStackTrace.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000037#include "llvm/Support/Signals.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000039#include "llvm/Support/TargetRegistry.h"
40#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000041#include "llvm/Support/ToolOutputFile.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000042using 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"),
49 cl::value_desc("filename"));
50
Daniel Dunbard18dd1d2009-08-27 07:56:39 +000051static cl::opt<bool>
52ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
53
Daniel Dunbare3ee3322010-02-03 18:18:30 +000054static cl::opt<bool>
Eric Christopher23c6d1f2014-06-19 06:22:01 +000055CompressDebugSections("compress-debug-sections",
56 cl::desc("Compress DWARF debug sections"));
David Blaikie7400a972014-03-27 20:45:58 +000057
58static cl::opt<bool>
Daniel Dunbare3ee3322010-02-03 18:18:30 +000059ShowInst("show-inst", cl::desc("Show internal instruction representation"));
60
Daniel Dunbar2eca0252010-08-11 06:37:09 +000061static cl::opt<bool>
62ShowInstOperands("show-inst-operands",
63 cl::desc("Show instructions operands as parsed"));
64
Chris Lattner44790342009-09-20 07:17:49 +000065static cl::opt<unsigned>
66OutputAsmVariant("output-asm-variant",
67 cl::desc("Syntax variant to use for output printing"));
68
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +000069static cl::opt<bool>
70PrintImmHex("print-imm-hex", cl::init(false),
71 cl::desc("Prefer hex format for immediate values"));
72
Colin LeMahieu229a1e62015-06-07 01:46:24 +000073static cl::list<std::string>
74DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
75
Daniel Dunbar3016db32009-08-21 09:11:24 +000076enum OutputFileType {
Daniel Dunbarb09b8902010-03-23 23:47:12 +000077 OFT_Null,
Daniel Dunbar3016db32009-08-21 09:11:24 +000078 OFT_AssemblyFile,
79 OFT_ObjectFile
80};
81static cl::opt<OutputFileType>
82FileType("filetype", cl::init(OFT_AssemblyFile),
83 cl::desc("Choose an output file type:"),
84 cl::values(
85 clEnumValN(OFT_AssemblyFile, "asm",
86 "Emit an assembly ('.s') file"),
Daniel Dunbarb09b8902010-03-23 23:47:12 +000087 clEnumValN(OFT_Null, "null",
88 "Don't emit anything (for timing purposes)"),
Daniel Dunbar3016db32009-08-21 09:11:24 +000089 clEnumValN(OFT_ObjectFile, "obj",
90 "Emit a native object ('.o') file"),
91 clEnumValEnd));
92
Chris Lattnerd70e15b42009-06-21 05:22:37 +000093static cl::list<std::string>
94IncludeDirs("I", cl::desc("Directory of include files"),
95 cl::value_desc("directory"), cl::Prefix);
Chris Lattner8dd8a522009-06-18 23:04:45 +000096
Daniel Dunbar8c6bad22009-07-17 22:38:58 +000097static cl::opt<std::string>
Daniel Dunbar46892112010-03-13 02:20:38 +000098ArchName("arch", cl::desc("Target arch to assemble for, "
Bill Wendlinge3031142011-06-17 20:35:21 +000099 "see -version for available targets"));
Daniel Dunbar46892112010-03-13 02:20:38 +0000100
101static cl::opt<std::string>
Nick Lewyckyb2449092009-11-01 22:07:54 +0000102TripleName("triple", cl::desc("Target triple to assemble for, "
Daniel Dunbar46892112010-03-13 02:20:38 +0000103 "see -version for available targets"));
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000104
Jim Grosbach685b7732010-10-30 15:57:50 +0000105static cl::opt<std::string>
106MCPU("mcpu",
107 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
108 cl::value_desc("cpu-name"),
109 cl::init(""));
110
James Molloy4c493e82011-09-07 17:24:38 +0000111static cl::list<std::string>
112MAttrs("mattr",
113 cl::CommaSeparated,
114 cl::desc("Target specific attributes (-mattr=help for details)"),
115 cl::value_desc("a1,+a2,-a3,..."));
116
Evan Cheng2129f592011-07-19 06:37:02 +0000117static cl::opt<Reloc::Model>
118RelocModel("relocation-model",
119 cl::desc("Choose relocation model"),
120 cl::init(Reloc::Default),
121 cl::values(
122 clEnumValN(Reloc::Default, "default",
123 "Target default relocation model"),
124 clEnumValN(Reloc::Static, "static",
125 "Non-relocatable code"),
126 clEnumValN(Reloc::PIC_, "pic",
127 "Fully relocatable, position independent code"),
128 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic",
129 "Relocatable external references, non-relocatable code"),
130 clEnumValEnd));
131
Evan Chengefd9b422011-07-20 07:51:56 +0000132static cl::opt<llvm::CodeModel::Model>
133CMModel("code-model",
134 cl::desc("Choose code model"),
135 cl::init(CodeModel::Default),
136 cl::values(clEnumValN(CodeModel::Default, "default",
137 "Target default code model"),
138 clEnumValN(CodeModel::Small, "small",
139 "Small code model"),
140 clEnumValN(CodeModel::Kernel, "kernel",
141 "Kernel code model"),
142 clEnumValN(CodeModel::Medium, "medium",
143 "Medium code model"),
144 clEnumValN(CodeModel::Large, "large",
145 "Large code model"),
146 clEnumValEnd));
147
Daniel Dunbar322fec62010-03-13 02:20:57 +0000148static cl::opt<bool>
Bill Wendlinge3031142011-06-17 20:35:21 +0000149NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
150 "in the text section"));
Daniel Dunbar322fec62010-03-13 02:20:57 +0000151
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000152static cl::opt<bool>
Kevin Enderby6469fc22011-11-01 22:27:22 +0000153GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
154 "source files"));
155
Chandler Carruth10700aad2012-12-17 21:32:42 +0000156static cl::opt<std::string>
157DebugCompilationDir("fdebug-compilation-dir",
158 cl::desc("Specifies the debug info's compilation dir"));
159
Eric Christopher906da232012-12-18 00:31:01 +0000160static cl::opt<std::string>
161MainFileName("main-file-name",
162 cl::desc("Specifies the name we should consider the input file"));
163
Eric Christopherdc3e9c72014-05-21 00:20:01 +0000164static cl::opt<bool> SaveTempLabels("save-temp-labels",
165 cl::desc("Don't discard temporary labels"));
166
Eric Christopher472cee32014-05-21 21:05:09 +0000167static cl::opt<bool> NoExecStack("no-exec-stack",
168 cl::desc("File doesn't need an exec stack"));
169
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000170enum ActionType {
Chris Lattnerb0133452009-06-21 20:16:42 +0000171 AC_AsLex,
Sean Callanan7e645502009-12-17 01:49:59 +0000172 AC_Assemble,
Sean Callanan2d03d3a2010-04-12 19:43:00 +0000173 AC_Disassemble,
Kevin Enderby168ffb32012-12-05 18:13:19 +0000174 AC_MDisassemble,
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000175};
Chris Lattner8dd8a522009-06-18 23:04:45 +0000176
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000177static cl::opt<ActionType>
178Action(cl::desc("Action to perform:"),
Chris Lattnerb0133452009-06-21 20:16:42 +0000179 cl::init(AC_Assemble),
180 cl::values(clEnumValN(AC_AsLex, "as-lex",
181 "Lex tokens from a .s file"),
182 clEnumValN(AC_Assemble, "assemble",
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000183 "Assemble a .s file (default)"),
Sean Callanan7e645502009-12-17 01:49:59 +0000184 clEnumValN(AC_Disassemble, "disassemble",
185 "Disassemble strings of hex bytes"),
Kevin Enderby62183c42012-10-22 22:31:46 +0000186 clEnumValN(AC_MDisassemble, "mdis",
187 "Marked up disassembly of strings of hex bytes"),
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000188 clEnumValEnd));
189
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000190static const Target *GetTarget(const char *ProgName) {
Daniel Dunbar46892112010-03-13 02:20:38 +0000191 // Figure out the target triple.
192 if (TripleName.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000193 TripleName = sys::getDefaultTargetTriple();
Evan Chenge64f0e52011-07-26 19:02:16 +0000194 Triple TheTriple(Triple::normalize(TripleName));
195
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000196 // Get the target specific parser.
197 std::string Error;
198 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
199 Error);
200 if (!TheTarget) {
201 errs() << ProgName << ": " << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000202 return nullptr;
Daniel Dunbar46892112010-03-13 02:20:38 +0000203 }
204
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000205 // Update the triple name and return the found target.
Evan Chenge64f0e52011-07-26 19:02:16 +0000206 TripleName = TheTriple.getTriple();
207 return TheTarget;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000208}
209
Craig Topper8c8ee4d2014-12-12 07:52:16 +0000210static std::unique_ptr<tool_output_file> GetOutputStream() {
Dan Gohman268b0f42010-08-20 01:07:01 +0000211 if (OutputFilename == "")
212 OutputFilename = "-";
213
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000214 std::error_code EC;
Craig Topper8c8ee4d2014-12-12 07:52:16 +0000215 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
216 sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000217 if (EC) {
218 errs() << EC.message() << '\n';
Craig Toppere6cb63e2014-04-25 04:24:47 +0000219 return nullptr;
Dan Gohman268b0f42010-08-20 01:07:01 +0000220 }
Dan Gohmana2233f22010-09-01 14:20:41 +0000221
222 return Out;
Dan Gohman268b0f42010-08-20 01:07:01 +0000223}
224
Kevin Enderbye7739d42011-12-09 18:09:40 +0000225static std::string DwarfDebugFlags;
226static void setDwarfDebugFlags(int argc, char **argv) {
227 if (!getenv("RC_DEBUG_OPTIONS"))
228 return;
229 for (int i = 0; i < argc; i++) {
230 DwarfDebugFlags += argv[i];
231 if (i + 1 < argc)
232 DwarfDebugFlags += " ";
233 }
234}
235
Kevin Enderbye82ada62013-01-16 17:46:23 +0000236static std::string DwarfDebugProducer;
237static void setDwarfDebugProducer(void) {
238 if(!getenv("DEBUG_PRODUCER"))
239 return;
240 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
241}
242
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000243static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
Craig Topper4e05fc32014-12-12 07:52:19 +0000244 raw_ostream &OS) {
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000245
Richard Bartondef81b92012-04-16 11:32:10 +0000246 AsmLexer Lexer(MAI);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000247 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
Daniel Dunbar7a85f9c2010-07-18 18:31:28 +0000248
Chris Lattnerb0133452009-06-21 20:16:42 +0000249 bool Error = false;
Daniel Dunbarbc798162009-07-28 16:56:42 +0000250 while (Lexer.Lex().isNot(AsmToken::Eof)) {
Daniel Dunbar1601f552010-10-25 20:18:46 +0000251 AsmToken Tok = Lexer.getTok();
252
253 switch (Tok.getKind()) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000254 default:
Chris Lattner03b80a42011-10-16 05:43:57 +0000255 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning,
256 "unknown token");
Chris Lattnerb0133452009-06-21 20:16:42 +0000257 Error = true;
258 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000259 case AsmToken::Error:
Chris Lattnerb0133452009-06-21 20:16:42 +0000260 Error = true; // error already printed.
Chris Lattnerd0765612009-06-21 19:21:25 +0000261 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000262 case AsmToken::Identifier:
Craig Topper4e05fc32014-12-12 07:52:19 +0000263 OS << "identifier: " << Lexer.getTok().getString();
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000264 break;
Daniel Dunbarf2dcd772009-07-28 16:08:33 +0000265 case AsmToken::Integer:
Craig Topper4e05fc32014-12-12 07:52:19 +0000266 OS << "int: " << Lexer.getTok().getString();
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000267 break;
Daniel Dunbar3068a932010-09-24 01:59:31 +0000268 case AsmToken::Real:
Craig Topper4e05fc32014-12-12 07:52:19 +0000269 OS << "real: " << Lexer.getTok().getString();
Daniel Dunbar3068a932010-09-24 01:59:31 +0000270 break;
Daniel Dunbar25c2c622010-09-16 00:42:35 +0000271 case AsmToken::String:
Craig Topper4e05fc32014-12-12 07:52:19 +0000272 OS << "string: " << Lexer.getTok().getString();
Daniel Dunbar25c2c622010-09-16 00:42:35 +0000273 break;
Daniel Dunbar9c4809a2009-07-01 06:56:54 +0000274
Craig Topper4e05fc32014-12-12 07:52:19 +0000275 case AsmToken::Amp: OS << "Amp"; break;
276 case AsmToken::AmpAmp: OS << "AmpAmp"; break;
277 case AsmToken::At: OS << "At"; break;
278 case AsmToken::Caret: OS << "Caret"; break;
279 case AsmToken::Colon: OS << "Colon"; break;
280 case AsmToken::Comma: OS << "Comma"; break;
281 case AsmToken::Dollar: OS << "Dollar"; break;
282 case AsmToken::Dot: OS << "Dot"; break;
283 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break;
284 case AsmToken::Eof: OS << "Eof"; break;
285 case AsmToken::Equal: OS << "Equal"; break;
286 case AsmToken::EqualEqual: OS << "EqualEqual"; break;
287 case AsmToken::Exclaim: OS << "Exclaim"; break;
288 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break;
289 case AsmToken::Greater: OS << "Greater"; break;
290 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break;
291 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break;
292 case AsmToken::Hash: OS << "Hash"; break;
293 case AsmToken::LBrac: OS << "LBrac"; break;
294 case AsmToken::LCurly: OS << "LCurly"; break;
295 case AsmToken::LParen: OS << "LParen"; break;
296 case AsmToken::Less: OS << "Less"; break;
297 case AsmToken::LessEqual: OS << "LessEqual"; break;
298 case AsmToken::LessGreater: OS << "LessGreater"; break;
299 case AsmToken::LessLess: OS << "LessLess"; break;
300 case AsmToken::Minus: OS << "Minus"; break;
301 case AsmToken::Percent: OS << "Percent"; break;
302 case AsmToken::Pipe: OS << "Pipe"; break;
303 case AsmToken::PipePipe: OS << "PipePipe"; break;
304 case AsmToken::Plus: OS << "Plus"; break;
305 case AsmToken::RBrac: OS << "RBrac"; break;
306 case AsmToken::RCurly: OS << "RCurly"; break;
307 case AsmToken::RParen: OS << "RParen"; break;
308 case AsmToken::Slash: OS << "Slash"; break;
309 case AsmToken::Star: OS << "Star"; break;
310 case AsmToken::Tilde: OS << "Tilde"; break;
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000311 }
Daniel Dunbar1601f552010-10-25 20:18:46 +0000312
313 // Print the token string.
Craig Topper4e05fc32014-12-12 07:52:19 +0000314 OS << " (\"";
315 OS.write_escaped(Tok.getString());
316 OS << "\")\n";
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000317 }
Dan Gohman268b0f42010-08-20 01:07:01 +0000318
Chris Lattnerb0133452009-06-21 20:16:42 +0000319 return Error;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000320}
321
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000322static int fillCommandLineSymbols(MCAsmParser &Parser){
323 for(auto &I: DefineSymbol){
324 auto Pair = StringRef(I).split('=');
325 if(Pair.second.empty()){
326 errs() << "error: defsym must be of the form: sym=value: " << I;
327 return 1;
328 }
329 int64_t Value;
330 if(Pair.second.getAsInteger(0, Value)){
331 errs() << "error: Value is not an integer: " << Pair.second;
332 return 1;
333 }
334 auto &Context = Parser.getContext();
335 auto Symbol = Context.getOrCreateSymbol(Pair.first);
336 Parser.getStreamer().EmitAssignment(Symbol,
337 MCConstantExpr::create(Value, Context));
338 }
339 return 0;
340}
341
NAKAMURA Takumi89b8c172014-01-22 03:12:43 +0000342static int AssembleInput(const char *ProgName, const Target *TheTarget,
Richard Bartondef81b92012-04-16 11:32:10 +0000343 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000344 MCAsmInfo &MAI, MCSubtargetInfo &STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000345 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000346 std::unique_ptr<MCAsmParser> Parser(
347 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000348 std::unique_ptr<MCTargetAsmParser> TAP(
Eric Christopher4c5bff32014-06-19 06:22:08 +0000349 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
350
Richard Bartondef81b92012-04-16 11:32:10 +0000351 if (!TAP) {
352 errs() << ProgName
353 << ": error: this target does not support assembly parsing.\n";
354 return 1;
355 }
356
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000357 int SymbolResult = fillCommandLineSymbols(*Parser);
358 if(SymbolResult)
359 return SymbolResult;
Richard Bartondef81b92012-04-16 11:32:10 +0000360 Parser->setShowParsedOperands(ShowInstOperands);
Craig Topper4e05fc32014-12-12 07:52:19 +0000361 Parser->setTargetParser(*TAP);
Richard Bartondef81b92012-04-16 11:32:10 +0000362
363 int Res = Parser->Run(NoInitialTextSection);
364
365 return Res;
366}
367
368int main(int argc, char **argv) {
369 // Print a stack trace if we signal out.
370 sys::PrintStackTraceOnErrorSignal();
371 PrettyStackTraceProgram X(argc, argv);
372 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
373
374 // Initialize targets and assembly printers/parsers.
375 llvm::InitializeAllTargetInfos();
376 llvm::InitializeAllTargetMCs();
377 llvm::InitializeAllAsmParsers();
378 llvm::InitializeAllDisassemblers();
379
380 // Register the target printer for --version.
381 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
382
383 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
Eric Christopher4c5bff32014-06-19 06:22:08 +0000384 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Richard Bartondef81b92012-04-16 11:32:10 +0000385 TripleName = Triple::normalize(TripleName);
386 setDwarfDebugFlags(argc, argv);
387
Kevin Enderbye82ada62013-01-16 17:46:23 +0000388 setDwarfDebugProducer();
389
Richard Bartondef81b92012-04-16 11:32:10 +0000390 const char *ProgName = argv[0];
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000391 const Target *TheTarget = GetTarget(ProgName);
392 if (!TheTarget)
393 return 1;
Daniel Sandersc535d932015-06-16 09:57:38 +0000394 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
395 // construct the Triple object.
396 Triple TheTriple(TripleName);
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000397
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000398 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
399 MemoryBuffer::getFileOrSTDIN(InputFilename);
400 if (std::error_code EC = BufferPtr.getError()) {
Davide Italiano2c007d02015-09-14 17:10:01 +0000401 errs() << InputFilename << ": " << EC.message() << '\n';
Chris Lattnerb0133452009-06-21 20:16:42 +0000402 return 1;
403 }
David Blaikie1961f142014-08-21 20:44:56 +0000404 MemoryBuffer *Buffer = BufferPtr->get();
Jim Grosbach112a2de2011-05-09 20:05:25 +0000405
Chris Lattnerb0133452009-06-21 20:16:42 +0000406 SourceMgr SrcMgr;
Jim Grosbach112a2de2011-05-09 20:05:25 +0000407
Daniel Dunbar5c947db2009-08-19 16:25:53 +0000408 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie1961f142014-08-21 20:44:56 +0000409 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
Jim Grosbach112a2de2011-05-09 20:05:25 +0000410
Chris Lattnerb0133452009-06-21 20:16:42 +0000411 // Record the location of the include directories so that the lexer can find
412 // it later.
413 SrcMgr.setIncludeDirs(IncludeDirs);
Jim Grosbach112a2de2011-05-09 20:05:25 +0000414
Ahmed Charles56440fd2014-03-06 05:51:42 +0000415 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Evan Chengd60fa58b2011-07-18 20:57:22 +0000416 assert(MRI && "Unable to create target register info!");
417
Ahmed Charles56440fd2014-03-06 05:51:42 +0000418 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Rafael Espindola227144c2013-05-13 01:16:13 +0000419 assert(MAI && "Unable to create target asm info!");
420
David Blaikie9b620b42014-03-28 20:45:24 +0000421 if (CompressDebugSections) {
422 if (!zlib::isAvailable()) {
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000423 errs() << ProgName
424 << ": build tools with zlib to enable -compress-debug-sections";
David Blaikie9b620b42014-03-28 20:45:24 +0000425 return 1;
426 }
David Blaikie7400a972014-03-27 20:45:58 +0000427 MAI->setCompressDebugSections(true);
David Blaikie9b620b42014-03-28 20:45:24 +0000428 }
David Blaikie7400a972014-03-27 20:45:58 +0000429
Evan Cheng76792992011-07-20 05:58:47 +0000430 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
431 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Rafael Espindola75556bc2014-06-28 17:46:19 +0000432 MCObjectFileInfo MOFI;
433 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
Daniel Sanders8d8b13d2015-06-16 12:18:07 +0000434 MOFI.InitMCObjectFileInfo(TheTriple, RelocModel, CMModel, Ctx);
Evan Cheng76792992011-07-20 05:58:47 +0000435
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000436 if (SaveTempLabels)
437 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola0a017a62010-12-10 07:39:47 +0000438
Kevin Enderby6469fc22011-11-01 22:27:22 +0000439 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
Eric Christopher4c5bff32014-06-19 06:22:08 +0000440 // Default to 4 for dwarf version.
441 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
Oliver Stannard7eacbd52014-05-01 08:46:02 +0000442 if (DwarfVersion < 2 || DwarfVersion > 4) {
443 errs() << ProgName << ": Dwarf version " << DwarfVersion
444 << " is not supported." << '\n';
445 return 1;
446 }
447 Ctx.setDwarfVersion(DwarfVersion);
Chandler Carruth10700aad2012-12-17 21:32:42 +0000448 if (!DwarfDebugFlags.empty())
Kevin Enderbye7739d42011-12-09 18:09:40 +0000449 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
Kevin Enderbye82ada62013-01-16 17:46:23 +0000450 if (!DwarfDebugProducer.empty())
451 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
Chandler Carruth10700aad2012-12-17 21:32:42 +0000452 if (!DebugCompilationDir.empty())
453 Ctx.setCompilationDir(DebugCompilationDir);
Eric Christopher906da232012-12-18 00:31:01 +0000454 if (!MainFileName.empty())
455 Ctx.setMainFileName(MainFileName);
Kevin Enderby6469fc22011-11-01 22:27:22 +0000456
James Molloy4c493e82011-09-07 17:24:38 +0000457 // Package up features to be passed to target/subtarget
458 std::string FeaturesStr;
459 if (MAttrs.size()) {
460 SubtargetFeatures Features;
461 for (unsigned i = 0; i != MAttrs.size(); ++i)
462 Features.AddFeature(MAttrs[i]);
463 FeaturesStr = Features.getString();
464 }
465
Craig Topper8c8ee4d2014-12-12 07:52:16 +0000466 std::unique_ptr<tool_output_file> Out = GetOutputStream();
Dan Gohman268b0f42010-08-20 01:07:01 +0000467 if (!Out)
468 return 1;
469
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000470 std::unique_ptr<buffer_ostream> BOS;
471 raw_pwrite_stream *OS = &Out->os();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000472 std::unique_ptr<MCStreamer> Str;
Chris Lattnera61e93d2009-08-17 04:23:44 +0000473
Ahmed Charles56440fd2014-03-06 05:51:42 +0000474 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
475 std::unique_ptr<MCSubtargetInfo> STI(
476 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Evan Cheng91111d22011-07-09 05:47:46 +0000477
Craig Toppere6cb63e2014-04-25 04:24:47 +0000478 MCInstPrinter *IP = nullptr;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000479 if (FileType == OFT_AssemblyFile) {
Daniel Sanders50f17232015-09-15 16:17:27 +0000480 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
481 *MAI, *MCII, *MRI);
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000482
483 // Set the display preference for hex vs. decimal immediates.
484 IP->setPrintImmHex(PrintImmHex);
485
486 // Set up the AsmStreamer.
Craig Toppere6cb63e2014-04-25 04:24:47 +0000487 MCCodeEmitter *CE = nullptr;
488 MCAsmBackend *MAB = nullptr;
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000489 if (ShowEncoding) {
Eric Christopher0169e422015-03-10 22:03:14 +0000490 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Bill Wendling58e2d3d2013-09-09 02:37:14 +0000491 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
Daniel Dunbarecd0c8a2010-12-16 03:05:59 +0000492 }
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000493 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
Rafael Espindola5682ce22015-04-09 21:06:08 +0000494 Str.reset(TheTarget->createAsmStreamer(
495 Ctx, std::move(FOut), /*asmverbose*/ true,
496 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst));
Jim Grosbach78309c42011-12-05 23:20:14 +0000497
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000498 } else if (FileType == OFT_Null) {
Peter Collingbournef4498a42015-02-19 00:45:04 +0000499 Str.reset(TheTarget->createNullStreamer(Ctx));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000500 } else {
501 assert(FileType == OFT_ObjectFile && "Invalid file type!");
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000502
Rafael Espindolaf27fa2b2015-06-17 16:26:47 +0000503 // Don't waste memory on names of temp labels.
504 Ctx.setUseNamesOnTempLabels(false);
505
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000506 if (!Out->os().supportsSeeking()) {
507 BOS = make_unique<buffer_ostream>(Out->os());
508 OS = BOS.get();
509 }
510
Eric Christopher0169e422015-03-10 22:03:14 +0000511 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Bill Wendling58e2d3d2013-09-09 02:37:14 +0000512 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU);
Daniel Sanders50f17232015-09-15 16:17:27 +0000513 Str.reset(TheTarget->createMCObjectStreamer(TheTriple, Ctx, *MAB, *OS, CE,
514 *STI, RelaxAll,
Rafael Espindola36a15cb2015-03-20 20:00:01 +0000515 /*DWARFMustBeAtTheEnd*/ false));
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000516 if (NoExecStack)
517 Str->InitSections(true);
Daniel Dunbar3016db32009-08-21 09:11:24 +0000518 }
Daniel Dunbara10e5192009-06-24 23:30:00 +0000519
Richard Bartondef81b92012-04-16 11:32:10 +0000520 int Res = 1;
Kevin Enderby168ffb32012-12-05 18:13:19 +0000521 bool disassemble = false;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000522 switch (Action) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000523 case AC_AsLex:
Craig Topper4e05fc32014-12-12 07:52:19 +0000524 Res = AsLexInput(SrcMgr, *MAI, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000525 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000526 case AC_Assemble:
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000527 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000528 *MCII, MCOptions);
Richard Bartondef81b92012-04-16 11:32:10 +0000529 break;
Kevin Enderby62183c42012-10-22 22:31:46 +0000530 case AC_MDisassemble:
Eli Bendersky6f5d70e2013-02-26 23:04:17 +0000531 assert(IP && "Expected assembly output");
Kevin Enderby62183c42012-10-22 22:31:46 +0000532 IP->setUseMarkup(1);
Kevin Enderby168ffb32012-12-05 18:13:19 +0000533 disassemble = true;
534 break;
Sean Callanan7e645502009-12-17 01:49:59 +0000535 case AC_Disassemble:
Kevin Enderby168ffb32012-12-05 18:13:19 +0000536 disassemble = true;
Richard Bartondef81b92012-04-16 11:32:10 +0000537 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000538 }
Kevin Enderby168ffb32012-12-05 18:13:19 +0000539 if (disassemble)
540 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
541 *Buffer, SrcMgr, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000542
543 // Keep output if no errors.
544 if (Res == 0) Out->keep();
545 return Res;
Chris Lattner8dd8a522009-06-18 23:04:45 +0000546}