blob: a89769f0535211ce03cd8709141069aa4d2a18ec [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"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000027#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000029#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/MC/MCSectionELF.h"
31#include "llvm/MC/MCSectionMachO.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000032#include "llvm/MC/MCStreamer.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000033#include "llvm/MC/MCSymbol.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000034#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000035#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000036#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000038#include "llvm/Target/TargetLowering.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000039#include "llvm/Target/TargetMachine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000040#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000041using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000042using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000043
44//===----------------------------------------------------------------------===//
45// ELF
46//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000047
Rafael Espindoladaeafb42014-02-19 17:23:20 +000048MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000051 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000052 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000053 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000054 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000055 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
56 return TM.getSymbol(GV, Mang);
57 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +000058}
59
60void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61 const TargetMachine &TM,
Rafael Espindola08704342011-04-27 23:08:15 +000062 const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000063 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
Rafael Espindola39897762011-04-27 21:29:52 +000066 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000068 StringRef Prefix = ".data.";
69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-04-27 21:29:52 +000070 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
71 const MCSection *Sec = getContext().getELFSection(NameData,
72 ELF::SHT_PROGBITS,
73 Flags,
74 SectionKind::getDataRel(),
75 0, Label->getName());
Eric Christopherd9134482014-08-04 21:25:23 +000076 unsigned Size = TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000077 Streamer.SwitchSection(Sec);
Eric Christopherd9134482014-08-04 21:25:23 +000078 Streamer.EmitValueToAlignment(
79 TM.getSubtargetImpl()->getDataLayout()->getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000080 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
David Chisnall8fa17162012-02-17 16:05:50 +000081 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
Rafael Espindola39897762011-04-27 21:29:52 +000082 Streamer.EmitELFSize(Label, E);
83 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::
107 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
108 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
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000123 if (Name.empty() || Name[0] != '.') return K;
124
125 // Some lame default implementation based on some magic section names.
126 if (Name == ".bss" ||
127 Name.startswith(".bss.") ||
128 Name.startswith(".gnu.linkonce.b.") ||
129 Name.startswith(".llvm.linkonce.b.") ||
130 Name == ".sbss" ||
131 Name.startswith(".sbss.") ||
132 Name.startswith(".gnu.linkonce.sb.") ||
133 Name.startswith(".llvm.linkonce.sb."))
134 return SectionKind::getBSS();
135
136 if (Name == ".tdata" ||
137 Name.startswith(".tdata.") ||
138 Name.startswith(".gnu.linkonce.td.") ||
139 Name.startswith(".llvm.linkonce.td."))
140 return SectionKind::getThreadData();
141
142 if (Name == ".tbss" ||
143 Name.startswith(".tbss.") ||
144 Name.startswith(".gnu.linkonce.tb.") ||
145 Name.startswith(".llvm.linkonce.tb."))
146 return SectionKind::getThreadBSS();
147
148 return K;
149}
150
151
152static unsigned getELFSectionType(StringRef Name, SectionKind K) {
153
154 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000155 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000156
157 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000158 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000159
160 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000161 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000162
163 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000164 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000165
Rafael Espindolaaea49582011-01-23 04:28:49 +0000166 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000167}
168
169
170static unsigned
171getELFSectionFlags(SectionKind K) {
172 unsigned Flags = 0;
173
174 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000175 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000176
177 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000178 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000179
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000180 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000181 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000182
183 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000184 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000185
186 // K.isMergeableConst() is left out to honour PR4650
187 if (K.isMergeableCString() || K.isMergeableConst4() ||
188 K.isMergeableConst8() || K.isMergeableConst16())
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 Espindoladaeafb42014-02-19 17:23:20 +0000209const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
210 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 = "";
218 unsigned Flags = getELFSectionFlags(Kind);
219 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,
225 Kind, /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000226}
227
Chris Lattner5b212a32010-04-13 00:36:43 +0000228/// getSectionPrefixForGlobal - Return the section prefix name used by options
229/// FunctionsSections and DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000230static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Chris Lattner5b212a32010-04-13 00:36:43 +0000231 if (Kind.isText()) return ".text.";
232 if (Kind.isReadOnly()) return ".rodata.";
Anton Korobeynikova22828e2012-02-23 10:36:04 +0000233 if (Kind.isBSS()) return ".bss.";
Chris Lattner5b212a32010-04-13 00:36:43 +0000234
235 if (Kind.isThreadData()) return ".tdata.";
236 if (Kind.isThreadBSS()) return ".tbss.";
237
238 if (Kind.isDataNoRel()) return ".data.";
239 if (Kind.isDataRelLocal()) return ".data.rel.local.";
240 if (Kind.isDataRel()) return ".data.rel.";
241 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
242
243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
244 return ".data.rel.ro.";
245}
246
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000247const MCSection *TargetLoweringObjectFileELF::
248SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000249 Mangler &Mang, const TargetMachine &TM) const {
Chris Lattner5b212a32010-04-13 00:36:43 +0000250 // If we have -ffunction-section or -fdata-section then we should emit the
251 // global value to a uniqued section specifically for it.
252 bool EmitUniquedSection;
253 if (Kind.isText())
254 EmitUniquedSection = TM.getFunctionSections();
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000255 else
Chris Lattner5b212a32010-04-13 00:36:43 +0000256 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000257
258 // If this global is linkonce/weak and the target handles this by emitting it
259 // into a 'uniqued' section name, create and return the section now.
David Majnemerdad0a642014-06-27 18:19:56 +0000260 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
Anton Korobeynikova22828e2012-02-23 10:36:04 +0000261 !Kind.isCommon()) {
David Majnemer102ff692014-06-24 16:01:53 +0000262 StringRef Prefix = getSectionPrefixForGlobal(Kind);
Chris Lattner5b212a32010-04-13 00:36:43 +0000263
David Majnemer102ff692014-06-24 16:01:53 +0000264 SmallString<128> Name(Prefix);
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000265 TM.getNameWithPrefix(Name, GV, Mang, true);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000266
Rafael Espindola70d80152011-02-14 22:23:49 +0000267 StringRef Group = "";
268 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000269 if (GV->isWeakForLinker() || GV->hasComdat()) {
270 if (const Comdat *C = getELFComdat(GV))
271 Group = C->getName();
272 else
273 Group = Name.substr(Prefix.size());
Rafael Espindola70d80152011-02-14 22:23:49 +0000274 Flags |= ELF::SHF_GROUP;
275 }
276
Chris Lattner80c34592010-04-08 21:34:17 +0000277 return getContext().getELFSection(Name.str(),
278 getELFSectionType(Name.str(), Kind),
Rafael Espindola70d80152011-02-14 22:23:49 +0000279 Flags, Kind, 0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000280 }
281
282 if (Kind.isText()) return TextSection;
283
284 if (Kind.isMergeable1ByteCString() ||
285 Kind.isMergeable2ByteCString() ||
286 Kind.isMergeable4ByteCString()) {
287
288 // We also need alignment here.
289 // FIXME: this is getting the alignment of the character, not the
290 // alignment of the global!
291 unsigned Align =
Eric Christopherd9134482014-08-04 21:25:23 +0000292 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
293 cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000294
295 const char *SizeSpec = ".rodata.str1.";
296 if (Kind.isMergeable2ByteCString())
297 SizeSpec = ".rodata.str2.";
298 else if (Kind.isMergeable4ByteCString())
299 SizeSpec = ".rodata.str4.";
300 else
301 assert(Kind.isMergeable1ByteCString() && "unknown string width");
302
303
304 std::string Name = SizeSpec + utostr(Align);
Rafael Espindolaaea49582011-01-23 04:28:49 +0000305 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000306 ELF::SHF_ALLOC |
307 ELF::SHF_MERGE |
308 ELF::SHF_STRINGS,
Chris Lattner80c34592010-04-08 21:34:17 +0000309 Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000310 }
311
312 if (Kind.isMergeableConst()) {
313 if (Kind.isMergeableConst4() && MergeableConst4Section)
314 return MergeableConst4Section;
315 if (Kind.isMergeableConst8() && MergeableConst8Section)
316 return MergeableConst8Section;
317 if (Kind.isMergeableConst16() && MergeableConst16Section)
318 return MergeableConst16Section;
319 return ReadOnlySection; // .const
320 }
321
322 if (Kind.isReadOnly()) return ReadOnlySection;
323
324 if (Kind.isThreadData()) return TLSDataSection;
325 if (Kind.isThreadBSS()) return TLSBSSSection;
326
327 // Note: we claim that common symbols are put in BSSSection, but they are
328 // really emitted with the magic .comm directive, which creates a symbol table
329 // entry but not a section.
330 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
331
332 if (Kind.isDataNoRel()) return DataSection;
333 if (Kind.isDataRelLocal()) return DataRelLocalSection;
334 if (Kind.isDataRel()) return DataRelSection;
335 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
336
337 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
338 return DataRelROSection;
339}
340
341/// getSectionForConstant - Given a mergeable constant with the
342/// specified size and relocation information, return a section that it
343/// should be placed in.
David Majnemer8bce66b2014-07-14 22:57:27 +0000344const MCSection *
345TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
346 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000347 if (Kind.isMergeableConst4() && MergeableConst4Section)
348 return MergeableConst4Section;
349 if (Kind.isMergeableConst8() && MergeableConst8Section)
350 return MergeableConst8Section;
351 if (Kind.isMergeableConst16() && MergeableConst16Section)
352 return MergeableConst16Section;
353 if (Kind.isReadOnly())
354 return ReadOnlySection;
355
356 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
357 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
358 return DataRelROSection;
359}
360
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000361const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000362 unsigned Priority, const MCSymbol *KeySym) const {
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000363 // The default scheme is .ctor / .dtor, so we have to invert the priority
364 // numbering.
365 if (Priority == 65535)
366 return StaticCtorSection;
367
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000368 if (UseInitArray) {
369 std::string Name = std::string(".init_array.") + utostr(Priority);
370 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
371 ELF::SHF_ALLOC | ELF::SHF_WRITE,
372 SectionKind::getDataRel());
373 } else {
374 std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
375 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
376 ELF::SHF_ALLOC |ELF::SHF_WRITE,
377 SectionKind::getDataRel());
378 }
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000379}
380
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000381const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000382 unsigned Priority, const MCSymbol *KeySym) const {
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000383 // The default scheme is .ctor / .dtor, so we have to invert the priority
384 // numbering.
385 if (Priority == 65535)
386 return StaticDtorSection;
387
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000388 if (UseInitArray) {
389 std::string Name = std::string(".fini_array.") + utostr(Priority);
390 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
391 ELF::SHF_ALLOC | ELF::SHF_WRITE,
392 SectionKind::getDataRel());
393 } else {
394 std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
395 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
396 ELF::SHF_ALLOC |ELF::SHF_WRITE,
397 SectionKind::getDataRel());
398 }
399}
400
401void
402TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
403 UseInitArray = UseInitArray_;
404 if (!UseInitArray)
405 return;
406
407 StaticCtorSection =
408 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
409 ELF::SHF_WRITE |
410 ELF::SHF_ALLOC,
411 SectionKind::getDataRel());
412 StaticDtorSection =
413 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
414 ELF::SHF_WRITE |
415 ELF::SHF_ALLOC,
416 SectionKind::getDataRel());
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000417}
418
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000419//===----------------------------------------------------------------------===//
420// MachO
421//===----------------------------------------------------------------------===//
422
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000423/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
424/// option string. Returns StringRef() if the option does not specify a library.
425StringRef TargetLoweringObjectFileMachO::
426getDepLibFromLinkerOpt(StringRef LinkerOption) const {
427 const char *LibCmd = "-l";
428 if (LinkerOption.startswith(LibCmd))
429 return LinkerOption.substr(strlen(LibCmd));
430 return StringRef();
431}
432
Daniel Dunbar95856122013-01-18 19:37:00 +0000433/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000434void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000435emitModuleFlags(MCStreamer &Streamer,
436 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000437 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000438 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000439 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000440 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000441 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000442
Bill Wendling734909a2012-02-15 22:36:15 +0000443 for (ArrayRef<Module::ModuleFlagEntry>::iterator
444 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
445 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000446
447 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000448 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000449 continue;
450
Bill Wendling734909a2012-02-15 22:36:15 +0000451 StringRef Key = MFE.Key->getString();
452 Value *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000453
Daniel Dunbar95856122013-01-18 19:37:00 +0000454 if (Key == "Objective-C Image Info Version") {
Bill Wendling06df7722012-02-14 21:28:13 +0000455 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000456 } else if (Key == "Objective-C Garbage Collection" ||
457 Key == "Objective-C GC Only" ||
458 Key == "Objective-C Is Simulated") {
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000459 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000460 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000461 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000462 } else if (Key == "Linker Options") {
463 LinkerOptions = cast<MDNode>(Val);
464 }
465 }
466
467 // Emit the linker options if present.
468 if (LinkerOptions) {
469 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
470 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
471 SmallVector<std::string, 4> StrOptions;
472
473 // Convert to strings.
474 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
475 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
476 StrOptions.push_back(MDOption->getString());
477 }
478
479 Streamer.EmitLinkerOptions(StrOptions);
480 }
Bill Wendling06df7722012-02-14 21:28:13 +0000481 }
482
Bill Wendling734909a2012-02-15 22:36:15 +0000483 // The section is mandatory. If we don't have it, then we don't have GC info.
484 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000485
Bill Wendling734909a2012-02-15 22:36:15 +0000486 StringRef Segment, Section;
487 unsigned TAA = 0, StubSize = 0;
488 bool TAAParsed;
489 std::string ErrorCode =
490 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
491 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000492 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000493 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000494 report_fatal_error("Invalid section specifier '" + Section + "': " +
495 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000496
Bill Wendling734909a2012-02-15 22:36:15 +0000497 // Get the section.
498 const MCSectionMachO *S =
499 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000500 SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000501 Streamer.SwitchSection(S);
502 Streamer.EmitLabel(getContext().
503 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000504 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000505 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000506 Streamer.AddBlankLine();
507}
508
David Majnemerdad0a642014-06-27 18:19:56 +0000509static void checkMachOComdat(const GlobalValue *GV) {
510 const Comdat *C = GV->getComdat();
511 if (!C)
512 return;
513
514 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
515 "' cannot be lowered.");
516}
517
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000518const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
519 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
520 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000521 // Parse the section specifier and create it if valid.
522 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000523 unsigned TAA = 0, StubSize = 0;
524 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000525
526 checkMachOComdat(GV);
527
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000528 std::string ErrorCode =
529 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000530 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000531 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000532 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000533 report_fatal_error("Global variable '" + GV->getName() +
534 "' has an invalid section specifier '" +
535 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000536 }
537
538 // Get the section.
539 const MCSectionMachO *S =
Chris Lattner433d4062010-04-08 20:40:11 +0000540 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000541
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000542 // If TAA wasn't set by ParseSectionSpecifier() above,
543 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000544 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000545 TAA = S->getTypeAndAttributes();
546
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000547 // Okay, now that we got the section, verify that the TAA & StubSize agree.
548 // If the user declared multiple globals with different section flags, we need
549 // to reject it here.
550 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000551 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000552 report_fatal_error("Global variable '" + GV->getName() +
553 "' section type or attributes does not match previous"
554 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000555 }
556
557 return S;
558}
559
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000560bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
561 const MCSection &Section) const {
562 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
563
564 // Sections holding 1 byte strings are atomized based on the data
565 // they contain.
566 // Sections holding 2 byte strings require symbols in order to be
567 // atomized.
568 // There is no dedicated section for 4 byte strings.
569 if (SMO.getKind().isMergeable1ByteCString())
570 return false;
571
572 if (SMO.getSegmentName() == "__DATA" &&
573 SMO.getSectionName() == "__cfstring")
574 return false;
575
576 switch (SMO.getType()) {
577 default:
578 return true;
579
580 // These sections are atomized at the element boundaries without using
581 // symbols.
David Majnemer7b583052014-03-07 07:36:05 +0000582 case MachO::S_4BYTE_LITERALS:
583 case MachO::S_8BYTE_LITERALS:
584 case MachO::S_16BYTE_LITERALS:
585 case MachO::S_LITERAL_POINTERS:
586 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
587 case MachO::S_LAZY_SYMBOL_POINTERS:
588 case MachO::S_MOD_INIT_FUNC_POINTERS:
589 case MachO::S_MOD_TERM_FUNC_POINTERS:
590 case MachO::S_INTERPOSING:
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000591 return false;
592 }
593}
594
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000595const MCSection *TargetLoweringObjectFileMachO::
596SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000597 Mangler &Mang, const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000598 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000599
600 // Handle thread local data.
601 if (Kind.isThreadBSS()) return TLSBSSSection;
602 if (Kind.isThreadData()) return TLSDataSection;
603
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000604 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000605 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
606
607 // If this is weak/linkonce, put this in a coalescable section, either in text
608 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000609 if (GV->isWeakForLinker()) {
610 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000611 return ConstTextCoalSection;
612 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000613 }
614
615 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000616 if (Kind.isMergeable1ByteCString() &&
Eric Christopherd9134482014-08-04 21:25:23 +0000617 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
618 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000619 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000620
Chris Lattneref2f8042010-03-07 04:28:09 +0000621 // Do not put 16-bit arrays in the UString section if they have an
622 // externally visible label, this runs into issues with certain linker
623 // versions.
624 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Eric Christopherd9134482014-08-04 21:25:23 +0000625 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
626 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000627 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000628
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000629 // With MachO only variables whose corresponding symbol starts with 'l' or
630 // 'L' can be merged, so we only try merging GVs with private linkage.
631 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000632 if (Kind.isMergeableConst4())
633 return FourByteConstantSection;
634 if (Kind.isMergeableConst8())
635 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000636 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000637 return SixteenByteConstantSection;
638 }
639
640 // Otherwise, if it is readonly, but not something we can specially optimize,
641 // just drop it in .const.
642 if (Kind.isReadOnly())
643 return ReadOnlySection;
644
645 // If this is marked const, put it into a const section. But if the dynamic
646 // linker needs to write to it, put it in the data segment.
647 if (Kind.isReadOnlyWithRel())
648 return ConstDataSection;
649
650 // Put zero initialized globals with strong external linkage in the
651 // DATA, __common section with the .zerofill directive.
652 if (Kind.isBSSExtern())
653 return DataCommonSection;
654
655 // Put zero initialized globals with local linkage in __DATA,__bss directive
656 // with the .zerofill directive (aka .lcomm).
657 if (Kind.isBSSLocal())
658 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000659
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000660 // Otherwise, just drop the variable in the normal data section.
661 return DataSection;
662}
663
664const MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000665TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
666 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000667 // If this constant requires a relocation, we have to put it in the data
668 // segment, not in the text segment.
669 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
670 return ConstDataSection;
671
672 if (Kind.isMergeableConst4())
673 return FourByteConstantSection;
674 if (Kind.isMergeableConst8())
675 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000676 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000677 return SixteenByteConstantSection;
678 return ReadOnlySection; // .const
679}
680
Rafael Espindola15b26692014-02-09 14:50:44 +0000681const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
682 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000683 const TargetMachine &TM, MachineModuleInfo *MMI,
684 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000685 // The mach-o version of this method defaults to returning a stub reference.
686
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000687 if (Encoding & DW_EH_PE_indirect) {
688 MachineModuleInfoMachO &MachOMMI =
689 MMI->getObjFileInfo<MachineModuleInfoMachO>();
690
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000691 MCSymbol *SSym =
692 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000693
694 // Add information about the stub reference to MachOMMI so that the stub
695 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000696 MachineModuleInfoImpl::StubValueTy &StubSym =
697 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
698 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000699 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000700 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000701 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000702 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000703
704 return TargetLoweringObjectFile::
Anton Korobeynikove42af362012-11-14 01:47:00 +0000705 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
706 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000707 }
708
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000709 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
710 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000711}
712
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000713MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
714 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
715 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000716 // The mach-o version of this method defaults to returning a stub reference.
717 MachineModuleInfoMachO &MachOMMI =
718 MMI->getObjFileInfo<MachineModuleInfoMachO>();
719
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000720 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000721
722 // Add information about the stub reference to MachOMMI so that the stub
723 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000724 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000725 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000726 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000727 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
728 }
729
730 return SSym;
731}
732
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000733//===----------------------------------------------------------------------===//
734// COFF
735//===----------------------------------------------------------------------===//
736
Chris Lattner87cffa92010-05-07 17:17:41 +0000737static unsigned
738getCOFFSectionFlags(SectionKind K) {
739 unsigned Flags = 0;
740
Anton Korobeynikove4152302010-07-06 15:24:56 +0000741 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000742 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000743 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000744 else if (K.isText())
745 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000746 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000747 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000748 COFF::IMAGE_SCN_CNT_CODE;
Chris Lattner02844932010-05-07 21:49:09 +0000749 else if (K.isBSS ())
750 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000751 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
752 COFF::IMAGE_SCN_MEM_READ |
753 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000754 else if (K.isThreadLocal())
755 Flags |=
756 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
757 COFF::IMAGE_SCN_MEM_READ |
758 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000759 else if (K.isReadOnly())
760 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000761 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
762 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000763 else if (K.isWriteable())
764 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000765 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
766 COFF::IMAGE_SCN_MEM_READ |
767 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000768
769 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000770}
771
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000772static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000773 const Comdat *C = GV->getComdat();
774 assert(C && "expected GV to have a Comdat!");
775
776 StringRef ComdatGVName = C->getName();
777 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
778 if (!ComdatGV)
779 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
780 "' does not exist.");
781
782 if (ComdatGV->getComdat() != C)
783 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
784 "' is not a key for it's COMDAT.");
785
786 return ComdatGV;
787}
788
789static int getSelectionForCOFF(const GlobalValue *GV) {
790 if (const Comdat *C = GV->getComdat()) {
791 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
792 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
793 ComdatKey = GA->getBaseObject();
794 if (ComdatKey == GV) {
795 switch (C->getSelectionKind()) {
796 case Comdat::Any:
797 return COFF::IMAGE_COMDAT_SELECT_ANY;
798 case Comdat::ExactMatch:
799 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
800 case Comdat::Largest:
801 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
802 case Comdat::NoDuplicates:
803 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
804 case Comdat::SameSize:
805 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
806 }
807 } else {
808 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
809 }
810 } else if (GV->isWeakForLinker()) {
811 return COFF::IMAGE_COMDAT_SELECT_ANY;
812 }
813 return 0;
814}
815
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000816const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
817 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
818 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000819 int Selection = 0;
820 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000821 StringRef Name = GV->getSection();
822 StringRef COMDATSymName = "";
David Majnemerdad0a642014-06-27 18:19:56 +0000823 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
824 Selection = getSelectionForCOFF(GV);
825 const GlobalValue *ComdatGV;
826 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
827 ComdatGV = getComdatGVForCOFF(GV);
828 else
829 ComdatGV = GV;
830
831 if (!ComdatGV->hasPrivateLinkage()) {
832 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
833 COMDATSymName = Sym->getName();
834 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
835 } else {
836 Selection = 0;
837 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000838 }
839 return getContext().getCOFFSection(Name,
840 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000841 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000842 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000843 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000844}
845
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000846static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000847 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000848 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000849 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000850 return ".bss";
851 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000852 return ".tls$";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000853 if (Kind.isWriteable())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000854 return ".data";
855 return ".rdata";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000856}
857
858
859const MCSection *TargetLoweringObjectFileCOFF::
860SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000861 Mangler &Mang, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000862 // If we have -ffunction-sections then we should emit the global value to a
863 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000864 bool EmitUniquedSection;
865 if (Kind.isText())
866 EmitUniquedSection = TM.getFunctionSections();
867 else
868 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000869
870 // If this global is linkonce/weak and the target handles this by emitting it
871 // into a 'uniqued' section name, create and return the section now.
David Majnemer273bff42014-03-25 06:14:26 +0000872 // Section names depend on the name of the symbol which is not feasible if the
873 // symbol has private linkage.
David Majnemerdad0a642014-06-27 18:19:56 +0000874 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
875 !Kind.isCommon()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000876 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000877 unsigned Characteristics = getCOFFSectionFlags(Kind);
878
Daniel Dunbar329d2022010-07-01 20:07:24 +0000879 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000880 int Selection = getSelectionForCOFF(GV);
881 if (!Selection)
882 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
883 const GlobalValue *ComdatGV;
884 if (GV->hasComdat())
885 ComdatGV = getComdatGVForCOFF(GV);
886 else
887 ComdatGV = GV;
888
889 if (!ComdatGV->hasPrivateLinkage()) {
890 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
891 StringRef COMDATSymName = Sym->getName();
892 return getContext().getCOFFSection(Name, Characteristics, Kind,
893 COMDATSymName, Selection);
894 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000895 }
896
897 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000898 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000899
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000900 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000901 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000902
David Majnemer3d96acb2013-08-13 01:23:53 +0000903 if (Kind.isReadOnly())
David Majnemerf76d6b32013-08-08 01:50:52 +0000904 return ReadOnlySection;
905
David Majnemera9bdb322014-04-08 22:33:40 +0000906 // Note: we claim that common symbols are put in BSSSection, but they are
907 // really emitted with the magic .comm directive, which creates a symbol table
908 // entry but not a section.
909 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000910 return BSSSection;
911
912 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000913}
914
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000915StringRef TargetLoweringObjectFileCOFF::
916getDepLibFromLinkerOpt(StringRef LinkerOption) const {
917 const char *LibCmd = "/DEFAULTLIB:";
918 if (LinkerOption.startswith(LibCmd))
919 return LinkerOption.substr(strlen(LibCmd));
920 return StringRef();
921}
922
Reid Klecknerd973ca32013-04-25 19:34:41 +0000923void TargetLoweringObjectFileCOFF::
924emitModuleFlags(MCStreamer &Streamer,
925 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000926 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000927 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000928
929 // Look for the "Linker Options" flag, since it's the only one we support.
930 for (ArrayRef<Module::ModuleFlagEntry>::iterator
931 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
932 const Module::ModuleFlagEntry &MFE = *i;
933 StringRef Key = MFE.Key->getString();
934 Value *Val = MFE.Val;
935 if (Key == "Linker Options") {
936 LinkerOptions = cast<MDNode>(Val);
937 break;
938 }
939 }
940 if (!LinkerOptions)
941 return;
942
943 // Emit the linker options to the linker .drectve section. According to the
944 // spec, this section is a space-separated string containing flags for linker.
945 const MCSection *Sec = getDrectveSection();
946 Streamer.SwitchSection(Sec);
947 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
948 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
949 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
950 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
951 StringRef Op = MDOption->getString();
952 // Lead with a space for consistency with our dllexport implementation.
953 std::string Escaped(" ");
954 if (Op.find(" ") != StringRef::npos) {
955 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
956 // how to escape quotes, but it probably uses this algorithm:
957 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
958 // FIXME: Reuse escaping code from Support/Windows/Program.inc
959 Escaped.push_back('\"');
960 Escaped.append(Op);
961 Escaped.push_back('\"');
962 } else {
963 Escaped.append(Op);
964 }
965 Streamer.EmitBytes(Escaped);
966 }
967 }
968}
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000969
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000970const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000971 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +0000972 return getContext().getAssociativeCOFFSection(
973 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000974}
975
976const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000977 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +0000978 return getContext().getAssociativeCOFFSection(
979 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000980}