blob: 81b429a8d11ebf00972520dced489f223b7196e5 [file] [log] [blame]
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001//===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements classes used to handle lowerings specific to common
11// object file formats.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/ADT/Triple.h"
19#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000025#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Peter Collingbourne94d77862015-11-03 23:40:03 +000027#include "llvm/MC/MCAsmInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000028#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000030#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/MC/MCSectionELF.h"
32#include "llvm/MC/MCSectionMachO.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000033#include "llvm/MC/MCStreamer.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000034#include "llvm/MC/MCSymbolELF.h"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000035#include "llvm/MC/MCValue.h"
Xinliang David Li5f04f922016-01-14 18:09:45 +000036#include "llvm/ProfileData/InstrProf.h"
Reid Kleckner1f13d472015-09-03 16:41:50 +000037#include "llvm/Support/COFF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000038#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000039#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000040#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/raw_ostream.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000042#include "llvm/Target/TargetLowering.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000043#include "llvm/Target/TargetMachine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000044#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000045using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000046using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000047
48//===----------------------------------------------------------------------===//
49// ELF
50//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000051
Rafael Espindoladaeafb42014-02-19 17:23:20 +000052MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
53 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
54 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000055 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000056 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Jim Grosbach6f482002015-05-18 18:43:14 +000057 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000058 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000059 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
60 return TM.getSymbol(GV, Mang);
61 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +000062}
63
Mehdi Amini5c0fa582015-07-16 06:04:17 +000064void TargetLoweringObjectFileELF::emitPersonalityValue(
65 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000066 SmallString<64> NameData("DW.ref.");
67 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +000068 MCSymbolELF *Label =
69 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +000070 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
71 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000072 StringRef Prefix = ".data.";
73 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-04-27 21:29:52 +000074 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Rafael Espindola0709a7b2015-05-21 19:20:38 +000075 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
76 Flags, 0, Label->getName());
Mehdi Amini5c0fa582015-07-16 06:04:17 +000077 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000078 Streamer.SwitchSection(Sec);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000079 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000080 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +000081 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +000082 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +000083 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000084
Rafael Espindola39897762011-04-27 21:29:52 +000085 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000086}
87
Rafael Espindola15b26692014-02-09 14:50:44 +000088const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
89 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000090 const TargetMachine &TM, MachineModuleInfo *MMI,
91 MCStreamer &Streamer) const {
Anton Korobeynikove42af362012-11-14 01:47:00 +000092
93 if (Encoding & dwarf::DW_EH_PE_indirect) {
94 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
95
Rafael Espindoladaeafb42014-02-19 17:23:20 +000096 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +000097
98 // Add information about the stub reference to ELFMMI so that the stub
99 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +0000100 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000101 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000102 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000103 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
104 }
105
106 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000107 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000108 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
109 }
110
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000111 return TargetLoweringObjectFile::
112 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000113}
114
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000115static SectionKind
116getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000117 // N.B.: The defaults used in here are no the same ones used in MC.
118 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
119 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000120 // section(".eh_frame") gcc will produce:
121 //
122 // .section .eh_frame,"a",@progbits
Xinliang David Li5f04f922016-01-14 18:09:45 +0000123
124 if (Name == getInstrProfCoverageSectionName(false))
125 return SectionKind::getMetadata();
126
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000127 if (Name.empty() || Name[0] != '.') return K;
128
129 // Some lame default implementation based on some magic section names.
130 if (Name == ".bss" ||
131 Name.startswith(".bss.") ||
132 Name.startswith(".gnu.linkonce.b.") ||
133 Name.startswith(".llvm.linkonce.b.") ||
134 Name == ".sbss" ||
135 Name.startswith(".sbss.") ||
136 Name.startswith(".gnu.linkonce.sb.") ||
137 Name.startswith(".llvm.linkonce.sb."))
138 return SectionKind::getBSS();
139
140 if (Name == ".tdata" ||
141 Name.startswith(".tdata.") ||
142 Name.startswith(".gnu.linkonce.td.") ||
143 Name.startswith(".llvm.linkonce.td."))
144 return SectionKind::getThreadData();
145
146 if (Name == ".tbss" ||
147 Name.startswith(".tbss.") ||
148 Name.startswith(".gnu.linkonce.tb.") ||
149 Name.startswith(".llvm.linkonce.tb."))
150 return SectionKind::getThreadBSS();
151
152 return K;
153}
154
155
156static unsigned getELFSectionType(StringRef Name, SectionKind K) {
157
158 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000159 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000160
161 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000162 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000163
164 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000165 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000166
167 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000168 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000169
Rafael Espindolaaea49582011-01-23 04:28:49 +0000170 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000171}
172
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000173static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000174 unsigned Flags = 0;
175
176 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000177 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000178
179 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000180 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000181
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000182 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000183 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000184
185 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000186 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000187
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000188 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000189 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000190
191 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000192 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000193
194 return Flags;
195}
196
David Majnemerdad0a642014-06-27 18:19:56 +0000197static const Comdat *getELFComdat(const GlobalValue *GV) {
198 const Comdat *C = GV->getComdat();
199 if (!C)
200 return nullptr;
201
202 if (C->getSelectionKind() != Comdat::Any)
203 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
204 C->getName() + "' cannot be lowered.");
205
206 return C;
207}
208
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000209MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000210 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
211 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000212 StringRef SectionName = GV->getSection();
213
214 // Infer section flags from the section name if we can.
215 Kind = getELFKindForNamedSection(SectionName, Kind);
216
David Majnemerdad0a642014-06-27 18:19:56 +0000217 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000218 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000219 if (const Comdat *C = getELFComdat(GV)) {
220 Group = C->getName();
221 Flags |= ELF::SHF_GROUP;
222 }
Chris Lattner80c34592010-04-08 21:34:17 +0000223 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000224 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000225 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000226}
227
Rafael Espindola25d2c202015-02-11 14:44:17 +0000228/// Return the section prefix name used by options FunctionsSections and
229/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000230static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000231 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000232 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000233 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000234 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000235 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000236 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000237 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000238 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000239 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000240 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000241 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000242 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000244 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000245}
246
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000247static MCSectionELF *
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000248selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
249 SectionKind Kind, Mangler &Mang,
250 const TargetMachine &TM, bool EmitUniqueSection,
251 unsigned Flags, unsigned *NextUniqueID) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000252 unsigned EntrySize = 0;
253 if (Kind.isMergeableCString()) {
254 if (Kind.isMergeable2ByteCString()) {
255 EntrySize = 2;
256 } else if (Kind.isMergeable4ByteCString()) {
257 EntrySize = 4;
258 } else {
259 EntrySize = 1;
260 assert(Kind.isMergeable1ByteCString() && "unknown string width");
261 }
262 } else if (Kind.isMergeableConst()) {
263 if (Kind.isMergeableConst4()) {
264 EntrySize = 4;
265 } else if (Kind.isMergeableConst8()) {
266 EntrySize = 8;
267 } else {
268 assert(Kind.isMergeableConst16() && "unknown data width");
269 EntrySize = 16;
270 }
271 }
272
Rafael Espindola9075f772015-02-20 23:28:28 +0000273 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000274 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000275 Flags |= ELF::SHF_GROUP;
276 Group = C->getName();
277 }
278
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000279 bool UniqueSectionNames = TM.getUniqueSectionNames();
280 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000281 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000282 // We also need alignment here.
283 // FIXME: this is getting the alignment of the character, not the
284 // alignment of the global!
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000285 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
286 cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000287
Rafael Espindolaba31e272015-01-29 17:33:21 +0000288 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000289 Name = SizeSpec + utostr(Align);
290 } else if (Kind.isMergeableConst()) {
291 Name = ".rodata.cst";
292 Name += utostr(EntrySize);
293 } else {
294 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000295 }
296
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000297 if (EmitUniqueSection && UniqueSectionNames) {
298 Name.push_back('.');
299 TM.getNameWithPrefix(Name, GV, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000300 }
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000301 unsigned UniqueID = ~0;
302 if (EmitUniqueSection && !UniqueSectionNames) {
303 UniqueID = *NextUniqueID;
304 (*NextUniqueID)++;
305 }
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000306 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000307 EntrySize, Group, UniqueID);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000308}
309
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000310MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000311 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
312 const TargetMachine &TM) const {
313 unsigned Flags = getELFSectionFlags(Kind);
314
315 // If we have -ffunction-section or -fdata-section then we should emit the
316 // global value to a uniqued section specifically for it.
317 bool EmitUniqueSection = false;
318 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
319 if (Kind.isText())
320 EmitUniqueSection = TM.getFunctionSections();
321 else
322 EmitUniqueSection = TM.getDataSections();
323 }
324 EmitUniqueSection |= GV->hasComdat();
325
326 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000327 EmitUniqueSection, Flags, &NextUniqueID);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000328}
329
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000330MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Rafael Espindola29786d42015-02-12 17:16:46 +0000331 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
332 // If the function can be removed, produce a unique section so that
333 // the table doesn't prevent the removal.
334 const Comdat *C = F.getComdat();
335 bool EmitUniqueSection = TM.getFunctionSections() || C;
336 if (!EmitUniqueSection)
337 return ReadOnlySection;
338
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000339 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000340 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
341 &NextUniqueID);
Rafael Espindola29786d42015-02-12 17:16:46 +0000342}
343
Rafael Espindoladf195192015-02-17 23:34:51 +0000344bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
345 bool UsesLabelDifference, const Function &F) const {
346 // We can always create relative relocations, so use another section
347 // that can be marked non-executable.
348 return false;
349}
350
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000351/// Given a mergeable constant with the specified size and relocation
352/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000353MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000354 const DataLayout &DL, SectionKind Kind, const Constant *C,
355 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000356 if (Kind.isMergeableConst4() && MergeableConst4Section)
357 return MergeableConst4Section;
358 if (Kind.isMergeableConst8() && MergeableConst8Section)
359 return MergeableConst8Section;
360 if (Kind.isMergeableConst16() && MergeableConst16Section)
361 return MergeableConst16Section;
362 if (Kind.isReadOnly())
363 return ReadOnlySection;
364
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000365 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
366 return DataRelROSection;
367}
368
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000369static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
370 bool IsCtor, unsigned Priority,
371 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000372 std::string Name;
373 unsigned Type;
374 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000375 StringRef COMDAT = KeySym ? KeySym->getName() : "";
376
377 if (KeySym)
378 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000379
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000380 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000381 if (IsCtor) {
382 Type = ELF::SHT_INIT_ARRAY;
383 Name = ".init_array";
384 } else {
385 Type = ELF::SHT_FINI_ARRAY;
386 Name = ".fini_array";
387 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000388 if (Priority != 65535) {
389 Name += '.';
390 Name += utostr(Priority);
391 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000392 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000393 // The default scheme is .ctor / .dtor, so we have to invert the priority
394 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000395 if (IsCtor)
396 Name = ".ctors";
397 else
398 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000399 if (Priority != 65535) {
400 Name += '.';
401 Name += utostr(65535 - Priority);
402 }
403 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000404 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000405
Rafael Espindolaba31e272015-01-29 17:33:21 +0000406 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000407}
408
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000409MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000410 unsigned Priority, const MCSymbol *KeySym) const {
411 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
412 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000413}
414
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000415MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000416 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000417 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
418 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000419}
420
421void
422TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
423 UseInitArray = UseInitArray_;
424 if (!UseInitArray)
425 return;
426
Rafael Espindolaba31e272015-01-29 17:33:21 +0000427 StaticCtorSection = getContext().getELFSection(
428 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
429 StaticDtorSection = getContext().getELFSection(
430 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000431}
432
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000433//===----------------------------------------------------------------------===//
434// MachO
435//===----------------------------------------------------------------------===//
436
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000437TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
438 : TargetLoweringObjectFile() {
439 SupportIndirectSymViaGOTPCRel = true;
440}
441
Daniel Dunbar95856122013-01-18 19:37:00 +0000442/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000443void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000444emitModuleFlags(MCStreamer &Streamer,
445 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000446 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000447 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000448 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000449 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000450 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000451
Bill Wendling734909a2012-02-15 22:36:15 +0000452 for (ArrayRef<Module::ModuleFlagEntry>::iterator
453 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
454 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000455
456 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000457 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000458 continue;
459
Bill Wendling734909a2012-02-15 22:36:15 +0000460 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000461 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000462
Daniel Dunbar95856122013-01-18 19:37:00 +0000463 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000464 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000465 } else if (Key == "Objective-C Garbage Collection" ||
466 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000467 Key == "Objective-C Is Simulated" ||
Manman Renc77e0ff2016-01-29 23:51:00 +0000468 Key == "Objective-C Class Properties" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000469 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000470 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000471 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000472 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000473 } else if (Key == "Linker Options") {
474 LinkerOptions = cast<MDNode>(Val);
475 }
476 }
477
478 // Emit the linker options if present.
479 if (LinkerOptions) {
480 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
481 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
482 SmallVector<std::string, 4> StrOptions;
483
484 // Convert to strings.
485 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
486 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
487 StrOptions.push_back(MDOption->getString());
488 }
489
490 Streamer.EmitLinkerOptions(StrOptions);
491 }
Bill Wendling06df7722012-02-14 21:28:13 +0000492 }
493
Bill Wendling734909a2012-02-15 22:36:15 +0000494 // The section is mandatory. If we don't have it, then we don't have GC info.
495 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000496
Bill Wendling734909a2012-02-15 22:36:15 +0000497 StringRef Segment, Section;
498 unsigned TAA = 0, StubSize = 0;
499 bool TAAParsed;
500 std::string ErrorCode =
501 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
502 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000503 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000504 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000505 report_fatal_error("Invalid section specifier '" + Section + "': " +
506 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000507
Bill Wendling734909a2012-02-15 22:36:15 +0000508 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000509 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000510 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000511 Streamer.SwitchSection(S);
512 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000513 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000514 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000515 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000516 Streamer.AddBlankLine();
517}
518
David Majnemerdad0a642014-06-27 18:19:56 +0000519static void checkMachOComdat(const GlobalValue *GV) {
520 const Comdat *C = GV->getComdat();
521 if (!C)
522 return;
523
524 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
525 "' cannot be lowered.");
526}
527
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000528MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000529 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
530 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000531 // Parse the section specifier and create it if valid.
532 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000533 unsigned TAA = 0, StubSize = 0;
534 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000535
536 checkMachOComdat(GV);
537
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000538 std::string ErrorCode =
539 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000540 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000541 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000542 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000543 report_fatal_error("Global variable '" + GV->getName() +
544 "' has an invalid section specifier '" +
545 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000546 }
547
548 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000549 MCSectionMachO *S =
550 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000551
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000552 // If TAA wasn't set by ParseSectionSpecifier() above,
553 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000554 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000555 TAA = S->getTypeAndAttributes();
556
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000557 // Okay, now that we got the section, verify that the TAA & StubSize agree.
558 // If the user declared multiple globals with different section flags, we need
559 // to reject it here.
560 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000561 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000562 report_fatal_error("Global variable '" + GV->getName() +
563 "' section type or attributes does not match previous"
564 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000565 }
566
567 return S;
568}
569
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000570MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
571 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
572 const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000573 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000574
575 // Handle thread local data.
576 if (Kind.isThreadBSS()) return TLSBSSSection;
577 if (Kind.isThreadData()) return TLSDataSection;
578
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000579 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000580 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
581
582 // If this is weak/linkonce, put this in a coalescable section, either in text
583 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000584 if (GV->isWeakForLinker()) {
585 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000586 return ConstTextCoalSection;
587 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000588 }
589
590 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000591 if (Kind.isMergeable1ByteCString() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000592 GV->getParent()->getDataLayout().getPreferredAlignment(
593 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000594 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000595
Chris Lattneref2f8042010-03-07 04:28:09 +0000596 // Do not put 16-bit arrays in the UString section if they have an
597 // externally visible label, this runs into issues with certain linker
598 // versions.
599 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000600 GV->getParent()->getDataLayout().getPreferredAlignment(
601 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000602 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000603
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000604 // With MachO only variables whose corresponding symbol starts with 'l' or
605 // 'L' can be merged, so we only try merging GVs with private linkage.
606 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000607 if (Kind.isMergeableConst4())
608 return FourByteConstantSection;
609 if (Kind.isMergeableConst8())
610 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000611 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000612 return SixteenByteConstantSection;
613 }
614
615 // Otherwise, if it is readonly, but not something we can specially optimize,
616 // just drop it in .const.
617 if (Kind.isReadOnly())
618 return ReadOnlySection;
619
620 // If this is marked const, put it into a const section. But if the dynamic
621 // linker needs to write to it, put it in the data segment.
622 if (Kind.isReadOnlyWithRel())
623 return ConstDataSection;
624
625 // Put zero initialized globals with strong external linkage in the
626 // DATA, __common section with the .zerofill directive.
627 if (Kind.isBSSExtern())
628 return DataCommonSection;
629
630 // Put zero initialized globals with local linkage in __DATA,__bss directive
631 // with the .zerofill directive (aka .lcomm).
632 if (Kind.isBSSLocal())
633 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000634
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000635 // Otherwise, just drop the variable in the normal data section.
636 return DataSection;
637}
638
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000639MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000640 const DataLayout &DL, SectionKind Kind, const Constant *C,
641 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000642 // If this constant requires a relocation, we have to put it in the data
643 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000644 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000645 return ConstDataSection;
646
647 if (Kind.isMergeableConst4())
648 return FourByteConstantSection;
649 if (Kind.isMergeableConst8())
650 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000651 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000652 return SixteenByteConstantSection;
653 return ReadOnlySection; // .const
654}
655
Rafael Espindola15b26692014-02-09 14:50:44 +0000656const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
657 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000658 const TargetMachine &TM, MachineModuleInfo *MMI,
659 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000660 // The mach-o version of this method defaults to returning a stub reference.
661
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000662 if (Encoding & DW_EH_PE_indirect) {
663 MachineModuleInfoMachO &MachOMMI =
664 MMI->getObjFileInfo<MachineModuleInfoMachO>();
665
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000666 MCSymbol *SSym =
667 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000668
669 // Add information about the stub reference to MachOMMI so that the stub
670 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000671 MachineModuleInfoImpl::StubValueTy &StubSym =
672 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
673 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000674 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000675 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000676 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000677 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000678
679 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000680 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000681 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000682 }
683
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000684 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
685 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000686}
687
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000688MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
689 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
690 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000691 // The mach-o version of this method defaults to returning a stub reference.
692 MachineModuleInfoMachO &MachOMMI =
693 MMI->getObjFileInfo<MachineModuleInfoMachO>();
694
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000695 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000696
697 // Add information about the stub reference to MachOMMI so that the stub
698 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000699 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000700 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000701 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000702 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
703 }
704
705 return SSym;
706}
707
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000708const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
709 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
710 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000711 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000712 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
713 // through a non_lazy_ptr stub instead. One advantage is that it allows the
714 // computation of deltas to final external symbols. Example:
715 //
716 // _extgotequiv:
717 // .long _extfoo
718 //
719 // _delta:
720 // .long _extgotequiv-_delta
721 //
722 // is transformed to:
723 //
724 // _delta:
725 // .long L_extfoo$non_lazy_ptr-(_delta+0)
726 //
727 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
728 // L_extfoo$non_lazy_ptr:
729 // .indirect_symbol _extfoo
730 // .long 0
731 //
732 MachineModuleInfoMachO &MachOMMI =
733 MMI->getObjFileInfo<MachineModuleInfoMachO>();
734 MCContext &Ctx = getContext();
735
736 // The offset must consider the original displacement from the base symbol
737 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
738 Offset = -MV.getConstant();
739 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
740
741 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
742 // non_lazy_ptr stubs.
743 SmallString<128> Name;
744 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000745 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000746 Name += Sym->getName();
747 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000748 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000749
750 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
751 if (!StubSym.getPointer())
752 StubSym = MachineModuleInfoImpl::
753 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
754
755 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000756 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000757 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000758 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000759
760 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000761 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000762
763 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000764 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
765 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000766}
767
Peter Collingbourne94d77862015-11-03 23:40:03 +0000768static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
769 const MCSection &Section) {
770 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
771 return true;
772
773 // If it is not dead stripped, it is safe to use private labels.
774 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
775 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
776 return true;
777
778 return false;
779}
780
781void TargetLoweringObjectFileMachO::getNameWithPrefix(
782 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
783 const TargetMachine &TM) const {
784 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
785 const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
786 bool CannotUsePrivateLabel =
787 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
788 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
789}
790
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000791//===----------------------------------------------------------------------===//
792// COFF
793//===----------------------------------------------------------------------===//
794
Chris Lattner87cffa92010-05-07 17:17:41 +0000795static unsigned
796getCOFFSectionFlags(SectionKind K) {
797 unsigned Flags = 0;
798
Anton Korobeynikove4152302010-07-06 15:24:56 +0000799 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000800 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000801 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000802 else if (K.isText())
803 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000804 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000805 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000806 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000807 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000808 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000809 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
810 COFF::IMAGE_SCN_MEM_READ |
811 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000812 else if (K.isThreadLocal())
813 Flags |=
814 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
815 COFF::IMAGE_SCN_MEM_READ |
816 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000817 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000818 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000819 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
820 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000821 else if (K.isWriteable())
822 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000823 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
824 COFF::IMAGE_SCN_MEM_READ |
825 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000826
827 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000828}
829
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000830static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000831 const Comdat *C = GV->getComdat();
832 assert(C && "expected GV to have a Comdat!");
833
834 StringRef ComdatGVName = C->getName();
835 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
836 if (!ComdatGV)
837 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
838 "' does not exist.");
839
840 if (ComdatGV->getComdat() != C)
841 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000842 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000843
844 return ComdatGV;
845}
846
847static int getSelectionForCOFF(const GlobalValue *GV) {
848 if (const Comdat *C = GV->getComdat()) {
849 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
850 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
851 ComdatKey = GA->getBaseObject();
852 if (ComdatKey == GV) {
853 switch (C->getSelectionKind()) {
854 case Comdat::Any:
855 return COFF::IMAGE_COMDAT_SELECT_ANY;
856 case Comdat::ExactMatch:
857 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
858 case Comdat::Largest:
859 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
860 case Comdat::NoDuplicates:
861 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
862 case Comdat::SameSize:
863 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
864 }
865 } else {
866 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
867 }
David Majnemerdad0a642014-06-27 18:19:56 +0000868 }
869 return 0;
870}
871
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000872MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000873 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
874 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000875 int Selection = 0;
876 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000877 StringRef Name = GV->getSection();
878 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000879 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000880 Selection = getSelectionForCOFF(GV);
881 const GlobalValue *ComdatGV;
882 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
883 ComdatGV = getComdatGVForCOFF(GV);
884 else
885 ComdatGV = GV;
886
887 if (!ComdatGV->hasPrivateLinkage()) {
888 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
889 COMDATSymName = Sym->getName();
890 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
891 } else {
892 Selection = 0;
893 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000894 }
895 return getContext().getCOFFSection(Name,
896 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000897 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000898 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000899 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000900}
901
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000902static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000903 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000904 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000905 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000906 return ".bss";
907 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000908 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000909 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
910 return ".rdata";
911 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000912}
913
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000914MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
915 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
916 const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000917 // If we have -ffunction-sections then we should emit the global value to a
918 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000919 bool EmitUniquedSection;
920 if (Kind.isText())
921 EmitUniquedSection = TM.getFunctionSections();
922 else
923 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000924
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000925 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000926 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000927 unsigned Characteristics = getCOFFSectionFlags(Kind);
928
Daniel Dunbar329d2022010-07-01 20:07:24 +0000929 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000930 int Selection = getSelectionForCOFF(GV);
931 if (!Selection)
932 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
933 const GlobalValue *ComdatGV;
934 if (GV->hasComdat())
935 ComdatGV = getComdatGVForCOFF(GV);
936 else
937 ComdatGV = GV;
938
939 if (!ComdatGV->hasPrivateLinkage()) {
940 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
941 StringRef COMDATSymName = Sym->getName();
942 return getContext().getCOFFSection(Name, Characteristics, Kind,
943 COMDATSymName, Selection);
David Majnemer7db449a2015-03-17 23:54:51 +0000944 } else {
945 SmallString<256> TmpData;
Peter Collingbourne94d77862015-11-03 23:40:03 +0000946 Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +0000947 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
948 Selection);
David Majnemerdad0a642014-06-27 18:19:56 +0000949 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000950 }
951
952 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000953 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000954
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000955 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000956 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000957
David Majnemer597be2d2014-09-22 20:39:23 +0000958 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000959 return ReadOnlySection;
960
David Majnemera9bdb322014-04-08 22:33:40 +0000961 // Note: we claim that common symbols are put in BSSSection, but they are
962 // really emitted with the magic .comm directive, which creates a symbol table
963 // entry but not a section.
964 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000965 return BSSSection;
966
967 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000968}
969
David Majnemer7db449a2015-03-17 23:54:51 +0000970void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Peter Collingbourne94d77862015-11-03 23:40:03 +0000971 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
972 const TargetMachine &TM) const {
973 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +0000974 if (GV->hasPrivateLinkage() &&
975 ((isa<Function>(GV) && TM.getFunctionSections()) ||
976 (isa<GlobalVariable>(GV) && TM.getDataSections())))
977 CannotUsePrivateLabel = true;
978
979 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
980}
981
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000982MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Rafael Espindolaab447e42015-03-11 19:58:37 +0000983 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
984 // If the function can be removed, produce a unique section so that
985 // the table doesn't prevent the removal.
986 const Comdat *C = F.getComdat();
987 bool EmitUniqueSection = TM.getFunctionSections() || C;
988 if (!EmitUniqueSection)
989 return ReadOnlySection;
990
991 // FIXME: we should produce a symbol for F instead.
992 if (F.hasPrivateLinkage())
993 return ReadOnlySection;
994
995 MCSymbol *Sym = TM.getSymbol(&F, Mang);
996 StringRef COMDATSymName = Sym->getName();
997
998 SectionKind Kind = SectionKind::getReadOnly();
999 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1000 unsigned Characteristics = getCOFFSectionFlags(Kind);
1001 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1002
1003 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1004 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
1005}
1006
Reid Klecknerd973ca32013-04-25 19:34:41 +00001007void TargetLoweringObjectFileCOFF::
1008emitModuleFlags(MCStreamer &Streamer,
1009 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +00001010 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001011 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001012
1013 // Look for the "Linker Options" flag, since it's the only one we support.
1014 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1015 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1016 const Module::ModuleFlagEntry &MFE = *i;
1017 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001018 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001019 if (Key == "Linker Options") {
1020 LinkerOptions = cast<MDNode>(Val);
1021 break;
1022 }
1023 }
1024 if (!LinkerOptions)
1025 return;
1026
1027 // Emit the linker options to the linker .drectve section. According to the
1028 // spec, this section is a space-separated string containing flags for linker.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001029 MCSection *Sec = getDrectveSection();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001030 Streamer.SwitchSection(Sec);
1031 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1032 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1033 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1034 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Klecknerd973ca32013-04-25 19:34:41 +00001035 // Lead with a space for consistency with our dllexport implementation.
Michael Kupersteinfc3e6262015-02-16 11:57:17 +00001036 std::string Directive(" ");
1037 Directive.append(MDOption->getString());
1038 Streamer.EmitBytes(Directive);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001039 }
1040 }
1041}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001042
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001043MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001044 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001045 return getContext().getAssociativeCOFFSection(
1046 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001047}
1048
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001049MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001050 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001051 return getContext().getAssociativeCOFFSection(
1052 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001053}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001054
1055void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1056 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1057 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1058 return;
1059
1060 const Triple &TT = getTargetTriple();
1061
1062 if (TT.isKnownWindowsMSVCEnvironment())
1063 OS << " /EXPORT:";
1064 else
1065 OS << " -export:";
1066
1067 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1068 std::string Flag;
1069 raw_string_ostream FlagOS(Flag);
1070 Mang.getNameWithPrefix(FlagOS, GV, false);
1071 FlagOS.flush();
Mehdi Amini5c0fa582015-07-16 06:04:17 +00001072 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
Peter Collingbourneaef36592015-06-29 22:04:09 +00001073 OS << Flag.substr(1);
1074 else
1075 OS << Flag;
1076 } else {
1077 Mang.getNameWithPrefix(OS, GV, false);
1078 }
1079
1080 if (!GV->getValueType()->isFunctionTy()) {
1081 if (TT.isKnownWindowsMSVCEnvironment())
1082 OS << ",DATA";
1083 else
1084 OS << ",data";
1085 }
1086}