blob: 0263c866f77230137771f55d73c8aeabb3a4d876 [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"
Peter Collingbournef7b81db2018-05-18 18:26:45 +000023#include "llvm/MC/MCObjectWriter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000024#include "llvm/MC/MCParser/AsmLexer.h"
Benjamin Kramerb3e8a6d2016-01-27 10:01:28 +000025#include "llvm/MC/MCParser/MCTargetAsmParser.h"
Evan Cheng76792992011-07-20 05:58:47 +000026#include "llvm/MC/MCRegisterInfo.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"
David Blaikie4333f972018-04-11 18:49:37 +000029#include "llvm/MC/MCTargetOptionsCommandFlags.inc"
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"
Rui Ueyama197194b2018-04-13 18:26:06 +000035#include "llvm/Support/InitLLVM.h"
Chris Lattner8dd8a522009-06-18 23:04:45 +000036#include "llvm/Support/MemoryBuffer.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Support/SourceMgr.h"
Evan Cheng2bb40352011-08-24 18:08:43 +000038#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Support/TargetSelect.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000040#include "llvm/Support/ToolOutputFile.h"
Jonas Devliegherec976aa72018-04-22 08:01:35 +000041#include "llvm/Support/WithColor.h"
Eugene Zelenkoffec81c2015-11-04 22:32:32 +000042
Chris Lattner8dd8a522009-06-18 23:04:45 +000043using namespace llvm;
44
45static cl::opt<std::string>
46InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
47
Peter Collingbourne63062d92018-05-21 19:44:54 +000048static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
49 cl::value_desc("filename"),
50 cl::init("-"));
51
52static cl::opt<std::string> SplitDwarfFile("split-dwarf-file",
53 cl::desc("DWO output filename"),
54 cl::value_desc("filename"));
Chris Lattner8dd8a522009-06-18 23:04:45 +000055
Daniel Dunbard18dd1d2009-08-27 07:56:39 +000056static cl::opt<bool>
57ShowEncoding("show-encoding", cl::desc("Show instruction encodings"));
58
Rafael Espindolae021e852016-06-17 17:04:56 +000059static cl::opt<bool> RelaxELFRel(
60 "relax-relocations", cl::init(true),
61 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL"));
Rafael Espindola9768d732016-05-29 01:11:00 +000062
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +000063static cl::opt<DebugCompressionType> CompressDebugSections(
64 "compress-debug-sections", cl::ValueOptional,
65 cl::init(DebugCompressionType::None),
66 cl::desc("Choose DWARF debug sections compression:"),
67 cl::values(clEnumValN(DebugCompressionType::None, "none", "No compression"),
68 clEnumValN(DebugCompressionType::Z, "zlib",
69 "Use zlib compression"),
70 clEnumValN(DebugCompressionType::GNU, "zlib-gnu",
71 "Use zlib-gnu compression (deprecated)")));
David Blaikie7400a972014-03-27 20:45:58 +000072
73static cl::opt<bool>
Daniel Dunbare3ee3322010-02-03 18:18:30 +000074ShowInst("show-inst", cl::desc("Show internal instruction representation"));
75
Daniel Dunbar2eca0252010-08-11 06:37:09 +000076static cl::opt<bool>
77ShowInstOperands("show-inst-operands",
78 cl::desc("Show instructions operands as parsed"));
79
Chris Lattner44790342009-09-20 07:17:49 +000080static cl::opt<unsigned>
81OutputAsmVariant("output-asm-variant",
82 cl::desc("Syntax variant to use for output printing"));
83
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +000084static cl::opt<bool>
85PrintImmHex("print-imm-hex", cl::init(false),
86 cl::desc("Prefer hex format for immediate values"));
87
Colin LeMahieu229a1e62015-06-07 01:46:24 +000088static cl::list<std::string>
89DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant"));
90
Nirav Dave53a72f42016-07-11 12:42:14 +000091static cl::opt<bool>
92 PreserveComments("preserve-comments",
93 cl::desc("Preserve Comments in outputted assembly"));
94
Daniel Dunbar3016db32009-08-21 09:11:24 +000095enum OutputFileType {
Daniel Dunbarb09b8902010-03-23 23:47:12 +000096 OFT_Null,
Daniel Dunbar3016db32009-08-21 09:11:24 +000097 OFT_AssemblyFile,
98 OFT_ObjectFile
99};
100static cl::opt<OutputFileType>
101FileType("filetype", cl::init(OFT_AssemblyFile),
102 cl::desc("Choose an output file type:"),
103 cl::values(
104 clEnumValN(OFT_AssemblyFile, "asm",
105 "Emit an assembly ('.s') file"),
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000106 clEnumValN(OFT_Null, "null",
107 "Don't emit anything (for timing purposes)"),
Daniel Dunbar3016db32009-08-21 09:11:24 +0000108 clEnumValN(OFT_ObjectFile, "obj",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000109 "Emit a native object ('.o') file")));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000110
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000111static cl::list<std::string>
112IncludeDirs("I", cl::desc("Directory of include files"),
113 cl::value_desc("directory"), cl::Prefix);
Chris Lattner8dd8a522009-06-18 23:04:45 +0000114
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000115static cl::opt<std::string>
Daniel Dunbar46892112010-03-13 02:20:38 +0000116ArchName("arch", cl::desc("Target arch to assemble for, "
Bill Wendlinge3031142011-06-17 20:35:21 +0000117 "see -version for available targets"));
Daniel Dunbar46892112010-03-13 02:20:38 +0000118
119static cl::opt<std::string>
Nick Lewyckyb2449092009-11-01 22:07:54 +0000120TripleName("triple", cl::desc("Target triple to assemble for, "
Daniel Dunbar46892112010-03-13 02:20:38 +0000121 "see -version for available targets"));
Daniel Dunbar8c6bad22009-07-17 22:38:58 +0000122
Jim Grosbach685b7732010-10-30 15:57:50 +0000123static cl::opt<std::string>
124MCPU("mcpu",
125 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
126 cl::value_desc("cpu-name"),
127 cl::init(""));
128
James Molloy4c493e82011-09-07 17:24:38 +0000129static cl::list<std::string>
130MAttrs("mattr",
131 cl::CommaSeparated,
132 cl::desc("Target specific attributes (-mattr=help for details)"),
133 cl::value_desc("a1,+a2,-a3,..."));
134
Rafael Espindola699281c2016-05-18 11:58:50 +0000135static cl::opt<bool> PIC("position-independent",
136 cl::desc("Position independent"), cl::init(false));
Evan Cheng2129f592011-07-19 06:37:02 +0000137
Rafael Espindola9f929952017-08-02 20:32:26 +0000138static cl::opt<bool>
139 LargeCodeModel("large-code-model",
140 cl::desc("Create cfi directives that assume the code might "
141 "be more than 2gb away"));
Evan Chengefd9b422011-07-20 07:51:56 +0000142
Daniel Dunbar322fec62010-03-13 02:20:57 +0000143static cl::opt<bool>
Bill Wendlinge3031142011-06-17 20:35:21 +0000144NoInitialTextSection("n", cl::desc("Don't assume assembly file starts "
145 "in the text section"));
Daniel Dunbar322fec62010-03-13 02:20:57 +0000146
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000147static cl::opt<bool>
Kevin Enderby6469fc22011-11-01 22:27:22 +0000148GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly "
149 "source files"));
150
Chandler Carruth10700aad2012-12-17 21:32:42 +0000151static cl::opt<std::string>
152DebugCompilationDir("fdebug-compilation-dir",
153 cl::desc("Specifies the debug info's compilation dir"));
154
Paul Robinsonc17c8bf2018-07-10 14:41:54 +0000155static cl::list<std::string>
156DebugPrefixMap("fdebug-prefix-map",
157 cl::desc("Map file source paths in debug info"),
158 cl::value_desc("= separated key-value pairs"));
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",
Mehdi Amini732afdd2016-10-08 19:41:06 +0000187 "Marked up disassembly of strings of hex bytes")));
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000188
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000189static const Target *GetTarget(const char *ProgName) {
Daniel Dunbar46892112010-03-13 02:20:38 +0000190 // Figure out the target triple.
191 if (TripleName.empty())
Sebastian Pop94441fb2011-11-01 21:32:20 +0000192 TripleName = sys::getDefaultTargetTriple();
Evan Chenge64f0e52011-07-26 19:02:16 +0000193 Triple TheTriple(Triple::normalize(TripleName));
194
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000195 // Get the target specific parser.
196 std::string Error;
197 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
198 Error);
199 if (!TheTarget) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000200 WithColor::error(errs(), ProgName) << Error;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000201 return nullptr;
Daniel Dunbar46892112010-03-13 02:20:38 +0000202 }
203
Kevin Enderbyfe3d0052012-05-08 23:38:45 +0000204 // Update the triple name and return the found target.
Evan Chenge64f0e52011-07-26 19:02:16 +0000205 TripleName = TheTriple.getTriple();
206 return TheTarget;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000207}
208
Peter Collingbourne63062d92018-05-21 19:44:54 +0000209static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path) {
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000210 std::error_code EC;
Peter Collingbourne63062d92018-05-21 19:44:54 +0000211 auto Out = llvm::make_unique<ToolOutputFile>(Path, EC, sys::fs::F_None);
Rafael Espindola3fd1e992014-08-25 18:16:47 +0000212 if (EC) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000213 WithColor::error() << EC.message() << '\n';
Craig Toppere6cb63e2014-04-25 04:24:47 +0000214 return nullptr;
Dan Gohman268b0f42010-08-20 01:07:01 +0000215 }
Dan Gohmana2233f22010-09-01 14:20:41 +0000216
217 return Out;
Dan Gohman268b0f42010-08-20 01:07:01 +0000218}
219
Kevin Enderbye7739d42011-12-09 18:09:40 +0000220static std::string DwarfDebugFlags;
221static void setDwarfDebugFlags(int argc, char **argv) {
222 if (!getenv("RC_DEBUG_OPTIONS"))
223 return;
224 for (int i = 0; i < argc; i++) {
225 DwarfDebugFlags += argv[i];
226 if (i + 1 < argc)
227 DwarfDebugFlags += " ";
228 }
229}
230
Kevin Enderbye82ada62013-01-16 17:46:23 +0000231static std::string DwarfDebugProducer;
Eugene Zelenkoffec81c2015-11-04 22:32:32 +0000232static void setDwarfDebugProducer() {
Kevin Enderbye82ada62013-01-16 17:46:23 +0000233 if(!getenv("DEBUG_PRODUCER"))
234 return;
235 DwarfDebugProducer += getenv("DEBUG_PRODUCER");
236}
237
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000238static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI,
Craig Topper4e05fc32014-12-12 07:52:19 +0000239 raw_ostream &OS) {
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000240
Richard Bartondef81b92012-04-16 11:32:10 +0000241 AsmLexer Lexer(MAI);
Rafael Espindola8026bd02014-07-06 14:17:29 +0000242 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer());
Daniel Dunbar7a85f9c2010-07-18 18:31:28 +0000243
Chris Lattnerb0133452009-06-21 20:16:42 +0000244 bool Error = false;
Daniel Dunbarbc798162009-07-28 16:56:42 +0000245 while (Lexer.Lex().isNot(AsmToken::Eof)) {
Oliver Stannard5c032ce2018-03-06 14:02:14 +0000246 Lexer.getTok().dump(OS);
247 OS << "\n";
248 if (Lexer.getTok().getKind() == AsmToken::Error)
Chris Lattnerb0133452009-06-21 20:16:42 +0000249 Error = true;
Chris Lattnerc8dfbcb2009-06-21 07:19:10 +0000250 }
Dan Gohman268b0f42010-08-20 01:07:01 +0000251
Chris Lattnerb0133452009-06-21 20:16:42 +0000252 return Error;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000253}
254
Mandeep Singh Grang32360072016-12-01 18:42:04 +0000255static int fillCommandLineSymbols(MCAsmParser &Parser) {
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000256 for (auto &I: DefineSymbol) {
257 auto Pair = StringRef(I).split('=');
258 auto Sym = Pair.first;
259 auto Val = Pair.second;
260
261 if (Sym.empty() || Val.empty()) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000262 WithColor::error() << "defsym must be of the form: sym=value: " << I
263 << "\n";
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000264 return 1;
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000265 }
266 int64_t Value;
267 if (Val.getAsInteger(0, Value)) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000268 WithColor::error() << "value is not an integer: " << Val << "\n";
Mandeep Singh Grang9a561aa2016-12-06 02:49:17 +0000269 return 1;
270 }
271 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value);
272 }
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000273 return 0;
274}
275
NAKAMURA Takumi89b8c172014-01-22 03:12:43 +0000276static int AssembleInput(const char *ProgName, const Target *TheTarget,
Richard Bartondef81b92012-04-16 11:32:10 +0000277 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000278 MCAsmInfo &MAI, MCSubtargetInfo &STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000279 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Evgeniy Stepanov0a951b72014-04-23 11:16:03 +0000280 std::unique_ptr<MCAsmParser> Parser(
281 createMCAsmParser(SrcMgr, Ctx, Str, MAI));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000282 std::unique_ptr<MCTargetAsmParser> TAP(
Eric Christopher4c5bff32014-06-19 06:22:08 +0000283 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
284
Richard Bartondef81b92012-04-16 11:32:10 +0000285 if (!TAP) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000286 WithColor::error(errs(), ProgName)
287 << "this target does not support assembly parsing.\n";
Richard Bartondef81b92012-04-16 11:32:10 +0000288 return 1;
289 }
290
Colin LeMahieu229a1e62015-06-07 01:46:24 +0000291 int SymbolResult = fillCommandLineSymbols(*Parser);
292 if(SymbolResult)
293 return SymbolResult;
Richard Bartondef81b92012-04-16 11:32:10 +0000294 Parser->setShowParsedOperands(ShowInstOperands);
Craig Topper4e05fc32014-12-12 07:52:19 +0000295 Parser->setTargetParser(*TAP);
Richard Bartondef81b92012-04-16 11:32:10 +0000296
297 int Res = Parser->Run(NoInitialTextSection);
298
299 return Res;
300}
301
302int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000303 InitLLVM X(argc, argv);
Richard Bartondef81b92012-04-16 11:32:10 +0000304
305 // Initialize targets and assembly printers/parsers.
306 llvm::InitializeAllTargetInfos();
307 llvm::InitializeAllTargetMCs();
308 llvm::InitializeAllAsmParsers();
309 llvm::InitializeAllDisassemblers();
310
311 // Register the target printer for --version.
312 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
313
314 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n");
Eric Christopher4c5bff32014-06-19 06:22:08 +0000315 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Richard Bartondef81b92012-04-16 11:32:10 +0000316 setDwarfDebugFlags(argc, argv);
317
Kevin Enderbye82ada62013-01-16 17:46:23 +0000318 setDwarfDebugProducer();
319
Richard Bartondef81b92012-04-16 11:32:10 +0000320 const char *ProgName = argv[0];
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000321 const Target *TheTarget = GetTarget(ProgName);
322 if (!TheTarget)
323 return 1;
Daniel Sandersc535d932015-06-16 09:57:38 +0000324 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to
325 // construct the Triple object.
326 Triple TheTriple(TripleName);
Daniel Dunbar80d484e2009-08-14 03:48:55 +0000327
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000328 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
329 MemoryBuffer::getFileOrSTDIN(InputFilename);
330 if (std::error_code EC = BufferPtr.getError()) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000331 WithColor::error(errs(), ProgName)
332 << InputFilename << ": " << EC.message() << '\n';
Chris Lattnerb0133452009-06-21 20:16:42 +0000333 return 1;
334 }
David Blaikie1961f142014-08-21 20:44:56 +0000335 MemoryBuffer *Buffer = BufferPtr->get();
Jim Grosbach112a2de2011-05-09 20:05:25 +0000336
Chris Lattnerb0133452009-06-21 20:16:42 +0000337 SourceMgr SrcMgr;
Jim Grosbach112a2de2011-05-09 20:05:25 +0000338
Daniel Dunbar5c947db2009-08-19 16:25:53 +0000339 // Tell SrcMgr about this buffer, which is what the parser will pick up.
David Blaikie1961f142014-08-21 20:44:56 +0000340 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
Jim Grosbach112a2de2011-05-09 20:05:25 +0000341
Chris Lattnerb0133452009-06-21 20:16:42 +0000342 // Record the location of the include directories so that the lexer can find
343 // it later.
344 SrcMgr.setIncludeDirs(IncludeDirs);
Jim Grosbach112a2de2011-05-09 20:05:25 +0000345
Ahmed Charles56440fd2014-03-06 05:51:42 +0000346 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
Evan Chengd60fa58b2011-07-18 20:57:22 +0000347 assert(MRI && "Unable to create target register info!");
348
Ahmed Charles56440fd2014-03-06 05:51:42 +0000349 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
Rafael Espindola227144c2013-05-13 01:16:13 +0000350 assert(MAI && "Unable to create target asm info!");
351
Rafael Espindola9768d732016-05-29 01:11:00 +0000352 MAI->setRelaxELFRelocations(RelaxELFRel);
353
Saleem Abdulrasool1f62f572017-06-09 00:40:19 +0000354 if (CompressDebugSections != DebugCompressionType::None) {
David Blaikie9b620b42014-03-28 20:45:24 +0000355 if (!zlib::isAvailable()) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000356 WithColor::error(errs(), ProgName)
357 << "build tools with zlib to enable -compress-debug-sections";
David Blaikie9b620b42014-03-28 20:45:24 +0000358 return 1;
359 }
George Rimarc91e38c2016-05-27 12:27:32 +0000360 MAI->setCompressDebugSections(CompressDebugSections);
David Blaikie9b620b42014-03-28 20:45:24 +0000361 }
Nirav Dave53a72f42016-07-11 12:42:14 +0000362 MAI->setPreserveAsmComments(PreserveComments);
David Blaikie7400a972014-03-27 20:45:58 +0000363
Evan Cheng76792992011-07-20 05:58:47 +0000364 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and
365 // MCObjectFileInfo needs a MCContext reference in order to initialize itself.
Rafael Espindola75556bc2014-06-28 17:46:19 +0000366 MCObjectFileInfo MOFI;
367 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
Rafael Espindola9f929952017-08-02 20:32:26 +0000368 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel);
Evan Cheng76792992011-07-20 05:58:47 +0000369
Daniel Dunbar4ee0d032011-03-28 22:49:15 +0000370 if (SaveTempLabels)
371 Ctx.setAllowTemporaryLabels(false);
Rafael Espindola0a017a62010-12-10 07:39:47 +0000372
Kevin Enderby6469fc22011-11-01 22:27:22 +0000373 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly);
Eric Christopher4c5bff32014-06-19 06:22:08 +0000374 // Default to 4 for dwarf version.
375 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4;
Paul Robinsondccb4fe2017-02-28 23:40:46 +0000376 if (DwarfVersion < 2 || DwarfVersion > 5) {
Oliver Stannard7eacbd52014-05-01 08:46:02 +0000377 errs() << ProgName << ": Dwarf version " << DwarfVersion
378 << " is not supported." << '\n';
379 return 1;
380 }
381 Ctx.setDwarfVersion(DwarfVersion);
Chandler Carruth10700aad2012-12-17 21:32:42 +0000382 if (!DwarfDebugFlags.empty())
Kevin Enderbye7739d42011-12-09 18:09:40 +0000383 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags));
Kevin Enderbye82ada62013-01-16 17:46:23 +0000384 if (!DwarfDebugProducer.empty())
385 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer));
Chandler Carruth10700aad2012-12-17 21:32:42 +0000386 if (!DebugCompilationDir.empty())
387 Ctx.setCompilationDir(DebugCompilationDir);
Justin Bogner8809c402016-03-22 22:24:29 +0000388 else {
389 // If no compilation dir is set, try to use the current directory.
390 SmallString<128> CWD;
391 if (!sys::fs::current_path(CWD))
392 Ctx.setCompilationDir(CWD);
393 }
Paul Robinsonc17c8bf2018-07-10 14:41:54 +0000394 for (const auto &Arg : DebugPrefixMap) {
395 const auto &KV = StringRef(Arg).split('=');
396 Ctx.addDebugPrefixMapEntry(KV.first, KV.second);
397 }
Eric Christopher906da232012-12-18 00:31:01 +0000398 if (!MainFileName.empty())
399 Ctx.setMainFileName(MainFileName);
Paul Robinsonf69316c2018-06-12 16:09:03 +0000400 if (GenDwarfForAssembly && DwarfVersion >= 5) {
Paul Robinsonb271f312018-03-29 17:16:41 +0000401 // DWARF v5 needs the root file as well as the compilation directory.
402 // If we find a '.file 0' directive that will supersede these values.
403 MD5 Hash;
404 MD5::MD5Result *Cksum =
405 (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
406 Hash.update(Buffer->getBuffer());
407 Hash.final(*Cksum);
408 Ctx.setMCLineTableRootFile(
409 /*CUID=*/0, Ctx.getCompilationDir(),
410 !MainFileName.empty() ? MainFileName : InputFilename, Cksum, None);
411 }
Kevin Enderby6469fc22011-11-01 22:27:22 +0000412
James Molloy4c493e82011-09-07 17:24:38 +0000413 // Package up features to be passed to target/subtarget
414 std::string FeaturesStr;
415 if (MAttrs.size()) {
416 SubtargetFeatures Features;
417 for (unsigned i = 0; i != MAttrs.size(); ++i)
418 Features.AddFeature(MAttrs[i]);
419 FeaturesStr = Features.getString();
420 }
421
Peter Collingbourne63062d92018-05-21 19:44:54 +0000422 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename);
Dan Gohman268b0f42010-08-20 01:07:01 +0000423 if (!Out)
424 return 1;
425
Peter Collingbourne63062d92018-05-21 19:44:54 +0000426 std::unique_ptr<ToolOutputFile> DwoOut;
427 if (!SplitDwarfFile.empty()) {
428 if (FileType != OFT_ObjectFile) {
429 WithColor::error() << "dwo output only supported with object files\n";
430 return 1;
431 }
432 DwoOut = GetOutputStream(SplitDwarfFile);
433 if (!DwoOut)
434 return 1;
435 }
436
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000437 std::unique_ptr<buffer_ostream> BOS;
438 raw_pwrite_stream *OS = &Out->os();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000439 std::unique_ptr<MCStreamer> Str;
Chris Lattnera61e93d2009-08-17 04:23:44 +0000440
Ahmed Charles56440fd2014-03-06 05:51:42 +0000441 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
442 std::unique_ptr<MCSubtargetInfo> STI(
443 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Evan Cheng91111d22011-07-09 05:47:46 +0000444
Craig Toppere6cb63e2014-04-25 04:24:47 +0000445 MCInstPrinter *IP = nullptr;
Kevin Enderbyf92f9902009-09-04 21:45:34 +0000446 if (FileType == OFT_AssemblyFile) {
Daniel Sanders50f17232015-09-15 16:17:27 +0000447 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant,
448 *MAI, *MCII, *MRI);
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000449
Nirav Davea9395af2016-10-31 18:36:31 +0000450 if (!IP) {
Jonas Devliegherec976aa72018-04-22 08:01:35 +0000451 WithColor::error()
452 << "unable to create instruction printer for target triple '"
Nirav Davea9395af2016-10-31 18:36:31 +0000453 << TheTriple.normalize() << "' with assembly variant "
454 << OutputAsmVariant << ".\n";
455 return 1;
456 }
457
Jim Grosbach3fdf7cf2014-06-11 20:26:40 +0000458 // Set the display preference for hex vs. decimal immediates.
459 IP->setPrintImmHex(PrintImmHex);
460
461 // Set up the AsmStreamer.
Nirav Dave1b5533c2018-04-27 15:45:54 +0000462 std::unique_ptr<MCCodeEmitter> CE;
463 if (ShowEncoding)
464 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
465
466 std::unique_ptr<MCAsmBackend> MAB(
467 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000468 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS);
Nirav Dave1b5533c2018-04-27 15:45:54 +0000469 Str.reset(
470 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true,
471 /*useDwarfDirectory*/ true, IP,
472 std::move(CE), std::move(MAB), ShowInst));
Jim Grosbach78309c42011-12-05 23:20:14 +0000473
Daniel Dunbarb09b8902010-03-23 23:47:12 +0000474 } else if (FileType == OFT_Null) {
Peter Collingbournef4498a42015-02-19 00:45:04 +0000475 Str.reset(TheTarget->createNullStreamer(Ctx));
Daniel Dunbar3016db32009-08-21 09:11:24 +0000476 } else {
477 assert(FileType == OFT_ObjectFile && "Invalid file type!");
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000478
Rafael Espindolaf27fa2b2015-06-17 16:26:47 +0000479 // Don't waste memory on names of temp labels.
480 Ctx.setUseNamesOnTempLabels(false);
481
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000482 if (!Out->os().supportsSeeking()) {
483 BOS = make_unique<buffer_ostream>(Out->os());
484 OS = BOS.get();
485 }
486
Eric Christopher0169e422015-03-10 22:03:14 +0000487 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx);
Alex Bradburyb22f7512018-01-03 08:53:05 +0000488 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
David Majnemer03e2cc32015-12-21 22:09:27 +0000489 Str.reset(TheTarget->createMCObjectStreamer(
Peter Collingbournef7b81db2018-05-18 18:26:45 +0000490 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
Peter Collingbourne63062d92018-05-21 19:44:54 +0000491 DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os())
492 : MAB->createObjectWriter(*OS),
493 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll,
494 MCOptions.MCIncrementalLinkerCompatible,
David Majnemer03e2cc32015-12-21 22:09:27 +0000495 /*DWARFMustBeAtTheEnd*/ false));
Rafael Espindola7b61ddf2014-10-15 16:12:52 +0000496 if (NoExecStack)
497 Str->InitSections(true);
Daniel Dunbar3016db32009-08-21 09:11:24 +0000498 }
Daniel Dunbara10e5192009-06-24 23:30:00 +0000499
Nirav Dave6c0665e2018-04-30 19:22:40 +0000500 // Use Assembler information for parsing.
501 Str->setUseAssemblerInfoForParsing(true);
502
Richard Bartondef81b92012-04-16 11:32:10 +0000503 int Res = 1;
Kevin Enderby168ffb32012-12-05 18:13:19 +0000504 bool disassemble = false;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000505 switch (Action) {
Chris Lattnerb0133452009-06-21 20:16:42 +0000506 case AC_AsLex:
Craig Topper4e05fc32014-12-12 07:52:19 +0000507 Res = AsLexInput(SrcMgr, *MAI, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000508 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000509 case AC_Assemble:
Eric Christopher23c6d1f2014-06-19 06:22:01 +0000510 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
Eric Christopher4c5bff32014-06-19 06:22:08 +0000511 *MCII, MCOptions);
Richard Bartondef81b92012-04-16 11:32:10 +0000512 break;
Kevin Enderby62183c42012-10-22 22:31:46 +0000513 case AC_MDisassemble:
Eli Bendersky6f5d70e2013-02-26 23:04:17 +0000514 assert(IP && "Expected assembly output");
Kevin Enderby62183c42012-10-22 22:31:46 +0000515 IP->setUseMarkup(1);
Kevin Enderby168ffb32012-12-05 18:13:19 +0000516 disassemble = true;
517 break;
Sean Callanan7e645502009-12-17 01:49:59 +0000518 case AC_Disassemble:
Kevin Enderby168ffb32012-12-05 18:13:19 +0000519 disassemble = true;
Richard Bartondef81b92012-04-16 11:32:10 +0000520 break;
Chris Lattnerd70e15b42009-06-21 05:22:37 +0000521 }
Kevin Enderby168ffb32012-12-05 18:13:19 +0000522 if (disassemble)
523 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str,
524 *Buffer, SrcMgr, Out->os());
Richard Bartondef81b92012-04-16 11:32:10 +0000525
526 // Keep output if no errors.
Peter Collingbourne63062d92018-05-21 19:44:54 +0000527 if (Res == 0) {
528 Out->keep();
529 if (DwoOut)
530 DwoOut->keep();
531 }
Richard Bartondef81b92012-04-16 11:32:10 +0000532 return Res;
Chris Lattner8dd8a522009-06-18 23:04:45 +0000533}