blob: bcf2aa72c4bbd4a99fce6f9a7f6c574527f0c0f4 [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"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000034#include "llvm/MC/MCValue.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000035#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000036#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000037#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000039#include "llvm/Target/TargetLowering.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000040#include "llvm/Target/TargetMachine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000042using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000043using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000044
45//===----------------------------------------------------------------------===//
46// ELF
47//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000048
Rafael Espindoladaeafb42014-02-19 17:23:20 +000049MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
50 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
51 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000052 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000053 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000054 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000055 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000056 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
57 return TM.getSymbol(GV, Mang);
58 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +000059}
60
61void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
62 const TargetMachine &TM,
Rafael Espindola08704342011-04-27 23:08:15 +000063 const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000064 SmallString<64> NameData("DW.ref.");
65 NameData += Sym->getName();
66 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
Rafael Espindola39897762011-04-27 21:29:52 +000067 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
68 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000069 StringRef Prefix = ".data.";
70 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-04-27 21:29:52 +000071 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
72 const MCSection *Sec = getContext().getELFSection(NameData,
73 ELF::SHT_PROGBITS,
74 Flags,
Rafael Espindola39897762011-04-27 21:29:52 +000075 0, Label->getName());
Eric Christopher8b770652015-01-26 19:03:15 +000076 unsigned Size = TM.getDataLayout()->getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000077 Streamer.SwitchSection(Sec);
Eric Christopher8b770652015-01-26 19:03:15 +000078 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000079 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
David Chisnall8fa17162012-02-17 16:05:50 +000080 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
Rafael Espindola39897762011-04-27 21:29:52 +000081 Streamer.EmitELFSize(Label, E);
82 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000083
Rafael Espindola39897762011-04-27 21:29:52 +000084 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000085}
86
Rafael Espindola15b26692014-02-09 14:50:44 +000087const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
88 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000089 const TargetMachine &TM, MachineModuleInfo *MMI,
90 MCStreamer &Streamer) const {
Anton Korobeynikove42af362012-11-14 01:47:00 +000091
92 if (Encoding & dwarf::DW_EH_PE_indirect) {
93 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
94
Rafael Espindoladaeafb42014-02-19 17:23:20 +000095 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +000096
97 // Add information about the stub reference to ELFMMI so that the stub
98 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +000099 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000100 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000101 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000102 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
103 }
104
105 return TargetLoweringObjectFile::
106 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
107 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
108 }
109
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000110 return TargetLoweringObjectFile::
111 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000112}
113
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000114static SectionKind
115getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000116 // N.B.: The defaults used in here are no the same ones used in MC.
117 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
118 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000119 // section(".eh_frame") gcc will produce:
120 //
121 // .section .eh_frame,"a",@progbits
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000122 if (Name.empty() || Name[0] != '.') return K;
123
124 // Some lame default implementation based on some magic section names.
125 if (Name == ".bss" ||
126 Name.startswith(".bss.") ||
127 Name.startswith(".gnu.linkonce.b.") ||
128 Name.startswith(".llvm.linkonce.b.") ||
129 Name == ".sbss" ||
130 Name.startswith(".sbss.") ||
131 Name.startswith(".gnu.linkonce.sb.") ||
132 Name.startswith(".llvm.linkonce.sb."))
133 return SectionKind::getBSS();
134
135 if (Name == ".tdata" ||
136 Name.startswith(".tdata.") ||
137 Name.startswith(".gnu.linkonce.td.") ||
138 Name.startswith(".llvm.linkonce.td."))
139 return SectionKind::getThreadData();
140
141 if (Name == ".tbss" ||
142 Name.startswith(".tbss.") ||
143 Name.startswith(".gnu.linkonce.tb.") ||
144 Name.startswith(".llvm.linkonce.tb."))
145 return SectionKind::getThreadBSS();
146
147 return K;
148}
149
150
151static unsigned getELFSectionType(StringRef Name, SectionKind K) {
152
153 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000154 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000155
156 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000157 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000158
159 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000160 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000161
162 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000163 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000164
Rafael Espindolaaea49582011-01-23 04:28:49 +0000165 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000166}
167
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000168static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000169 unsigned Flags = 0;
170
171 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000172 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000173
174 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000175 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000176
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000177 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000178 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000179
180 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000181 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000182
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000183 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000184 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000185
186 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000187 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000188
189 return Flags;
190}
191
David Majnemerdad0a642014-06-27 18:19:56 +0000192static const Comdat *getELFComdat(const GlobalValue *GV) {
193 const Comdat *C = GV->getComdat();
194 if (!C)
195 return nullptr;
196
197 if (C->getSelectionKind() != Comdat::Any)
198 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
199 C->getName() + "' cannot be lowered.");
200
201 return C;
202}
203
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000204const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
205 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
206 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000207 StringRef SectionName = GV->getSection();
208
209 // Infer section flags from the section name if we can.
210 Kind = getELFKindForNamedSection(SectionName, Kind);
211
David Majnemerdad0a642014-06-27 18:19:56 +0000212 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000213 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000214 if (const Comdat *C = getELFComdat(GV)) {
215 Group = C->getName();
216 Flags |= ELF::SHF_GROUP;
217 }
Chris Lattner80c34592010-04-08 21:34:17 +0000218 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000219 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000220 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000221}
222
Rafael Espindola25d2c202015-02-11 14:44:17 +0000223/// Return the section prefix name used by options FunctionsSections and
224/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000225static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000226 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000227 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000228 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000229 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000230 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000231 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000232 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000233 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000234 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000235 return ".tbss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000236 if (Kind.isDataNoRel())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000237 return ".data";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000238 if (Kind.isDataRelLocal())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000239 return ".data.rel.local";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000240 if (Kind.isDataRel())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000241 return ".data.rel";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000242 if (Kind.isReadOnlyWithRelLocal())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000243 return ".data.rel.ro.local";
Chris Lattner5b212a32010-04-13 00:36:43 +0000244 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000245 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000246}
247
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000248static const MCSectionELF *selectELFSectionForGlobal(
249 MCContext &Ctx, const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
250 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000251 unsigned EntrySize = 0;
252 if (Kind.isMergeableCString()) {
253 if (Kind.isMergeable2ByteCString()) {
254 EntrySize = 2;
255 } else if (Kind.isMergeable4ByteCString()) {
256 EntrySize = 4;
257 } else {
258 EntrySize = 1;
259 assert(Kind.isMergeable1ByteCString() && "unknown string width");
260 }
261 } else if (Kind.isMergeableConst()) {
262 if (Kind.isMergeableConst4()) {
263 EntrySize = 4;
264 } else if (Kind.isMergeableConst8()) {
265 EntrySize = 8;
266 } else {
267 assert(Kind.isMergeableConst16() && "unknown data width");
268 EntrySize = 16;
269 }
270 }
271
Rafael Espindola9075f772015-02-20 23:28:28 +0000272 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000273 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000274 Flags |= ELF::SHF_GROUP;
275 Group = C->getName();
276 }
277
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000278 bool UniqueSectionNames = TM.getUniqueSectionNames();
279 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000280 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000281 // We also need alignment here.
282 // FIXME: this is getting the alignment of the character, not the
283 // alignment of the global!
284 unsigned Align =
Eric Christopher8b770652015-01-26 19:03:15 +0000285 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000286
Rafael Espindolaba31e272015-01-29 17:33:21 +0000287 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000288 Name = SizeSpec + utostr(Align);
289 } else if (Kind.isMergeableConst()) {
290 Name = ".rodata.cst";
291 Name += utostr(EntrySize);
292 } else {
293 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000294 }
295
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000296 if (EmitUniqueSection && UniqueSectionNames) {
297 Name.push_back('.');
298 TM.getNameWithPrefix(Name, GV, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000299 }
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000300 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
301 EntrySize, Group,
302 EmitUniqueSection && !UniqueSectionNames);
303}
304
305const MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
306 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
307 const TargetMachine &TM) const {
308 unsigned Flags = getELFSectionFlags(Kind);
309
310 // If we have -ffunction-section or -fdata-section then we should emit the
311 // global value to a uniqued section specifically for it.
312 bool EmitUniqueSection = false;
313 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
314 if (Kind.isText())
315 EmitUniqueSection = TM.getFunctionSections();
316 else
317 EmitUniqueSection = TM.getDataSections();
318 }
319 EmitUniqueSection |= GV->hasComdat();
320
321 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
322 EmitUniqueSection, Flags);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000323}
324
Rafael Espindola29786d42015-02-12 17:16:46 +0000325const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
326 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
327 // If the function can be removed, produce a unique section so that
328 // the table doesn't prevent the removal.
329 const Comdat *C = F.getComdat();
330 bool EmitUniqueSection = TM.getFunctionSections() || C;
331 if (!EmitUniqueSection)
332 return ReadOnlySection;
333
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000334 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
335 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC);
Rafael Espindola29786d42015-02-12 17:16:46 +0000336}
337
Rafael Espindoladf195192015-02-17 23:34:51 +0000338bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
339 bool UsesLabelDifference, const Function &F) const {
340 // We can always create relative relocations, so use another section
341 // that can be marked non-executable.
342 return false;
343}
344
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000345/// getSectionForConstant - Given a mergeable constant with the
346/// specified size and relocation information, return a section that it
347/// should be placed in.
David Majnemer8bce66b2014-07-14 22:57:27 +0000348const MCSection *
349TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
350 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000351 if (Kind.isMergeableConst4() && MergeableConst4Section)
352 return MergeableConst4Section;
353 if (Kind.isMergeableConst8() && MergeableConst8Section)
354 return MergeableConst8Section;
355 if (Kind.isMergeableConst16() && MergeableConst16Section)
356 return MergeableConst16Section;
357 if (Kind.isReadOnly())
358 return ReadOnlySection;
359
360 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
361 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
362 return DataRelROSection;
363}
364
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000365static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
366 bool UseInitArray,
367 bool IsCtor,
368 unsigned Priority,
369 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000370 std::string Name;
371 unsigned Type;
372 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000373 StringRef COMDAT = KeySym ? KeySym->getName() : "";
374
375 if (KeySym)
376 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000377
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000378 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000379 if (IsCtor) {
380 Type = ELF::SHT_INIT_ARRAY;
381 Name = ".init_array";
382 } else {
383 Type = ELF::SHT_FINI_ARRAY;
384 Name = ".fini_array";
385 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000386 if (Priority != 65535) {
387 Name += '.';
388 Name += utostr(Priority);
389 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000390 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000391 // The default scheme is .ctor / .dtor, so we have to invert the priority
392 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000393 if (IsCtor)
394 Name = ".ctors";
395 else
396 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000397 if (Priority != 65535) {
398 Name += '.';
399 Name += utostr(65535 - Priority);
400 }
401 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000402 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000403
Rafael Espindolaba31e272015-01-29 17:33:21 +0000404 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000405}
406
407const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
408 unsigned Priority, const MCSymbol *KeySym) const {
409 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
410 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000411}
412
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000413const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000414 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000415 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
416 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000417}
418
419void
420TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
421 UseInitArray = UseInitArray_;
422 if (!UseInitArray)
423 return;
424
Rafael Espindolaba31e272015-01-29 17:33:21 +0000425 StaticCtorSection = getContext().getELFSection(
426 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
427 StaticDtorSection = getContext().getELFSection(
428 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000429}
430
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000431//===----------------------------------------------------------------------===//
432// MachO
433//===----------------------------------------------------------------------===//
434
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000435TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
436 : TargetLoweringObjectFile() {
437 SupportIndirectSymViaGOTPCRel = true;
438}
439
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000440/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
441/// option string. Returns StringRef() if the option does not specify a library.
442StringRef TargetLoweringObjectFileMachO::
443getDepLibFromLinkerOpt(StringRef LinkerOption) const {
444 const char *LibCmd = "-l";
445 if (LinkerOption.startswith(LibCmd))
446 return LinkerOption.substr(strlen(LibCmd));
447 return StringRef();
448}
449
Daniel Dunbar95856122013-01-18 19:37:00 +0000450/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000451void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000452emitModuleFlags(MCStreamer &Streamer,
453 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000454 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000455 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000456 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000457 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000458 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000459
Bill Wendling734909a2012-02-15 22:36:15 +0000460 for (ArrayRef<Module::ModuleFlagEntry>::iterator
461 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
462 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000463
464 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000465 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000466 continue;
467
Bill Wendling734909a2012-02-15 22:36:15 +0000468 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000469 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000470
Daniel Dunbar95856122013-01-18 19:37:00 +0000471 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000472 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000473 } else if (Key == "Objective-C Garbage Collection" ||
474 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000475 Key == "Objective-C Is Simulated" ||
476 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000477 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000478 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000479 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000480 } else if (Key == "Linker Options") {
481 LinkerOptions = cast<MDNode>(Val);
482 }
483 }
484
485 // Emit the linker options if present.
486 if (LinkerOptions) {
487 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
488 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
489 SmallVector<std::string, 4> StrOptions;
490
491 // Convert to strings.
492 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
493 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
494 StrOptions.push_back(MDOption->getString());
495 }
496
497 Streamer.EmitLinkerOptions(StrOptions);
498 }
Bill Wendling06df7722012-02-14 21:28:13 +0000499 }
500
Bill Wendling734909a2012-02-15 22:36:15 +0000501 // The section is mandatory. If we don't have it, then we don't have GC info.
502 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000503
Bill Wendling734909a2012-02-15 22:36:15 +0000504 StringRef Segment, Section;
505 unsigned TAA = 0, StubSize = 0;
506 bool TAAParsed;
507 std::string ErrorCode =
508 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
509 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000510 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000511 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000512 report_fatal_error("Invalid section specifier '" + Section + "': " +
513 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000514
Bill Wendling734909a2012-02-15 22:36:15 +0000515 // Get the section.
516 const MCSectionMachO *S =
517 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000518 SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000519 Streamer.SwitchSection(S);
520 Streamer.EmitLabel(getContext().
521 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000522 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000523 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000524 Streamer.AddBlankLine();
525}
526
David Majnemerdad0a642014-06-27 18:19:56 +0000527static void checkMachOComdat(const GlobalValue *GV) {
528 const Comdat *C = GV->getComdat();
529 if (!C)
530 return;
531
532 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
533 "' cannot be lowered.");
534}
535
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000536const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
537 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
538 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000539 // Parse the section specifier and create it if valid.
540 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000541 unsigned TAA = 0, StubSize = 0;
542 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000543
544 checkMachOComdat(GV);
545
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000546 std::string ErrorCode =
547 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000548 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000549 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000550 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000551 report_fatal_error("Global variable '" + GV->getName() +
552 "' has an invalid section specifier '" +
553 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000554 }
555
556 // Get the section.
557 const MCSectionMachO *S =
Chris Lattner433d4062010-04-08 20:40:11 +0000558 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000559
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000560 // If TAA wasn't set by ParseSectionSpecifier() above,
561 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000562 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000563 TAA = S->getTypeAndAttributes();
564
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000565 // Okay, now that we got the section, verify that the TAA & StubSize agree.
566 // If the user declared multiple globals with different section flags, we need
567 // to reject it here.
568 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000569 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000570 report_fatal_error("Global variable '" + GV->getName() +
571 "' section type or attributes does not match previous"
572 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000573 }
574
575 return S;
576}
577
578const MCSection *TargetLoweringObjectFileMachO::
579SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000580 Mangler &Mang, const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000581 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000582
583 // Handle thread local data.
584 if (Kind.isThreadBSS()) return TLSBSSSection;
585 if (Kind.isThreadData()) return TLSDataSection;
586
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000587 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000588 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
589
590 // If this is weak/linkonce, put this in a coalescable section, either in text
591 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000592 if (GV->isWeakForLinker()) {
593 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000594 return ConstTextCoalSection;
595 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000596 }
597
598 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000599 if (Kind.isMergeable1ByteCString() &&
Eric Christopher8b770652015-01-26 19:03:15 +0000600 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000601 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000602
Chris Lattneref2f8042010-03-07 04:28:09 +0000603 // Do not put 16-bit arrays in the UString section if they have an
604 // externally visible label, this runs into issues with certain linker
605 // versions.
606 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Eric Christopher8b770652015-01-26 19:03:15 +0000607 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000608 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000609
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000610 // With MachO only variables whose corresponding symbol starts with 'l' or
611 // 'L' can be merged, so we only try merging GVs with private linkage.
612 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000613 if (Kind.isMergeableConst4())
614 return FourByteConstantSection;
615 if (Kind.isMergeableConst8())
616 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000617 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000618 return SixteenByteConstantSection;
619 }
620
621 // Otherwise, if it is readonly, but not something we can specially optimize,
622 // just drop it in .const.
623 if (Kind.isReadOnly())
624 return ReadOnlySection;
625
626 // If this is marked const, put it into a const section. But if the dynamic
627 // linker needs to write to it, put it in the data segment.
628 if (Kind.isReadOnlyWithRel())
629 return ConstDataSection;
630
631 // Put zero initialized globals with strong external linkage in the
632 // DATA, __common section with the .zerofill directive.
633 if (Kind.isBSSExtern())
634 return DataCommonSection;
635
636 // Put zero initialized globals with local linkage in __DATA,__bss directive
637 // with the .zerofill directive (aka .lcomm).
638 if (Kind.isBSSLocal())
639 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000640
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000641 // Otherwise, just drop the variable in the normal data section.
642 return DataSection;
643}
644
645const MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000646TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
647 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000648 // If this constant requires a relocation, we have to put it in the data
649 // segment, not in the text segment.
650 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
651 return ConstDataSection;
652
653 if (Kind.isMergeableConst4())
654 return FourByteConstantSection;
655 if (Kind.isMergeableConst8())
656 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000657 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000658 return SixteenByteConstantSection;
659 return ReadOnlySection; // .const
660}
661
Rafael Espindola15b26692014-02-09 14:50:44 +0000662const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
663 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000664 const TargetMachine &TM, MachineModuleInfo *MMI,
665 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000666 // The mach-o version of this method defaults to returning a stub reference.
667
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000668 if (Encoding & DW_EH_PE_indirect) {
669 MachineModuleInfoMachO &MachOMMI =
670 MMI->getObjFileInfo<MachineModuleInfoMachO>();
671
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000672 MCSymbol *SSym =
673 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000674
675 // Add information about the stub reference to MachOMMI so that the stub
676 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000677 MachineModuleInfoImpl::StubValueTy &StubSym =
678 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
679 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000680 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000681 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000682 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000683 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000684
685 return TargetLoweringObjectFile::
Anton Korobeynikove42af362012-11-14 01:47:00 +0000686 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
687 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000688 }
689
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000690 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
691 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000692}
693
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000694MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
695 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
696 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000697 // The mach-o version of this method defaults to returning a stub reference.
698 MachineModuleInfoMachO &MachOMMI =
699 MMI->getObjFileInfo<MachineModuleInfoMachO>();
700
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000701 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000702
703 // Add information about the stub reference to MachOMMI so that the stub
704 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000705 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000706 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000707 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000708 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
709 }
710
711 return SSym;
712}
713
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000714const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
715 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
716 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
717 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
718 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
719 // through a non_lazy_ptr stub instead. One advantage is that it allows the
720 // computation of deltas to final external symbols. Example:
721 //
722 // _extgotequiv:
723 // .long _extfoo
724 //
725 // _delta:
726 // .long _extgotequiv-_delta
727 //
728 // is transformed to:
729 //
730 // _delta:
731 // .long L_extfoo$non_lazy_ptr-(_delta+0)
732 //
733 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
734 // L_extfoo$non_lazy_ptr:
735 // .indirect_symbol _extfoo
736 // .long 0
737 //
738 MachineModuleInfoMachO &MachOMMI =
739 MMI->getObjFileInfo<MachineModuleInfoMachO>();
740 MCContext &Ctx = getContext();
741
742 // The offset must consider the original displacement from the base symbol
743 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
744 Offset = -MV.getConstant();
745 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
746
747 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
748 // non_lazy_ptr stubs.
749 SmallString<128> Name;
750 StringRef Suffix = "$non_lazy_ptr";
751 Name += DL->getPrivateGlobalPrefix();
752 Name += Sym->getName();
753 Name += Suffix;
754 MCSymbol *Stub = Ctx.GetOrCreateSymbol(Name);
755
756 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
757 if (!StubSym.getPointer())
758 StubSym = MachineModuleInfoImpl::
759 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
760
761 const MCExpr *BSymExpr =
762 MCSymbolRefExpr::Create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
763 const MCExpr *LHS =
764 MCSymbolRefExpr::Create(Stub, MCSymbolRefExpr::VK_None, Ctx);
765
766 if (!Offset)
767 return MCBinaryExpr::CreateSub(LHS, BSymExpr, Ctx);
768
769 const MCExpr *RHS =
770 MCBinaryExpr::CreateAdd(BSymExpr, MCConstantExpr::Create(Offset, Ctx), Ctx);
771 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
772}
773
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000774//===----------------------------------------------------------------------===//
775// COFF
776//===----------------------------------------------------------------------===//
777
Chris Lattner87cffa92010-05-07 17:17:41 +0000778static unsigned
779getCOFFSectionFlags(SectionKind K) {
780 unsigned Flags = 0;
781
Anton Korobeynikove4152302010-07-06 15:24:56 +0000782 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000783 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000784 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000785 else if (K.isText())
786 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000787 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000788 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000789 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000790 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000791 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000792 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
793 COFF::IMAGE_SCN_MEM_READ |
794 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000795 else if (K.isThreadLocal())
796 Flags |=
797 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
798 COFF::IMAGE_SCN_MEM_READ |
799 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000800 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000801 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000802 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
803 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000804 else if (K.isWriteable())
805 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000806 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
807 COFF::IMAGE_SCN_MEM_READ |
808 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000809
810 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000811}
812
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000813static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000814 const Comdat *C = GV->getComdat();
815 assert(C && "expected GV to have a Comdat!");
816
817 StringRef ComdatGVName = C->getName();
818 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
819 if (!ComdatGV)
820 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
821 "' does not exist.");
822
823 if (ComdatGV->getComdat() != C)
824 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000825 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000826
827 return ComdatGV;
828}
829
830static int getSelectionForCOFF(const GlobalValue *GV) {
831 if (const Comdat *C = GV->getComdat()) {
832 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
833 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
834 ComdatKey = GA->getBaseObject();
835 if (ComdatKey == GV) {
836 switch (C->getSelectionKind()) {
837 case Comdat::Any:
838 return COFF::IMAGE_COMDAT_SELECT_ANY;
839 case Comdat::ExactMatch:
840 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
841 case Comdat::Largest:
842 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
843 case Comdat::NoDuplicates:
844 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
845 case Comdat::SameSize:
846 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
847 }
848 } else {
849 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
850 }
851 } else if (GV->isWeakForLinker()) {
852 return COFF::IMAGE_COMDAT_SELECT_ANY;
853 }
854 return 0;
855}
856
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000857const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
858 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
859 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000860 int Selection = 0;
861 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000862 StringRef Name = GV->getSection();
863 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000864 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000865 Selection = getSelectionForCOFF(GV);
866 const GlobalValue *ComdatGV;
867 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
868 ComdatGV = getComdatGVForCOFF(GV);
869 else
870 ComdatGV = GV;
871
872 if (!ComdatGV->hasPrivateLinkage()) {
873 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
874 COMDATSymName = Sym->getName();
875 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
876 } else {
877 Selection = 0;
878 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000879 }
880 return getContext().getCOFFSection(Name,
881 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000882 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000883 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000884 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000885}
886
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000887static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000888 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000889 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000890 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000891 return ".bss";
892 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000893 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000894 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
895 return ".rdata";
896 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000897}
898
899
900const MCSection *TargetLoweringObjectFileCOFF::
901SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000902 Mangler &Mang, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000903 // If we have -ffunction-sections then we should emit the global value to a
904 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000905 bool EmitUniquedSection;
906 if (Kind.isText())
907 EmitUniquedSection = TM.getFunctionSections();
908 else
909 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000910
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000911 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000912 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000913 unsigned Characteristics = getCOFFSectionFlags(Kind);
914
Daniel Dunbar329d2022010-07-01 20:07:24 +0000915 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000916 int Selection = getSelectionForCOFF(GV);
917 if (!Selection)
918 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
919 const GlobalValue *ComdatGV;
920 if (GV->hasComdat())
921 ComdatGV = getComdatGVForCOFF(GV);
922 else
923 ComdatGV = GV;
924
925 if (!ComdatGV->hasPrivateLinkage()) {
926 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
927 StringRef COMDATSymName = Sym->getName();
928 return getContext().getCOFFSection(Name, Characteristics, Kind,
929 COMDATSymName, Selection);
David Majnemer7db449a2015-03-17 23:54:51 +0000930 } else {
931 SmallString<256> TmpData;
932 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
933 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
934 Selection);
David Majnemerdad0a642014-06-27 18:19:56 +0000935 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000936 }
937
938 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000939 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000940
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000941 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000942 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000943
David Majnemer597be2d2014-09-22 20:39:23 +0000944 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000945 return ReadOnlySection;
946
David Majnemera9bdb322014-04-08 22:33:40 +0000947 // Note: we claim that common symbols are put in BSSSection, but they are
948 // really emitted with the magic .comm directive, which creates a symbol table
949 // entry but not a section.
950 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000951 return BSSSection;
952
953 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000954}
955
David Majnemer7db449a2015-03-17 23:54:51 +0000956void TargetLoweringObjectFileCOFF::getNameWithPrefix(
957 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
958 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
959 if (GV->hasPrivateLinkage() &&
960 ((isa<Function>(GV) && TM.getFunctionSections()) ||
961 (isa<GlobalVariable>(GV) && TM.getDataSections())))
962 CannotUsePrivateLabel = true;
963
964 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
965}
966
Rafael Espindolaab447e42015-03-11 19:58:37 +0000967const MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
968 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
969 // If the function can be removed, produce a unique section so that
970 // the table doesn't prevent the removal.
971 const Comdat *C = F.getComdat();
972 bool EmitUniqueSection = TM.getFunctionSections() || C;
973 if (!EmitUniqueSection)
974 return ReadOnlySection;
975
976 // FIXME: we should produce a symbol for F instead.
977 if (F.hasPrivateLinkage())
978 return ReadOnlySection;
979
980 MCSymbol *Sym = TM.getSymbol(&F, Mang);
981 StringRef COMDATSymName = Sym->getName();
982
983 SectionKind Kind = SectionKind::getReadOnly();
984 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
985 unsigned Characteristics = getCOFFSectionFlags(Kind);
986 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
987
988 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
989 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
990}
991
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000992StringRef TargetLoweringObjectFileCOFF::
993getDepLibFromLinkerOpt(StringRef LinkerOption) const {
994 const char *LibCmd = "/DEFAULTLIB:";
995 if (LinkerOption.startswith(LibCmd))
996 return LinkerOption.substr(strlen(LibCmd));
997 return StringRef();
998}
999
Reid Klecknerd973ca32013-04-25 19:34:41 +00001000void TargetLoweringObjectFileCOFF::
1001emitModuleFlags(MCStreamer &Streamer,
1002 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +00001003 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001004 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001005
1006 // Look for the "Linker Options" flag, since it's the only one we support.
1007 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1008 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1009 const Module::ModuleFlagEntry &MFE = *i;
1010 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001011 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001012 if (Key == "Linker Options") {
1013 LinkerOptions = cast<MDNode>(Val);
1014 break;
1015 }
1016 }
1017 if (!LinkerOptions)
1018 return;
1019
1020 // Emit the linker options to the linker .drectve section. According to the
1021 // spec, this section is a space-separated string containing flags for linker.
1022 const MCSection *Sec = getDrectveSection();
1023 Streamer.SwitchSection(Sec);
1024 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1025 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1026 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1027 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Klecknerd973ca32013-04-25 19:34:41 +00001028 // Lead with a space for consistency with our dllexport implementation.
Michael Kupersteinfc3e6262015-02-16 11:57:17 +00001029 std::string Directive(" ");
1030 Directive.append(MDOption->getString());
1031 Streamer.EmitBytes(Directive);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001032 }
1033 }
1034}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001035
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001036const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001037 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001038 return getContext().getAssociativeCOFFSection(
1039 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001040}
1041
1042const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001043 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001044 return getContext().getAssociativeCOFFSection(
1045 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001046}