blob: b9a3ad23d1f812c710196e1abde1f08d58550ec2 [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.
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000260 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
David Majnemer102ff692014-06-24 16:01:53 +0000261 StringRef Prefix = getSectionPrefixForGlobal(Kind);
Chris Lattner5b212a32010-04-13 00:36:43 +0000262
David Majnemer102ff692014-06-24 16:01:53 +0000263 SmallString<128> Name(Prefix);
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000264 TM.getNameWithPrefix(Name, GV, Mang, true);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000265
Rafael Espindola70d80152011-02-14 22:23:49 +0000266 StringRef Group = "";
267 unsigned Flags = getELFSectionFlags(Kind);
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000268 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola70d80152011-02-14 22:23:49 +0000269 Flags |= ELF::SHF_GROUP;
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000270 Group = C->getName();
Rafael Espindola70d80152011-02-14 22:23:49 +0000271 }
272
Chris Lattner80c34592010-04-08 21:34:17 +0000273 return getContext().getELFSection(Name.str(),
274 getELFSectionType(Name.str(), Kind),
Rafael Espindola70d80152011-02-14 22:23:49 +0000275 Flags, Kind, 0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000276 }
277
278 if (Kind.isText()) return TextSection;
279
280 if (Kind.isMergeable1ByteCString() ||
281 Kind.isMergeable2ByteCString() ||
282 Kind.isMergeable4ByteCString()) {
283
284 // We also need alignment here.
285 // FIXME: this is getting the alignment of the character, not the
286 // alignment of the global!
287 unsigned Align =
Eric Christopherd9134482014-08-04 21:25:23 +0000288 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
289 cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000290
291 const char *SizeSpec = ".rodata.str1.";
292 if (Kind.isMergeable2ByteCString())
293 SizeSpec = ".rodata.str2.";
294 else if (Kind.isMergeable4ByteCString())
295 SizeSpec = ".rodata.str4.";
296 else
297 assert(Kind.isMergeable1ByteCString() && "unknown string width");
298
299
300 std::string Name = SizeSpec + utostr(Align);
Rafael Espindolaaea49582011-01-23 04:28:49 +0000301 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000302 ELF::SHF_ALLOC |
303 ELF::SHF_MERGE |
304 ELF::SHF_STRINGS,
Chris Lattner80c34592010-04-08 21:34:17 +0000305 Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000306 }
307
308 if (Kind.isMergeableConst()) {
309 if (Kind.isMergeableConst4() && MergeableConst4Section)
310 return MergeableConst4Section;
311 if (Kind.isMergeableConst8() && MergeableConst8Section)
312 return MergeableConst8Section;
313 if (Kind.isMergeableConst16() && MergeableConst16Section)
314 return MergeableConst16Section;
315 return ReadOnlySection; // .const
316 }
317
318 if (Kind.isReadOnly()) return ReadOnlySection;
319
320 if (Kind.isThreadData()) return TLSDataSection;
321 if (Kind.isThreadBSS()) return TLSBSSSection;
322
323 // Note: we claim that common symbols are put in BSSSection, but they are
324 // really emitted with the magic .comm directive, which creates a symbol table
325 // entry but not a section.
326 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
327
328 if (Kind.isDataNoRel()) return DataSection;
329 if (Kind.isDataRelLocal()) return DataRelLocalSection;
330 if (Kind.isDataRel()) return DataRelSection;
331 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
332
333 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
334 return DataRelROSection;
335}
336
337/// getSectionForConstant - Given a mergeable constant with the
338/// specified size and relocation information, return a section that it
339/// should be placed in.
David Majnemer8bce66b2014-07-14 22:57:27 +0000340const MCSection *
341TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
342 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000343 if (Kind.isMergeableConst4() && MergeableConst4Section)
344 return MergeableConst4Section;
345 if (Kind.isMergeableConst8() && MergeableConst8Section)
346 return MergeableConst8Section;
347 if (Kind.isMergeableConst16() && MergeableConst16Section)
348 return MergeableConst16Section;
349 if (Kind.isReadOnly())
350 return ReadOnlySection;
351
352 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
353 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
354 return DataRelROSection;
355}
356
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000357static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
358 bool UseInitArray,
359 bool IsCtor,
360 unsigned Priority,
361 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000362 std::string Name;
363 unsigned Type;
364 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
365 SectionKind Kind = SectionKind::getDataRel();
366 StringRef COMDAT = KeySym ? KeySym->getName() : "";
367
368 if (KeySym)
369 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000370
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000371 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000372 if (IsCtor) {
373 Type = ELF::SHT_INIT_ARRAY;
374 Name = ".init_array";
375 } else {
376 Type = ELF::SHT_FINI_ARRAY;
377 Name = ".fini_array";
378 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000379 if (Priority != 65535) {
380 Name += '.';
381 Name += utostr(Priority);
382 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000383 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000384 // The default scheme is .ctor / .dtor, so we have to invert the priority
385 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000386 if (IsCtor)
387 Name = ".ctors";
388 else
389 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000390 if (Priority != 65535) {
391 Name += '.';
392 Name += utostr(65535 - Priority);
393 }
394 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000395 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000396
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000397 return Ctx.getELFSection(Name, Type, Flags, Kind, 0, COMDAT);
398}
399
400const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
401 unsigned Priority, const MCSymbol *KeySym) const {
402 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
403 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000404}
405
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000406const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000407 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000408 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
409 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000410}
411
412void
413TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
414 UseInitArray = UseInitArray_;
415 if (!UseInitArray)
416 return;
417
418 StaticCtorSection =
419 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
420 ELF::SHF_WRITE |
421 ELF::SHF_ALLOC,
422 SectionKind::getDataRel());
423 StaticDtorSection =
424 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
425 ELF::SHF_WRITE |
426 ELF::SHF_ALLOC,
427 SectionKind::getDataRel());
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000428}
429
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000430//===----------------------------------------------------------------------===//
431// MachO
432//===----------------------------------------------------------------------===//
433
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000434/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
435/// option string. Returns StringRef() if the option does not specify a library.
436StringRef TargetLoweringObjectFileMachO::
437getDepLibFromLinkerOpt(StringRef LinkerOption) const {
438 const char *LibCmd = "-l";
439 if (LinkerOption.startswith(LibCmd))
440 return LinkerOption.substr(strlen(LibCmd));
441 return StringRef();
442}
443
Daniel Dunbar95856122013-01-18 19:37:00 +0000444/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000445void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000446emitModuleFlags(MCStreamer &Streamer,
447 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000448 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000449 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000450 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000451 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000452 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000453
Bill Wendling734909a2012-02-15 22:36:15 +0000454 for (ArrayRef<Module::ModuleFlagEntry>::iterator
455 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
456 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000457
458 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000459 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000460 continue;
461
Bill Wendling734909a2012-02-15 22:36:15 +0000462 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000463 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000464
Daniel Dunbar95856122013-01-18 19:37:00 +0000465 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000466 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000467 } else if (Key == "Objective-C Garbage Collection" ||
468 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000469 Key == "Objective-C Is Simulated" ||
470 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000471 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000472 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000473 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000474 } else if (Key == "Linker Options") {
475 LinkerOptions = cast<MDNode>(Val);
476 }
477 }
478
479 // Emit the linker options if present.
480 if (LinkerOptions) {
481 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
482 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
483 SmallVector<std::string, 4> StrOptions;
484
485 // Convert to strings.
486 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
487 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
488 StrOptions.push_back(MDOption->getString());
489 }
490
491 Streamer.EmitLinkerOptions(StrOptions);
492 }
Bill Wendling06df7722012-02-14 21:28:13 +0000493 }
494
Bill Wendling734909a2012-02-15 22:36:15 +0000495 // The section is mandatory. If we don't have it, then we don't have GC info.
496 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000497
Bill Wendling734909a2012-02-15 22:36:15 +0000498 StringRef Segment, Section;
499 unsigned TAA = 0, StubSize = 0;
500 bool TAAParsed;
501 std::string ErrorCode =
502 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
503 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000504 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000505 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000506 report_fatal_error("Invalid section specifier '" + Section + "': " +
507 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000508
Bill Wendling734909a2012-02-15 22:36:15 +0000509 // Get the section.
510 const MCSectionMachO *S =
511 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000512 SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000513 Streamer.SwitchSection(S);
514 Streamer.EmitLabel(getContext().
515 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000516 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000517 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000518 Streamer.AddBlankLine();
519}
520
David Majnemerdad0a642014-06-27 18:19:56 +0000521static void checkMachOComdat(const GlobalValue *GV) {
522 const Comdat *C = GV->getComdat();
523 if (!C)
524 return;
525
526 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
527 "' cannot be lowered.");
528}
529
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000530const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
531 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
532 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000533 // Parse the section specifier and create it if valid.
534 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000535 unsigned TAA = 0, StubSize = 0;
536 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000537
538 checkMachOComdat(GV);
539
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000540 std::string ErrorCode =
541 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000542 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000543 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000544 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000545 report_fatal_error("Global variable '" + GV->getName() +
546 "' has an invalid section specifier '" +
547 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000548 }
549
550 // Get the section.
551 const MCSectionMachO *S =
Chris Lattner433d4062010-04-08 20:40:11 +0000552 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000553
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000554 // If TAA wasn't set by ParseSectionSpecifier() above,
555 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000556 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000557 TAA = S->getTypeAndAttributes();
558
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000559 // Okay, now that we got the section, verify that the TAA & StubSize agree.
560 // If the user declared multiple globals with different section flags, we need
561 // to reject it here.
562 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000563 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000564 report_fatal_error("Global variable '" + GV->getName() +
565 "' section type or attributes does not match previous"
566 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000567 }
568
569 return S;
570}
571
572const MCSection *TargetLoweringObjectFileMachO::
573SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000574 Mangler &Mang, const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000575 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000576
577 // Handle thread local data.
578 if (Kind.isThreadBSS()) return TLSBSSSection;
579 if (Kind.isThreadData()) return TLSDataSection;
580
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000581 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000582 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
583
584 // If this is weak/linkonce, put this in a coalescable section, either in text
585 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000586 if (GV->isWeakForLinker()) {
587 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000588 return ConstTextCoalSection;
589 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000590 }
591
592 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000593 if (Kind.isMergeable1ByteCString() &&
Eric Christopherd9134482014-08-04 21:25:23 +0000594 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
595 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000596 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000597
Chris Lattneref2f8042010-03-07 04:28:09 +0000598 // Do not put 16-bit arrays in the UString section if they have an
599 // externally visible label, this runs into issues with certain linker
600 // versions.
601 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Eric Christopherd9134482014-08-04 21:25:23 +0000602 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
603 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000604 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000605
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000606 // With MachO only variables whose corresponding symbol starts with 'l' or
607 // 'L' can be merged, so we only try merging GVs with private linkage.
608 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000609 if (Kind.isMergeableConst4())
610 return FourByteConstantSection;
611 if (Kind.isMergeableConst8())
612 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000613 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000614 return SixteenByteConstantSection;
615 }
616
617 // Otherwise, if it is readonly, but not something we can specially optimize,
618 // just drop it in .const.
619 if (Kind.isReadOnly())
620 return ReadOnlySection;
621
622 // If this is marked const, put it into a const section. But if the dynamic
623 // linker needs to write to it, put it in the data segment.
624 if (Kind.isReadOnlyWithRel())
625 return ConstDataSection;
626
627 // Put zero initialized globals with strong external linkage in the
628 // DATA, __common section with the .zerofill directive.
629 if (Kind.isBSSExtern())
630 return DataCommonSection;
631
632 // Put zero initialized globals with local linkage in __DATA,__bss directive
633 // with the .zerofill directive (aka .lcomm).
634 if (Kind.isBSSLocal())
635 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000636
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000637 // Otherwise, just drop the variable in the normal data section.
638 return DataSection;
639}
640
641const MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000642TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
643 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000644 // If this constant requires a relocation, we have to put it in the data
645 // segment, not in the text segment.
646 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
647 return ConstDataSection;
648
649 if (Kind.isMergeableConst4())
650 return FourByteConstantSection;
651 if (Kind.isMergeableConst8())
652 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000653 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000654 return SixteenByteConstantSection;
655 return ReadOnlySection; // .const
656}
657
Rafael Espindola15b26692014-02-09 14:50:44 +0000658const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
659 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000660 const TargetMachine &TM, MachineModuleInfo *MMI,
661 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000662 // The mach-o version of this method defaults to returning a stub reference.
663
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000664 if (Encoding & DW_EH_PE_indirect) {
665 MachineModuleInfoMachO &MachOMMI =
666 MMI->getObjFileInfo<MachineModuleInfoMachO>();
667
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000668 MCSymbol *SSym =
669 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000670
671 // Add information about the stub reference to MachOMMI so that the stub
672 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000673 MachineModuleInfoImpl::StubValueTy &StubSym =
674 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
675 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000676 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000677 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000678 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000679 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000680
681 return TargetLoweringObjectFile::
Anton Korobeynikove42af362012-11-14 01:47:00 +0000682 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
683 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000684 }
685
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000686 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
687 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000688}
689
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000690MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
691 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
692 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000693 // The mach-o version of this method defaults to returning a stub reference.
694 MachineModuleInfoMachO &MachOMMI =
695 MMI->getObjFileInfo<MachineModuleInfoMachO>();
696
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000697 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000698
699 // Add information about the stub reference to MachOMMI so that the stub
700 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000701 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000702 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000703 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000704 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
705 }
706
707 return SSym;
708}
709
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000710//===----------------------------------------------------------------------===//
711// COFF
712//===----------------------------------------------------------------------===//
713
Chris Lattner87cffa92010-05-07 17:17:41 +0000714static unsigned
715getCOFFSectionFlags(SectionKind K) {
716 unsigned Flags = 0;
717
Anton Korobeynikove4152302010-07-06 15:24:56 +0000718 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000719 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000720 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000721 else if (K.isText())
722 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000723 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000724 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000725 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000726 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000727 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000728 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
729 COFF::IMAGE_SCN_MEM_READ |
730 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000731 else if (K.isThreadLocal())
732 Flags |=
733 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
734 COFF::IMAGE_SCN_MEM_READ |
735 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000736 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000737 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000738 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
739 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000740 else if (K.isWriteable())
741 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000742 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
743 COFF::IMAGE_SCN_MEM_READ |
744 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000745
746 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000747}
748
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000749static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000750 const Comdat *C = GV->getComdat();
751 assert(C && "expected GV to have a Comdat!");
752
753 StringRef ComdatGVName = C->getName();
754 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
755 if (!ComdatGV)
756 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
757 "' does not exist.");
758
759 if (ComdatGV->getComdat() != C)
760 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000761 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000762
763 return ComdatGV;
764}
765
766static int getSelectionForCOFF(const GlobalValue *GV) {
767 if (const Comdat *C = GV->getComdat()) {
768 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
769 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
770 ComdatKey = GA->getBaseObject();
771 if (ComdatKey == GV) {
772 switch (C->getSelectionKind()) {
773 case Comdat::Any:
774 return COFF::IMAGE_COMDAT_SELECT_ANY;
775 case Comdat::ExactMatch:
776 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
777 case Comdat::Largest:
778 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
779 case Comdat::NoDuplicates:
780 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
781 case Comdat::SameSize:
782 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
783 }
784 } else {
785 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
786 }
787 } else if (GV->isWeakForLinker()) {
788 return COFF::IMAGE_COMDAT_SELECT_ANY;
789 }
790 return 0;
791}
792
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000793const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
794 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
795 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000796 int Selection = 0;
797 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000798 StringRef Name = GV->getSection();
799 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000800 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000801 Selection = getSelectionForCOFF(GV);
802 const GlobalValue *ComdatGV;
803 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
804 ComdatGV = getComdatGVForCOFF(GV);
805 else
806 ComdatGV = GV;
807
808 if (!ComdatGV->hasPrivateLinkage()) {
809 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
810 COMDATSymName = Sym->getName();
811 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
812 } else {
813 Selection = 0;
814 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000815 }
816 return getContext().getCOFFSection(Name,
817 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000818 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000819 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000820 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000821}
822
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000823static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000824 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000825 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000826 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000827 return ".bss";
828 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000829 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000830 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
831 return ".rdata";
832 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000833}
834
835
836const MCSection *TargetLoweringObjectFileCOFF::
837SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000838 Mangler &Mang, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000839 // If we have -ffunction-sections then we should emit the global value to a
840 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000841 bool EmitUniquedSection;
842 if (Kind.isText())
843 EmitUniquedSection = TM.getFunctionSections();
844 else
845 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000846
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000847 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000848 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000849 unsigned Characteristics = getCOFFSectionFlags(Kind);
850
Daniel Dunbar329d2022010-07-01 20:07:24 +0000851 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000852 int Selection = getSelectionForCOFF(GV);
853 if (!Selection)
854 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
855 const GlobalValue *ComdatGV;
856 if (GV->hasComdat())
857 ComdatGV = getComdatGVForCOFF(GV);
858 else
859 ComdatGV = GV;
860
861 if (!ComdatGV->hasPrivateLinkage()) {
862 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
863 StringRef COMDATSymName = Sym->getName();
864 return getContext().getCOFFSection(Name, Characteristics, Kind,
865 COMDATSymName, Selection);
866 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000867 }
868
869 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000870 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000871
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000872 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000873 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000874
David Majnemer597be2d2014-09-22 20:39:23 +0000875 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000876 return ReadOnlySection;
877
David Majnemera9bdb322014-04-08 22:33:40 +0000878 // Note: we claim that common symbols are put in BSSSection, but they are
879 // really emitted with the magic .comm directive, which creates a symbol table
880 // entry but not a section.
881 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000882 return BSSSection;
883
884 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000885}
886
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000887StringRef TargetLoweringObjectFileCOFF::
888getDepLibFromLinkerOpt(StringRef LinkerOption) const {
889 const char *LibCmd = "/DEFAULTLIB:";
890 if (LinkerOption.startswith(LibCmd))
891 return LinkerOption.substr(strlen(LibCmd));
892 return StringRef();
893}
894
Reid Klecknerd973ca32013-04-25 19:34:41 +0000895void TargetLoweringObjectFileCOFF::
896emitModuleFlags(MCStreamer &Streamer,
897 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000898 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000899 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000900
901 // Look for the "Linker Options" flag, since it's the only one we support.
902 for (ArrayRef<Module::ModuleFlagEntry>::iterator
903 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
904 const Module::ModuleFlagEntry &MFE = *i;
905 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000906 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000907 if (Key == "Linker Options") {
908 LinkerOptions = cast<MDNode>(Val);
909 break;
910 }
911 }
912 if (!LinkerOptions)
913 return;
914
915 // Emit the linker options to the linker .drectve section. According to the
916 // spec, this section is a space-separated string containing flags for linker.
917 const MCSection *Sec = getDrectveSection();
918 Streamer.SwitchSection(Sec);
919 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
920 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
921 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
922 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
923 StringRef Op = MDOption->getString();
924 // Lead with a space for consistency with our dllexport implementation.
925 std::string Escaped(" ");
Michael Kupersteinc43b0632014-12-30 19:23:48 +0000926 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
Reid Klecknerd973ca32013-04-25 19:34:41 +0000927 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
928 // how to escape quotes, but it probably uses this algorithm:
929 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
930 // FIXME: Reuse escaping code from Support/Windows/Program.inc
931 Escaped.push_back('\"');
932 Escaped.append(Op);
933 Escaped.push_back('\"');
934 } else {
935 Escaped.append(Op);
936 }
937 Streamer.EmitBytes(Escaped);
938 }
939 }
940}
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000941
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000942const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000943 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +0000944 return getContext().getAssociativeCOFFSection(
945 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000946}
947
948const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000949 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +0000950 return getContext().getAssociativeCOFFSection(
951 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000952}