blob: bbeb55525277554c4c604b273ccfdfee30d399d3 [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(
Eric Christopher4367c7f2016-09-16 07:33:15 +000053 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000054 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.") +
Eric Christopher4367c7f2016-09-16 07:33:15 +000058 TM.getSymbol(GV, getMangler())->getName());
Logan Chienc0029812014-05-30 16:48:56 +000059 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
Eric Christopher4367c7f2016-09-16 07:33:15 +000060 return TM.getSymbol(GV, getMangler());
Logan Chienc0029812014-05-30 16:48:56 +000061 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 Espindola39897762011-04-27 21:29:52 +000072 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Eric Christopher36e601c2016-07-01 06:07:38 +000073 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
74 ELF::SHT_PROGBITS, Flags, 0);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000075 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000076 Streamer.SwitchSection(Sec);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000077 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000078 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +000079 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +000080 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +000081 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000082
Rafael Espindola39897762011-04-27 21:29:52 +000083 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000084}
85
Rafael Espindola15b26692014-02-09 14:50:44 +000086const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +000087 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
88 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikove42af362012-11-14 01:47:00 +000089
90 if (Encoding & dwarf::DW_EH_PE_indirect) {
91 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
92
Eric Christopher4367c7f2016-09-16 07:33:15 +000093 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +000094
95 // Add information about the stub reference to ELFMMI so that the stub
96 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +000097 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +000098 if (!StubSym.getPointer()) {
Eric Christopher4367c7f2016-09-16 07:33:15 +000099 MCSymbol *Sym = TM.getSymbol(GV, getMangler());
Anton Korobeynikove42af362012-11-14 01:47:00 +0000100 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
101 }
102
103 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000104 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000105 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
106 }
107
Eric Christopher4367c7f2016-09-16 07:33:15 +0000108 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
109 MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000110}
111
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000112static SectionKind
113getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000114 // N.B.: The defaults used in here are no the same ones used in MC.
115 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
116 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000117 // section(".eh_frame") gcc will produce:
118 //
119 // .section .eh_frame,"a",@progbits
Xinliang David Li5f04f922016-01-14 18:09:45 +0000120
121 if (Name == getInstrProfCoverageSectionName(false))
122 return SectionKind::getMetadata();
123
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000124 if (Name.empty() || Name[0] != '.') return K;
125
126 // Some lame default implementation based on some magic section names.
127 if (Name == ".bss" ||
128 Name.startswith(".bss.") ||
129 Name.startswith(".gnu.linkonce.b.") ||
130 Name.startswith(".llvm.linkonce.b.") ||
131 Name == ".sbss" ||
132 Name.startswith(".sbss.") ||
133 Name.startswith(".gnu.linkonce.sb.") ||
134 Name.startswith(".llvm.linkonce.sb."))
135 return SectionKind::getBSS();
136
137 if (Name == ".tdata" ||
138 Name.startswith(".tdata.") ||
139 Name.startswith(".gnu.linkonce.td.") ||
140 Name.startswith(".llvm.linkonce.td."))
141 return SectionKind::getThreadData();
142
143 if (Name == ".tbss" ||
144 Name.startswith(".tbss.") ||
145 Name.startswith(".gnu.linkonce.tb.") ||
146 Name.startswith(".llvm.linkonce.tb."))
147 return SectionKind::getThreadBSS();
148
149 return K;
150}
151
152
153static unsigned getELFSectionType(StringRef Name, SectionKind K) {
154
155 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000156 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000157
158 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000159 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000160
161 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000162 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000163
164 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000165 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000166
Rafael Espindolaaea49582011-01-23 04:28:49 +0000167 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000168}
169
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000170static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000171 unsigned Flags = 0;
172
173 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000174 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000175
176 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000177 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000178
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000179 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000180 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000181
182 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000183 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000184
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000185 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000186 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000187
188 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000189 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000190
191 return Flags;
192}
193
David Majnemerdad0a642014-06-27 18:19:56 +0000194static const Comdat *getELFComdat(const GlobalValue *GV) {
195 const Comdat *C = GV->getComdat();
196 if (!C)
197 return nullptr;
198
199 if (C->getSelectionKind() != Comdat::Any)
200 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
201 C->getName() + "' cannot be lowered.");
202
203 return C;
204}
205
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000206MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000207 const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000208 StringRef SectionName = GV->getSection();
209
210 // Infer section flags from the section name if we can.
211 Kind = getELFKindForNamedSection(SectionName, Kind);
212
David Majnemerdad0a642014-06-27 18:19:56 +0000213 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000214 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000215 if (const Comdat *C = getELFComdat(GV)) {
216 Group = C->getName();
217 Flags |= ELF::SHF_GROUP;
218 }
Chris Lattner80c34592010-04-08 21:34:17 +0000219 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000220 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000221 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000222}
223
Rafael Espindola25d2c202015-02-11 14:44:17 +0000224/// Return the section prefix name used by options FunctionsSections and
225/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000226static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000227 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000228 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000229 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000230 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000231 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000232 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000233 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000234 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000235 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000236 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000237 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000238 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000239 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000240 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000241}
242
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000243static MCSectionELF *
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000244selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
245 SectionKind Kind, Mangler &Mang,
246 const TargetMachine &TM, bool EmitUniqueSection,
247 unsigned Flags, unsigned *NextUniqueID) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000248 unsigned EntrySize = 0;
249 if (Kind.isMergeableCString()) {
250 if (Kind.isMergeable2ByteCString()) {
251 EntrySize = 2;
252 } else if (Kind.isMergeable4ByteCString()) {
253 EntrySize = 4;
254 } else {
255 EntrySize = 1;
256 assert(Kind.isMergeable1ByteCString() && "unknown string width");
257 }
258 } else if (Kind.isMergeableConst()) {
259 if (Kind.isMergeableConst4()) {
260 EntrySize = 4;
261 } else if (Kind.isMergeableConst8()) {
262 EntrySize = 8;
David Majnemer964b70d2016-02-22 22:23:11 +0000263 } else if (Kind.isMergeableConst16()) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000264 EntrySize = 16;
David Majnemer964b70d2016-02-22 22:23:11 +0000265 } else {
266 assert(Kind.isMergeableConst32() && "unknown data width");
267 EntrySize = 32;
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000268 }
269 }
270
Rafael Espindola9075f772015-02-20 23:28:28 +0000271 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000272 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000273 Flags |= ELF::SHF_GROUP;
274 Group = C->getName();
275 }
276
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000277 bool UniqueSectionNames = TM.getUniqueSectionNames();
278 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000279 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000280 // We also need alignment here.
281 // FIXME: this is getting the alignment of the character, not the
282 // alignment of the global!
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000283 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
284 cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000285
Rafael Espindolaba31e272015-01-29 17:33:21 +0000286 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000287 Name = SizeSpec + utostr(Align);
288 } else if (Kind.isMergeableConst()) {
289 Name = ".rodata.cst";
290 Name += utostr(EntrySize);
291 } else {
292 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000293 }
Easwaran Raman01d98ba2016-05-16 23:59:04 +0000294 // FIXME: Extend the section prefix to include hotness catagories such as .hot
295 // or .unlikely for functions.
Dehao Chenf84b6302016-02-23 03:39:24 +0000296
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 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000301 unsigned UniqueID = MCContext::GenericSectionID;
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000302 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(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000311 const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000312 unsigned Flags = getELFSectionFlags(Kind);
313
314 // If we have -ffunction-section or -fdata-section then we should emit the
315 // global value to a uniqued section specifically for it.
316 bool EmitUniqueSection = false;
317 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
318 if (Kind.isText())
319 EmitUniqueSection = TM.getFunctionSections();
320 else
321 EmitUniqueSection = TM.getDataSections();
322 }
323 EmitUniqueSection |= GV->hasComdat();
324
Eric Christopher4367c7f2016-09-16 07:33:15 +0000325 return selectELFSectionForGlobal(getContext(), GV, Kind, getMangler(), TM,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000326 EmitUniqueSection, Flags, &NextUniqueID);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000327}
328
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000329MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000330 const Function &F, const TargetMachine &TM) const {
Rafael Espindola29786d42015-02-12 17:16:46 +0000331 // If the function can be removed, produce a unique section so that
332 // the table doesn't prevent the removal.
333 const Comdat *C = F.getComdat();
334 bool EmitUniqueSection = TM.getFunctionSections() || C;
335 if (!EmitUniqueSection)
336 return ReadOnlySection;
337
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000338 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Eric Christopher4367c7f2016-09-16 07:33:15 +0000339 getMangler(), TM, EmitUniqueSection, ELF::SHF_ALLOC,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000340 &NextUniqueID);
Rafael Espindola29786d42015-02-12 17:16:46 +0000341}
342
Rafael Espindoladf195192015-02-17 23:34:51 +0000343bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
344 bool UsesLabelDifference, const Function &F) const {
345 // We can always create relative relocations, so use another section
346 // that can be marked non-executable.
347 return false;
348}
349
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000350/// Given a mergeable constant with the specified size and relocation
351/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000352MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000353 const DataLayout &DL, SectionKind Kind, const Constant *C,
354 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000355 if (Kind.isMergeableConst4() && MergeableConst4Section)
356 return MergeableConst4Section;
357 if (Kind.isMergeableConst8() && MergeableConst8Section)
358 return MergeableConst8Section;
359 if (Kind.isMergeableConst16() && MergeableConst16Section)
360 return MergeableConst16Section;
David Majnemer964b70d2016-02-22 22:23:11 +0000361 if (Kind.isMergeableConst32() && MergeableConst32Section)
362 return MergeableConst32Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000363 if (Kind.isReadOnly())
364 return ReadOnlySection;
365
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000366 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
367 return DataRelROSection;
368}
369
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000370static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
371 bool IsCtor, unsigned Priority,
372 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000373 std::string Name;
374 unsigned Type;
375 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000376 StringRef COMDAT = KeySym ? KeySym->getName() : "";
377
378 if (KeySym)
379 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000380
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000381 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000382 if (IsCtor) {
383 Type = ELF::SHT_INIT_ARRAY;
384 Name = ".init_array";
385 } else {
386 Type = ELF::SHT_FINI_ARRAY;
387 Name = ".fini_array";
388 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000389 if (Priority != 65535) {
390 Name += '.';
391 Name += utostr(Priority);
392 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000393 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000394 // The default scheme is .ctor / .dtor, so we have to invert the priority
395 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000396 if (IsCtor)
397 Name = ".ctors";
398 else
399 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000400 if (Priority != 65535) {
401 Name += '.';
402 Name += utostr(65535 - Priority);
403 }
404 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000405 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000406
Rafael Espindolaba31e272015-01-29 17:33:21 +0000407 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000408}
409
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000410MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000411 unsigned Priority, const MCSymbol *KeySym) const {
412 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
413 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000414}
415
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000416MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000417 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000418 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
419 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000420}
421
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000422const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000423 const GlobalValue *LHS, const GlobalValue *RHS,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000424 const TargetMachine &TM) const {
425 // We may only use a PLT-relative relocation to refer to unnamed_addr
426 // functions.
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000427 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000428 return nullptr;
429
430 // Basic sanity checks.
431 if (LHS->getType()->getPointerAddressSpace() != 0 ||
432 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
433 RHS->isThreadLocal())
434 return nullptr;
435
436 return MCBinaryExpr::createSub(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000437 MCSymbolRefExpr::create(TM.getSymbol(LHS, getMangler()), PLTRelativeVariantKind,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000438 getContext()),
Eric Christopher4367c7f2016-09-16 07:33:15 +0000439 MCSymbolRefExpr::create(TM.getSymbol(RHS, getMangler()), getContext()),
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000440 getContext());
441}
442
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000443void
444TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
445 UseInitArray = UseInitArray_;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000446 MCContext &Ctx = getContext();
447 if (!UseInitArray) {
448 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
449 ELF::SHF_ALLOC | ELF::SHF_WRITE);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000450
Rafael Espindola46fa2312016-08-29 12:33:42 +0000451 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
452 ELF::SHF_ALLOC | ELF::SHF_WRITE);
453 return;
454 }
455
456 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
457 ELF::SHF_WRITE | ELF::SHF_ALLOC);
458 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
459 ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000460}
461
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000462//===----------------------------------------------------------------------===//
463// MachO
464//===----------------------------------------------------------------------===//
465
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000466TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
467 : TargetLoweringObjectFile() {
468 SupportIndirectSymViaGOTPCRel = true;
469}
470
Rafael Espindola46fa2312016-08-29 12:33:42 +0000471void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
472 const TargetMachine &TM) {
473 TargetLoweringObjectFile::Initialize(Ctx, TM);
Rafael Espindola412a5292016-08-29 12:47:22 +0000474 if (TM.getRelocationModel() == Reloc::Static) {
Rafael Espindola46fa2312016-08-29 12:33:42 +0000475 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
476 SectionKind::getData());
477 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
478 SectionKind::getData());
479 } else {
480 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
481 MachO::S_MOD_INIT_FUNC_POINTERS,
482 SectionKind::getData());
483 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
484 MachO::S_MOD_TERM_FUNC_POINTERS,
485 SectionKind::getData());
486 }
487}
488
Daniel Dunbar95856122013-01-18 19:37:00 +0000489/// emitModuleFlags - Perform code emission for module flags.
Eric Christopher4367c7f2016-09-16 07:33:15 +0000490void TargetLoweringObjectFileMachO::emitModuleFlags(
491 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
492 const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000493 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000494 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000495 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000496 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000497
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000498 for (const auto &MFE : ModuleFlags) {
Bill Wendling06df7722012-02-14 21:28:13 +0000499 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000500 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000501 continue;
502
Bill Wendling734909a2012-02-15 22:36:15 +0000503 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000504 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000505
Daniel Dunbar95856122013-01-18 19:37:00 +0000506 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000507 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000508 } else if (Key == "Objective-C Garbage Collection" ||
509 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000510 Key == "Objective-C Is Simulated" ||
Manman Renc77e0ff2016-01-29 23:51:00 +0000511 Key == "Objective-C Class Properties" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000512 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000513 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000514 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000515 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000516 } else if (Key == "Linker Options") {
517 LinkerOptions = cast<MDNode>(Val);
518 }
519 }
520
521 // Emit the linker options if present.
522 if (LinkerOptions) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000523 for (const auto &Option : LinkerOptions->operands()) {
Daniel Dunbar95856122013-01-18 19:37:00 +0000524 SmallVector<std::string, 4> StrOptions;
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000525 for (const auto &Piece : cast<MDNode>(Option)->operands())
526 StrOptions.push_back(cast<MDString>(Piece)->getString());
Daniel Dunbar95856122013-01-18 19:37:00 +0000527 Streamer.EmitLinkerOptions(StrOptions);
528 }
Bill Wendling06df7722012-02-14 21:28:13 +0000529 }
530
Bill Wendling734909a2012-02-15 22:36:15 +0000531 // The section is mandatory. If we don't have it, then we don't have GC info.
532 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000533
Bill Wendling734909a2012-02-15 22:36:15 +0000534 StringRef Segment, Section;
535 unsigned TAA = 0, StubSize = 0;
536 bool TAAParsed;
537 std::string ErrorCode =
538 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
539 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000540 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000541 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000542 report_fatal_error("Invalid section specifier '" + Section + "': " +
543 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000544
Bill Wendling734909a2012-02-15 22:36:15 +0000545 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000546 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000547 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000548 Streamer.SwitchSection(S);
549 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000550 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000551 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000552 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000553 Streamer.AddBlankLine();
554}
555
David Majnemerdad0a642014-06-27 18:19:56 +0000556static void checkMachOComdat(const GlobalValue *GV) {
557 const Comdat *C = GV->getComdat();
558 if (!C)
559 return;
560
561 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
562 "' cannot be lowered.");
563}
564
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000565MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000566 const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000567 // Parse the section specifier and create it if valid.
568 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000569 unsigned TAA = 0, StubSize = 0;
570 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000571
572 checkMachOComdat(GV);
573
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000574 std::string ErrorCode =
575 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000576 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000577 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000578 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000579 report_fatal_error("Global variable '" + GV->getName() +
580 "' has an invalid section specifier '" +
581 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000582 }
583
584 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000585 MCSectionMachO *S =
586 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000587
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000588 // If TAA wasn't set by ParseSectionSpecifier() above,
589 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000590 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000591 TAA = S->getTypeAndAttributes();
592
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000593 // Okay, now that we got the section, verify that the TAA & StubSize agree.
594 // If the user declared multiple globals with different section flags, we need
595 // to reject it here.
596 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000597 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000598 report_fatal_error("Global variable '" + GV->getName() +
599 "' section type or attributes does not match previous"
600 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000601 }
602
603 return S;
604}
605
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000606MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000607 const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000608 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000609
610 // Handle thread local data.
611 if (Kind.isThreadBSS()) return TLSBSSSection;
612 if (Kind.isThreadData()) return TLSDataSection;
613
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000614 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000615 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
616
617 // If this is weak/linkonce, put this in a coalescable section, either in text
618 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000619 if (GV->isWeakForLinker()) {
620 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000621 return ConstTextCoalSection;
622 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000623 }
624
625 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000626 if (Kind.isMergeable1ByteCString() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000627 GV->getParent()->getDataLayout().getPreferredAlignment(
628 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000629 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000630
Chris Lattneref2f8042010-03-07 04:28:09 +0000631 // Do not put 16-bit arrays in the UString section if they have an
632 // externally visible label, this runs into issues with certain linker
633 // versions.
634 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000635 GV->getParent()->getDataLayout().getPreferredAlignment(
636 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000637 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000638
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000639 // With MachO only variables whose corresponding symbol starts with 'l' or
640 // 'L' can be merged, so we only try merging GVs with private linkage.
641 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000642 if (Kind.isMergeableConst4())
643 return FourByteConstantSection;
644 if (Kind.isMergeableConst8())
645 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000646 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000647 return SixteenByteConstantSection;
648 }
649
650 // Otherwise, if it is readonly, but not something we can specially optimize,
651 // just drop it in .const.
652 if (Kind.isReadOnly())
653 return ReadOnlySection;
654
655 // If this is marked const, put it into a const section. But if the dynamic
656 // linker needs to write to it, put it in the data segment.
657 if (Kind.isReadOnlyWithRel())
658 return ConstDataSection;
659
660 // Put zero initialized globals with strong external linkage in the
661 // DATA, __common section with the .zerofill directive.
662 if (Kind.isBSSExtern())
663 return DataCommonSection;
664
665 // Put zero initialized globals with local linkage in __DATA,__bss directive
666 // with the .zerofill directive (aka .lcomm).
667 if (Kind.isBSSLocal())
668 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000669
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000670 // Otherwise, just drop the variable in the normal data section.
671 return DataSection;
672}
673
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000674MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000675 const DataLayout &DL, SectionKind Kind, const Constant *C,
676 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000677 // If this constant requires a relocation, we have to put it in the data
678 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000679 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000680 return ConstDataSection;
681
682 if (Kind.isMergeableConst4())
683 return FourByteConstantSection;
684 if (Kind.isMergeableConst8())
685 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000686 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000687 return SixteenByteConstantSection;
688 return ReadOnlySection; // .const
689}
690
Rafael Espindola15b26692014-02-09 14:50:44 +0000691const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000692 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
693 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000694 // The mach-o version of this method defaults to returning a stub reference.
695
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000696 if (Encoding & DW_EH_PE_indirect) {
697 MachineModuleInfoMachO &MachOMMI =
698 MMI->getObjFileInfo<MachineModuleInfoMachO>();
699
Eric Christopher4367c7f2016-09-16 07:33:15 +0000700 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000701
702 // Add information about the stub reference to MachOMMI so that the stub
703 // gets emitted by the asmprinter.
Rafael Espindola712f9572016-05-17 16:01:32 +0000704 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000705 if (!StubSym.getPointer()) {
Eric Christopher4367c7f2016-09-16 07:33:15 +0000706 MCSymbol *Sym = TM.getSymbol(GV, getMangler());
Chris Lattner2ea586b2010-03-15 20:37:38 +0000707 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000708 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000709
710 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000711 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000712 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000713 }
714
Eric Christopher4367c7f2016-09-16 07:33:15 +0000715 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
716 MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000717}
718
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000719MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000720 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000721 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000722 // The mach-o version of this method defaults to returning a stub reference.
723 MachineModuleInfoMachO &MachOMMI =
724 MMI->getObjFileInfo<MachineModuleInfoMachO>();
725
Eric Christopher4367c7f2016-09-16 07:33:15 +0000726 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000727
728 // Add information about the stub reference to MachOMMI so that the stub
729 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000730 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000731 if (!StubSym.getPointer()) {
Eric Christopher4367c7f2016-09-16 07:33:15 +0000732 MCSymbol *Sym = TM.getSymbol(GV, getMangler());
Rafael Espindola08704342011-04-27 23:08:15 +0000733 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
734 }
735
736 return SSym;
737}
738
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000739const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
740 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
741 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000742 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000743 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
744 // through a non_lazy_ptr stub instead. One advantage is that it allows the
745 // computation of deltas to final external symbols. Example:
746 //
747 // _extgotequiv:
748 // .long _extfoo
749 //
750 // _delta:
751 // .long _extgotequiv-_delta
752 //
753 // is transformed to:
754 //
755 // _delta:
756 // .long L_extfoo$non_lazy_ptr-(_delta+0)
757 //
758 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
759 // L_extfoo$non_lazy_ptr:
760 // .indirect_symbol _extfoo
761 // .long 0
762 //
763 MachineModuleInfoMachO &MachOMMI =
764 MMI->getObjFileInfo<MachineModuleInfoMachO>();
765 MCContext &Ctx = getContext();
766
767 // The offset must consider the original displacement from the base symbol
768 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
769 Offset = -MV.getConstant();
770 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
771
772 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
773 // non_lazy_ptr stubs.
774 SmallString<128> Name;
775 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000776 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000777 Name += Sym->getName();
778 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000779 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000780
781 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
782 if (!StubSym.getPointer())
783 StubSym = MachineModuleInfoImpl::
784 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
785
786 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000787 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000788 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000789 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000790
791 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000792 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000793
794 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000795 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
796 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000797}
798
Peter Collingbourne94d77862015-11-03 23:40:03 +0000799static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
800 const MCSection &Section) {
801 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
802 return true;
803
804 // If it is not dead stripped, it is safe to use private labels.
805 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
806 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
807 return true;
808
809 return false;
810}
811
812void TargetLoweringObjectFileMachO::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000813 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +0000814 const TargetMachine &TM) const {
815 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
Eric Christopher4367c7f2016-09-16 07:33:15 +0000816 const MCSection *TheSection = SectionForGlobal(GV, GVKind, TM);
Peter Collingbourne94d77862015-11-03 23:40:03 +0000817 bool CannotUsePrivateLabel =
818 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
Eric Christopher4367c7f2016-09-16 07:33:15 +0000819 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
Peter Collingbourne94d77862015-11-03 23:40:03 +0000820}
821
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000822//===----------------------------------------------------------------------===//
823// COFF
824//===----------------------------------------------------------------------===//
825
Chris Lattner87cffa92010-05-07 17:17:41 +0000826static unsigned
Renato Golinef3eb062016-06-27 14:42:20 +0000827getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
Chris Lattner87cffa92010-05-07 17:17:41 +0000828 unsigned Flags = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000829 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
Chris Lattner87cffa92010-05-07 17:17:41 +0000830
Anton Korobeynikove4152302010-07-06 15:24:56 +0000831 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000832 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000833 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000834 else if (K.isText())
835 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000836 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000837 COFF::IMAGE_SCN_MEM_READ |
Renato Golinef3eb062016-06-27 14:42:20 +0000838 COFF::IMAGE_SCN_CNT_CODE |
839 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
David Majnemerb8dbebb2014-09-20 07:31:46 +0000840 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000841 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000842 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
843 COFF::IMAGE_SCN_MEM_READ |
844 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000845 else if (K.isThreadLocal())
846 Flags |=
847 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
848 COFF::IMAGE_SCN_MEM_READ |
849 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000850 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000851 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000852 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
853 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000854 else if (K.isWriteable())
855 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000856 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
857 COFF::IMAGE_SCN_MEM_READ |
858 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000859
860 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000861}
862
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000863static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000864 const Comdat *C = GV->getComdat();
865 assert(C && "expected GV to have a Comdat!");
866
867 StringRef ComdatGVName = C->getName();
868 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
869 if (!ComdatGV)
870 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
871 "' does not exist.");
872
873 if (ComdatGV->getComdat() != C)
874 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000875 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000876
877 return ComdatGV;
878}
879
880static int getSelectionForCOFF(const GlobalValue *GV) {
881 if (const Comdat *C = GV->getComdat()) {
882 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
883 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
884 ComdatKey = GA->getBaseObject();
885 if (ComdatKey == GV) {
886 switch (C->getSelectionKind()) {
887 case Comdat::Any:
888 return COFF::IMAGE_COMDAT_SELECT_ANY;
889 case Comdat::ExactMatch:
890 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
891 case Comdat::Largest:
892 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
893 case Comdat::NoDuplicates:
894 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
895 case Comdat::SameSize:
896 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
897 }
898 } else {
899 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
900 }
David Majnemerdad0a642014-06-27 18:19:56 +0000901 }
902 return 0;
903}
904
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000905MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000906 const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000907 int Selection = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000908 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000909 StringRef Name = GV->getSection();
910 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000911 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000912 Selection = getSelectionForCOFF(GV);
913 const GlobalValue *ComdatGV;
914 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
915 ComdatGV = getComdatGVForCOFF(GV);
916 else
917 ComdatGV = GV;
918
919 if (!ComdatGV->hasPrivateLinkage()) {
Eric Christopher4367c7f2016-09-16 07:33:15 +0000920 MCSymbol *Sym = TM.getSymbol(ComdatGV, getMangler());
David Majnemerdad0a642014-06-27 18:19:56 +0000921 COMDATSymName = Sym->getName();
922 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
923 } else {
924 Selection = 0;
925 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000926 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000927
928 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000929 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000930}
931
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000932static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000933 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000934 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000935 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000936 return ".bss";
937 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000938 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000939 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
940 return ".rdata";
941 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000942}
943
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000944MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000945 const GlobalValue *GV, SectionKind Kind, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000946 // If we have -ffunction-sections then we should emit the global value to a
947 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000948 bool EmitUniquedSection;
949 if (Kind.isText())
950 EmitUniquedSection = TM.getFunctionSections();
951 else
952 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000953
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000954 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000955 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +0000956 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Chris Lattner02844932010-05-07 21:49:09 +0000957
Daniel Dunbar329d2022010-07-01 20:07:24 +0000958 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000959 int Selection = getSelectionForCOFF(GV);
960 if (!Selection)
961 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
962 const GlobalValue *ComdatGV;
963 if (GV->hasComdat())
964 ComdatGV = getComdatGVForCOFF(GV);
965 else
966 ComdatGV = GV;
967
Reid Kleckner97837b72016-05-02 23:22:18 +0000968 unsigned UniqueID = MCContext::GenericSectionID;
969 if (EmitUniquedSection)
970 UniqueID = NextUniqueID++;
971
David Majnemerdad0a642014-06-27 18:19:56 +0000972 if (!ComdatGV->hasPrivateLinkage()) {
Eric Christopher4367c7f2016-09-16 07:33:15 +0000973 MCSymbol *Sym = TM.getSymbol(ComdatGV, getMangler());
David Majnemerdad0a642014-06-27 18:19:56 +0000974 StringRef COMDATSymName = Sym->getName();
975 return getContext().getCOFFSection(Name, Characteristics, Kind,
Reid Kleckner97837b72016-05-02 23:22:18 +0000976 COMDATSymName, Selection, UniqueID);
David Majnemer7db449a2015-03-17 23:54:51 +0000977 } else {
978 SmallString<256> TmpData;
Eric Christopher4367c7f2016-09-16 07:33:15 +0000979 getMangler().getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +0000980 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
Reid Kleckner97837b72016-05-02 23:22:18 +0000981 Selection, UniqueID);
David Majnemerdad0a642014-06-27 18:19:56 +0000982 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000983 }
984
985 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000986 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000987
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000988 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000989 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000990
David Majnemer597be2d2014-09-22 20:39:23 +0000991 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000992 return ReadOnlySection;
993
David Majnemera9bdb322014-04-08 22:33:40 +0000994 // Note: we claim that common symbols are put in BSSSection, but they are
995 // really emitted with the magic .comm directive, which creates a symbol table
996 // entry but not a section.
997 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000998 return BSSSection;
999
1000 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001001}
1002
David Majnemer7db449a2015-03-17 23:54:51 +00001003void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001004 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001005 const TargetMachine &TM) const {
1006 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +00001007 if (GV->hasPrivateLinkage() &&
1008 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1009 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1010 CannotUsePrivateLabel = true;
1011
Eric Christopher4367c7f2016-09-16 07:33:15 +00001012 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
David Majnemer7db449a2015-03-17 23:54:51 +00001013}
1014
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001015MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001016 const Function &F, const TargetMachine &TM) const {
Rafael Espindolaab447e42015-03-11 19:58:37 +00001017 // If the function can be removed, produce a unique section so that
1018 // the table doesn't prevent the removal.
1019 const Comdat *C = F.getComdat();
1020 bool EmitUniqueSection = TM.getFunctionSections() || C;
1021 if (!EmitUniqueSection)
1022 return ReadOnlySection;
1023
1024 // FIXME: we should produce a symbol for F instead.
1025 if (F.hasPrivateLinkage())
1026 return ReadOnlySection;
1027
Eric Christopher4367c7f2016-09-16 07:33:15 +00001028 MCSymbol *Sym = TM.getSymbol(&F, getMangler());
Rafael Espindolaab447e42015-03-11 19:58:37 +00001029 StringRef COMDATSymName = Sym->getName();
1030
1031 SectionKind Kind = SectionKind::getReadOnly();
1032 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001033 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001034 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Reid Kleckner97837b72016-05-02 23:22:18 +00001035 unsigned UniqueID = NextUniqueID++;
Rafael Espindolaab447e42015-03-11 19:58:37 +00001036
1037 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Reid Kleckner97837b72016-05-02 23:22:18 +00001038 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001039}
1040
Eric Christopher4367c7f2016-09-16 07:33:15 +00001041void TargetLoweringObjectFileCOFF::emitModuleFlags(
1042 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1043 const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001044 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001045
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001046 for (const auto &MFE : ModuleFlags) {
Reid Klecknerd973ca32013-04-25 19:34:41 +00001047 StringRef Key = MFE.Key->getString();
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001048 if (Key == "Linker Options")
1049 LinkerOptions = cast<MDNode>(MFE.Val);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001050 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001051
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001052 if (LinkerOptions) {
1053 // Emit the linker options to the linker .drectve section. According to the
1054 // spec, this section is a space-separated string containing flags for
1055 // linker.
1056 MCSection *Sec = getDrectveSection();
1057 Streamer.SwitchSection(Sec);
1058 for (const auto &Option : LinkerOptions->operands()) {
1059 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1060 // Lead with a space for consistency with our dllexport implementation.
1061 std::string Directive(" ");
1062 Directive.append(cast<MDString>(Piece)->getString());
1063 Streamer.EmitBytes(Directive);
1064 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001065 }
1066 }
1067}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001068
Rafael Espindola46fa2312016-08-29 12:33:42 +00001069void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1070 const TargetMachine &TM) {
1071 TargetLoweringObjectFile::Initialize(Ctx, TM);
1072 const Triple &T = TM.getTargetTriple();
1073 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1074 StaticCtorSection =
1075 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1076 COFF::IMAGE_SCN_MEM_READ,
1077 SectionKind::getReadOnly());
1078 StaticDtorSection =
1079 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1080 COFF::IMAGE_SCN_MEM_READ,
1081 SectionKind::getReadOnly());
1082 } else {
1083 StaticCtorSection = Ctx.getCOFFSection(
1084 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1085 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1086 SectionKind::getData());
1087 StaticDtorSection = Ctx.getCOFFSection(
1088 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1089 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1090 SectionKind::getData());
1091 }
1092}
1093
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001094MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001095 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001096 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001097 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001098}
1099
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001100MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001101 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001102 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001103 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001104}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001105
1106void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001107 raw_ostream &OS, const GlobalValue *GV) const {
Peter Collingbourneaef36592015-06-29 22:04:09 +00001108 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1109 return;
1110
1111 const Triple &TT = getTargetTriple();
1112
1113 if (TT.isKnownWindowsMSVCEnvironment())
1114 OS << " /EXPORT:";
1115 else
1116 OS << " -export:";
1117
1118 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1119 std::string Flag;
1120 raw_string_ostream FlagOS(Flag);
Eric Christopher4367c7f2016-09-16 07:33:15 +00001121 getMangler().getNameWithPrefix(FlagOS, GV, false);
Peter Collingbourneaef36592015-06-29 22:04:09 +00001122 FlagOS.flush();
Mehdi Amini5c0fa582015-07-16 06:04:17 +00001123 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
Peter Collingbourneaef36592015-06-29 22:04:09 +00001124 OS << Flag.substr(1);
1125 else
1126 OS << Flag;
1127 } else {
Eric Christopher4367c7f2016-09-16 07:33:15 +00001128 getMangler().getNameWithPrefix(OS, GV, false);
Peter Collingbourneaef36592015-06-29 22:04:09 +00001129 }
1130
1131 if (!GV->getValueType()->isFunctionTy()) {
1132 if (TT.isKnownWindowsMSVCEnvironment())
1133 OS << ",DATA";
1134 else
1135 OS << ",data";
1136 }
1137}