blob: 2b571a02b4de224ed5e88fbf7c30ed21711331c5 [file] [log] [blame]
Eugene Zelenkofa912a72017-02-27 22:45:06 +00001//===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +00002//
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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallString.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000017#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/StringExtras.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000019#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/COFF.h"
22#include "llvm/BinaryFormat/Dwarf.h"
23#include "llvm/BinaryFormat/ELF.h"
24#include "llvm/BinaryFormat/MachO.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000027#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000032#include "llvm/IR/GlobalAlias.h"
33#include "llvm/IR/GlobalObject.h"
34#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000036#include "llvm/IR/Mangler.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000039#include "llvm/IR/Type.h"
Peter Collingbourne94d77862015-11-03 23:40:03 +000040#include "llvm/MC/MCAsmInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000041#include "llvm/MC/MCContext.h"
42#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000043#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/MC/MCSectionELF.h"
45#include "llvm/MC/MCSectionMachO.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000046#include "llvm/MC/MCSectionWasm.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000047#include "llvm/MC/MCStreamer.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000048#include "llvm/MC/MCSymbol.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000049#include "llvm/MC/MCSymbolELF.h"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000050#include "llvm/MC/MCValue.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000051#include "llvm/MC/SectionKind.h"
Xinliang David Li5f04f922016-01-14 18:09:45 +000052#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000053#include "llvm/Support/Casting.h"
54#include "llvm/Support/CodeGen.h"
Martin Storsjo04b68442017-11-28 08:07:18 +000055#include "llvm/Support/Format.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000056#include "llvm/Support/ErrorHandling.h"
57#include "llvm/Support/raw_ostream.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000058#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000059#include <cassert>
60#include <string>
61
Anton Korobeynikovab663a02010-02-15 22:37:53 +000062using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000063using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000064
Peter Collingbourne89061b22017-06-12 20:10:48 +000065static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
Saleem Abdulrasool4c474342017-06-05 21:26:39 +000066 StringRef &Section) {
Peter Collingbourne89061b22017-06-12 20:10:48 +000067 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
68 M.getModuleFlagsMetadata(ModuleFlags);
69
Saleem Abdulrasool4c474342017-06-05 21:26:39 +000070 for (const auto &MFE: ModuleFlags) {
71 // Ignore flags with 'Require' behaviour.
72 if (MFE.Behavior == Module::Require)
73 continue;
74
75 StringRef Key = MFE.Key->getString();
76 if (Key == "Objective-C Image Info Version") {
77 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78 } else if (Key == "Objective-C Garbage Collection" ||
79 Key == "Objective-C GC Only" ||
80 Key == "Objective-C Is Simulated" ||
81 Key == "Objective-C Class Properties" ||
82 Key == "Objective-C Image Swift Version") {
83 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84 } else if (Key == "Objective-C Image Info Section") {
85 Section = cast<MDString>(MFE.Val)->getString();
86 }
87 }
88}
89
Anton Korobeynikovab663a02010-02-15 22:37:53 +000090//===----------------------------------------------------------------------===//
91// ELF
92//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000093
Michael J. Spencer7bb27672018-07-16 00:28:24 +000094void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
95 const TargetMachine &TgtM) {
96 TargetLoweringObjectFile::Initialize(Ctx, TgtM);
97 TM = &TgtM;
Reid Klecknerfce7f732018-08-09 22:24:04 +000098
99 bool Large = TgtM.getCodeModel() == CodeModel::Large;
100
101 switch (TgtM.getTargetTriple().getArch()) {
102 case Triple::arm:
103 case Triple::armeb:
104 case Triple::thumb:
105 case Triple::thumbeb:
106 if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
107 break;
108 // Fallthrough if not using EHABI
109 LLVM_FALLTHROUGH;
110 case Triple::ppc:
111 case Triple::x86:
112 PersonalityEncoding = isPositionIndependent()
113 ? dwarf::DW_EH_PE_indirect |
114 dwarf::DW_EH_PE_pcrel |
115 dwarf::DW_EH_PE_sdata4
116 : dwarf::DW_EH_PE_absptr;
117 LSDAEncoding = isPositionIndependent()
118 ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
119 : dwarf::DW_EH_PE_absptr;
120 TTypeEncoding = isPositionIndependent()
121 ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
122 dwarf::DW_EH_PE_sdata4
123 : dwarf::DW_EH_PE_absptr;
124 break;
125 case Triple::x86_64:
126 if (isPositionIndependent()) {
127 PersonalityEncoding =
128 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
129 (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
130 LSDAEncoding = dwarf::DW_EH_PE_pcrel |
131 (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
132 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
133 (Large ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4);
134 } else {
135 PersonalityEncoding =
136 Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
137 LSDAEncoding = Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
138 TTypeEncoding = Large ? dwarf::DW_EH_PE_absptr : dwarf::DW_EH_PE_udata4;
139 }
140 break;
141 case Triple::hexagon:
142 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
143 LSDAEncoding = dwarf::DW_EH_PE_absptr;
144 TTypeEncoding = dwarf::DW_EH_PE_absptr;
145 if (isPositionIndependent()) {
146 PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
147 LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
148 TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
149 }
150 break;
151 case Triple::aarch64:
152 case Triple::aarch64_be:
153 // The small model guarantees static code/data size < 4GB, but not where it
154 // will be in memory. Most of these could end up >2GB away so even a signed
155 // pc-relative 32-bit address is insufficient, theoretically.
156 if (isPositionIndependent()) {
157 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
158 dwarf::DW_EH_PE_sdata8;
159 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
160 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
161 dwarf::DW_EH_PE_sdata8;
162 } else {
163 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
164 LSDAEncoding = dwarf::DW_EH_PE_absptr;
165 TTypeEncoding = dwarf::DW_EH_PE_absptr;
166 }
167 break;
168 case Triple::lanai:
169 LSDAEncoding = dwarf::DW_EH_PE_absptr;
170 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
171 TTypeEncoding = dwarf::DW_EH_PE_absptr;
172 break;
173 case Triple::mips:
174 case Triple::mipsel:
175 case Triple::mips64:
176 case Triple::mips64el:
177 // MIPS uses indirect pointer to refer personality functions and types, so
178 // that the eh_frame section can be read-only. DW.ref.personality will be
179 // generated for relocation.
180 PersonalityEncoding = dwarf::DW_EH_PE_indirect;
181 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
182 // identify N64 from just a triple.
183 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
184 dwarf::DW_EH_PE_sdata4;
185 // We don't support PC-relative LSDA references in GAS so we use the default
186 // DW_EH_PE_absptr for those.
187
188 // FreeBSD must be explicit about the data size and using pcrel since it's
189 // assembler/linker won't do the automatic conversion that the Linux tools
190 // do.
191 if (TgtM.getTargetTriple().isOSFreeBSD()) {
192 PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
193 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
194 }
195 break;
196 case Triple::ppc64:
197 case Triple::ppc64le:
198 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
199 dwarf::DW_EH_PE_udata8;
200 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
201 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
202 dwarf::DW_EH_PE_udata8;
203 break;
204 case Triple::sparcel:
205 case Triple::sparc:
206 if (isPositionIndependent()) {
207 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
208 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
209 dwarf::DW_EH_PE_sdata4;
210 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
211 dwarf::DW_EH_PE_sdata4;
212 } else {
213 LSDAEncoding = dwarf::DW_EH_PE_absptr;
214 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
215 TTypeEncoding = dwarf::DW_EH_PE_absptr;
216 }
217 break;
218 case Triple::sparcv9:
219 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
220 if (isPositionIndependent()) {
221 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
222 dwarf::DW_EH_PE_sdata4;
223 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
224 dwarf::DW_EH_PE_sdata4;
225 } else {
226 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
227 TTypeEncoding = dwarf::DW_EH_PE_absptr;
228 }
229 break;
230 case Triple::systemz:
231 // All currently-defined code models guarantee that 4-byte PC-relative
232 // values will be in range.
233 if (isPositionIndependent()) {
234 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
235 dwarf::DW_EH_PE_sdata4;
236 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
237 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
238 dwarf::DW_EH_PE_sdata4;
239 } else {
240 PersonalityEncoding = dwarf::DW_EH_PE_absptr;
241 LSDAEncoding = dwarf::DW_EH_PE_absptr;
242 TTypeEncoding = dwarf::DW_EH_PE_absptr;
243 }
244 break;
245 default:
246 break;
247 }
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000248}
249
Eric Christopheraadbabc2018-04-20 19:07:57 +0000250void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
251 Module &M) const {
Saleem Abdulrasoolb36fbbc2018-01-30 16:29:29 +0000252 auto &C = getContext();
253
254 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
255 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
256 ELF::SHF_EXCLUDE);
257
258 Streamer.SwitchSection(S);
259
260 for (const auto &Operand : LinkerOptions->operands()) {
261 if (cast<MDNode>(Operand)->getNumOperands() != 2)
262 report_fatal_error("invalid llvm.linker.options");
263 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
264 Streamer.EmitBytes(cast<MDString>(Option)->getString());
265 Streamer.EmitIntValue(0, 1);
266 }
267 }
268 }
269
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000270 unsigned Version = 0;
271 unsigned Flags = 0;
272 StringRef Section;
273
Peter Collingbourne89061b22017-06-12 20:10:48 +0000274 GetObjCImageInfo(M, Version, Flags, Section);
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000275 if (!Section.empty()) {
276 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
277 Streamer.SwitchSection(S);
278 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
279 Streamer.EmitIntValue(Version, 4);
280 Streamer.EmitIntValue(Flags, 4);
281 Streamer.AddBlankLine();
282 }
283
284 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
285 M.getModuleFlagsMetadata(ModuleFlags);
286
287 MDNode *CFGProfile = nullptr;
288
289 for (const auto &MFE : ModuleFlags) {
290 StringRef Key = MFE.Key->getString();
291 if (Key == "CG Profile") {
292 CFGProfile = cast<MDNode>(MFE.Val);
293 break;
294 }
295 }
296
297 if (!CFGProfile)
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000298 return;
299
Michael J. Spencer7bb27672018-07-16 00:28:24 +0000300 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
301 if (!MDO)
302 return nullptr;
303 auto V = cast<ValueAsMetadata>(MDO);
304 const Function *F = cast<Function>(V->getValue());
305 return TM->getSymbol(F);
306 };
307
308 for (const auto &Edge : CFGProfile->operands()) {
309 MDNode *E = cast<MDNode>(Edge);
310 const MCSymbol *From = GetSym(E->getOperand(0));
311 const MCSymbol *To = GetSym(E->getOperand(1));
312 // Skip null functions. This can happen if functions are dead stripped after
313 // the CGProfile pass has been run.
314 if (!From || !To)
315 continue;
316 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
317 ->getValue()
318 ->getUniqueInteger()
319 .getZExtValue();
320 Streamer.emitCGProfileEntry(
321 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
322 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
323 }
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000324}
325
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000326MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000327 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000328 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +0000329 unsigned Encoding = getPersonalityEncoding();
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000330 if ((Encoding & 0x80) == DW_EH_PE_indirect)
Jim Grosbach6f482002015-05-18 18:43:14 +0000331 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
Tim Northoverb64fb452016-11-22 16:17:20 +0000332 TM.getSymbol(GV)->getName());
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000333 if ((Encoding & 0x70) == DW_EH_PE_absptr)
Tim Northoverb64fb452016-11-22 16:17:20 +0000334 return TM.getSymbol(GV);
Logan Chienc0029812014-05-30 16:48:56 +0000335 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000336}
337
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000338void TargetLoweringObjectFileELF::emitPersonalityValue(
339 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +0000340 SmallString<64> NameData("DW.ref.");
341 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +0000342 MCSymbolELF *Label =
343 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +0000344 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
345 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola39897762011-04-27 21:29:52 +0000346 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Eric Christopher36e601c2016-07-01 06:07:38 +0000347 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
348 ELF::SHT_PROGBITS, Flags, 0);
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000349 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +0000350 Streamer.SwitchSection(Sec);
Fangrui Songe73534462017-11-15 06:17:32 +0000351 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
Rafael Espindola39897762011-04-27 21:29:52 +0000352 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000353 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +0000354 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +0000355 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000356
Rafael Espindola39897762011-04-27 21:29:52 +0000357 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000358}
359
Rafael Espindola15b26692014-02-09 14:50:44 +0000360const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000361 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
362 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000363 if (Encoding & DW_EH_PE_indirect) {
Anton Korobeynikove42af362012-11-14 01:47:00 +0000364 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
365
Eric Christopher4367c7f2016-09-16 07:33:15 +0000366 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000367
368 // Add information about the stub reference to ELFMMI so that the stub
369 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +0000370 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000371 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000372 MCSymbol *Sym = TM.getSymbol(GV);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000373 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
374 }
375
376 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000377 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000378 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000379 }
380
Eric Christopher4367c7f2016-09-16 07:33:15 +0000381 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
382 MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000383}
384
Sam Clegg12fd3da2017-10-20 21:28:38 +0000385static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
Eric Christopher1f5eb862018-05-16 20:34:00 +0000386 // N.B.: The defaults used in here are not the same ones used in MC.
Rafael Espindola0d018b12011-05-24 03:10:31 +0000387 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
388 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000389 // section(".eh_frame") gcc will produce:
390 //
391 // .section .eh_frame,"a",@progbits
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000392
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000393 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
394 /*AddSegmentInfo=*/false))
Xinliang David Li5f04f922016-01-14 18:09:45 +0000395 return SectionKind::getMetadata();
396
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000397 if (Name.empty() || Name[0] != '.') return K;
398
Eric Christopherf31e91e2018-05-18 02:39:57 +0000399 // Default implementation based on some magic section names.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000400 if (Name == ".bss" ||
401 Name.startswith(".bss.") ||
402 Name.startswith(".gnu.linkonce.b.") ||
403 Name.startswith(".llvm.linkonce.b.") ||
404 Name == ".sbss" ||
405 Name.startswith(".sbss.") ||
406 Name.startswith(".gnu.linkonce.sb.") ||
407 Name.startswith(".llvm.linkonce.sb."))
408 return SectionKind::getBSS();
409
410 if (Name == ".tdata" ||
411 Name.startswith(".tdata.") ||
412 Name.startswith(".gnu.linkonce.td.") ||
413 Name.startswith(".llvm.linkonce.td."))
414 return SectionKind::getThreadData();
415
416 if (Name == ".tbss" ||
417 Name.startswith(".tbss.") ||
418 Name.startswith(".gnu.linkonce.tb.") ||
419 Name.startswith(".llvm.linkonce.tb."))
420 return SectionKind::getThreadBSS();
421
422 return K;
423}
424
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000425static unsigned getELFSectionType(StringRef Name, SectionKind K) {
Petr Hosek12903552016-09-20 20:21:13 +0000426 // Use SHT_NOTE for section whose name starts with ".note" to allow
427 // emitting ELF notes from C variable declaration.
428 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
429 if (Name.startswith(".note"))
430 return ELF::SHT_NOTE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000431
432 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000433 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000434
435 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000436 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000437
438 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000439 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000440
441 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000442 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000443
Rafael Espindolaaea49582011-01-23 04:28:49 +0000444 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000445}
446
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000447static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000448 unsigned Flags = 0;
449
450 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000451 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000452
453 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000454 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000455
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000456 if (K.isExecuteOnly())
457 Flags |= ELF::SHF_ARM_PURECODE;
458
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000459 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000460 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000461
462 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000463 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000464
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000465 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000466 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000467
468 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000469 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000470
471 return Flags;
472}
473
David Majnemerdad0a642014-06-27 18:19:56 +0000474static const Comdat *getELFComdat(const GlobalValue *GV) {
475 const Comdat *C = GV->getComdat();
476 if (!C)
477 return nullptr;
478
479 if (C->getSelectionKind() != Comdat::Any)
480 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
481 C->getName() + "' cannot be lowered.");
482
483 return C;
484}
485
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000486static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
487 const TargetMachine &TM) {
488 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
489 if (!MD)
490 return nullptr;
491
Evgeniy Stepanovf7e8acf2017-05-08 23:46:20 +0000492 const MDOperand &Op = MD->getOperand(0);
493 if (!Op.get())
494 return nullptr;
495
496 auto *VM = dyn_cast<ValueAsMetadata>(Op);
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000497 if (!VM)
498 report_fatal_error("MD_associated operand is not ValueAsMetadata");
499
500 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
501 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
502}
503
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000504MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000505 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
506 StringRef SectionName = GO->getSection();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000507
Javed Absarb16d1462017-06-05 10:09:13 +0000508 // Check if '#pragma clang section' name is applicable.
509 // Note that pragma directive overrides -ffunction-section, -fdata-section
510 // and so section name is exactly as user specified and not uniqued.
511 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
512 if (GV && GV->hasImplicitSection()) {
513 auto Attrs = GV->getAttributes();
514 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
515 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
516 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
517 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
518 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
519 SectionName = Attrs.getAttribute("data-section").getValueAsString();
520 }
521 }
522 const Function *F = dyn_cast<Function>(GO);
523 if (F && F->hasFnAttribute("implicit-section-name")) {
524 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
525 }
526
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000527 // Infer section flags from the section name if we can.
528 Kind = getELFKindForNamedSection(SectionName, Kind);
529
David Majnemerdad0a642014-06-27 18:19:56 +0000530 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000531 unsigned Flags = getELFSectionFlags(Kind);
Peter Collingbourne67335642016-10-24 19:23:39 +0000532 if (const Comdat *C = getELFComdat(GO)) {
David Majnemerdad0a642014-06-27 18:19:56 +0000533 Group = C->getName();
534 Flags |= ELF::SHF_GROUP;
535 }
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000536
537 // A section can have at most one associated section. Put each global with
538 // MD_associated in a unique section.
539 unsigned UniqueID = MCContext::GenericSectionID;
540 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
541 if (AssociatedSymbol) {
542 UniqueID = NextUniqueID++;
543 Flags |= ELF::SHF_LINK_ORDER;
544 }
545
546 MCSectionELF *Section = getContext().getELFSection(
547 SectionName, getELFSectionType(SectionName, Kind), Flags,
548 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
549 // Make sure that we did not get some other section with incompatible sh_link.
550 // This should not be possible due to UniqueID code above.
Eric Christopher76cfef42018-06-21 07:15:14 +0000551 assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
552 "Associated symbol mismatch between sections");
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000553 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000554}
555
Rafael Espindola25d2c202015-02-11 14:44:17 +0000556/// Return the section prefix name used by options FunctionsSections and
557/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000558static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000559 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000560 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000561 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000562 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000563 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000564 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000565 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000566 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000567 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000568 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000569 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000570 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000571 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000572 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000573}
574
Eric Christopher7a70be62018-08-01 01:29:30 +0000575static unsigned getEntrySizeForKind(SectionKind Kind) {
576 if (Kind.isMergeable1ByteCString())
577 return 1;
578 else if (Kind.isMergeable2ByteCString())
579 return 2;
580 else if (Kind.isMergeable4ByteCString())
581 return 4;
582 else if (Kind.isMergeableConst4())
583 return 4;
584 else if (Kind.isMergeableConst8())
585 return 8;
586 else if (Kind.isMergeableConst16())
587 return 16;
588 else if (Kind.isMergeableConst32())
589 return 32;
590 else {
591 // We shouldn't have mergeable C strings or mergeable constants that we
592 // didn't handle above.
593 assert(!Kind.isMergeableCString() && "unknown string width");
594 assert(!Kind.isMergeableConst() && "unknown data width");
595 return 0;
596 }
597}
598
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000599static MCSectionELF *selectELFSectionForGlobal(
600 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
601 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
602 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000603
Rafael Espindola9075f772015-02-20 23:28:28 +0000604 StringRef Group = "";
Peter Collingbourne67335642016-10-24 19:23:39 +0000605 if (const Comdat *C = getELFComdat(GO)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000606 Flags |= ELF::SHF_GROUP;
607 Group = C->getName();
608 }
609
Eric Christopher7a70be62018-08-01 01:29:30 +0000610 // Get the section entry size based on the kind.
611 unsigned EntrySize = getEntrySizeForKind(Kind);
612
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000613 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000614 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000615 // We also need alignment here.
616 // FIXME: this is getting the alignment of the character, not the
617 // alignment of the global!
Peter Collingbourne67335642016-10-24 19:23:39 +0000618 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
619 cast<GlobalVariable>(GO));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000620
Rafael Espindolaba31e272015-01-29 17:33:21 +0000621 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000622 Name = SizeSpec + utostr(Align);
623 } else if (Kind.isMergeableConst()) {
624 Name = ".rodata.cst";
625 Name += utostr(EntrySize);
626 } else {
627 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000628 }
Dehao Chen302b69c2016-10-18 20:42:47 +0000629
Peter Collingbourne67335642016-10-24 19:23:39 +0000630 if (const auto *F = dyn_cast<Function>(GO)) {
Dehao Chen302b69c2016-10-18 20:42:47 +0000631 const auto &OptionalPrefix = F->getSectionPrefix();
632 if (OptionalPrefix)
633 Name += *OptionalPrefix;
634 }
Dehao Chenf84b6302016-02-23 03:39:24 +0000635
Reid Kleckner97837b72016-05-02 23:22:18 +0000636 unsigned UniqueID = MCContext::GenericSectionID;
Eric Christopherad36c742018-08-01 01:03:34 +0000637 if (EmitUniqueSection) {
638 if (TM.getUniqueSectionNames()) {
639 Name.push_back('.');
640 TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
641 } else {
642 UniqueID = *NextUniqueID;
643 (*NextUniqueID)++;
644 }
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000645 }
Eric Christopherad36c742018-08-01 01:03:34 +0000646 // Use 0 as the unique ID for execute-only text.
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000647 if (Kind.isExecuteOnly())
648 UniqueID = 0;
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000649 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000650 EntrySize, Group, UniqueID, AssociatedSymbol);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000651}
652
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000653MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000654 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000655 unsigned Flags = getELFSectionFlags(Kind);
656
657 // If we have -ffunction-section or -fdata-section then we should emit the
658 // global value to a uniqued section specifically for it.
659 bool EmitUniqueSection = false;
660 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
661 if (Kind.isText())
662 EmitUniqueSection = TM.getFunctionSections();
663 else
664 EmitUniqueSection = TM.getDataSections();
665 }
Peter Collingbourne67335642016-10-24 19:23:39 +0000666 EmitUniqueSection |= GO->hasComdat();
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000667
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000668 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
669 if (AssociatedSymbol) {
670 EmitUniqueSection = true;
671 Flags |= ELF::SHF_LINK_ORDER;
672 }
673
674 MCSectionELF *Section = selectELFSectionForGlobal(
675 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
676 &NextUniqueID, AssociatedSymbol);
677 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
678 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000679}
680
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000681MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000682 const Function &F, const TargetMachine &TM) const {
Rafael Espindola29786d42015-02-12 17:16:46 +0000683 // If the function can be removed, produce a unique section so that
684 // the table doesn't prevent the removal.
685 const Comdat *C = F.getComdat();
686 bool EmitUniqueSection = TM.getFunctionSections() || C;
687 if (!EmitUniqueSection)
688 return ReadOnlySection;
689
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000690 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000691 getMangler(), TM, EmitUniqueSection,
692 ELF::SHF_ALLOC, &NextUniqueID,
693 /* AssociatedSymbol */ nullptr);
Rafael Espindola29786d42015-02-12 17:16:46 +0000694}
695
Rafael Espindoladf195192015-02-17 23:34:51 +0000696bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
697 bool UsesLabelDifference, const Function &F) const {
698 // We can always create relative relocations, so use another section
699 // that can be marked non-executable.
700 return false;
701}
702
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000703/// Given a mergeable constant with the specified size and relocation
704/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000705MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000706 const DataLayout &DL, SectionKind Kind, const Constant *C,
707 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000708 if (Kind.isMergeableConst4() && MergeableConst4Section)
709 return MergeableConst4Section;
710 if (Kind.isMergeableConst8() && MergeableConst8Section)
711 return MergeableConst8Section;
712 if (Kind.isMergeableConst16() && MergeableConst16Section)
713 return MergeableConst16Section;
David Majnemer964b70d2016-02-22 22:23:11 +0000714 if (Kind.isMergeableConst32() && MergeableConst32Section)
715 return MergeableConst32Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000716 if (Kind.isReadOnly())
717 return ReadOnlySection;
718
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000719 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
720 return DataRelROSection;
721}
722
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000723static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
724 bool IsCtor, unsigned Priority,
725 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000726 std::string Name;
727 unsigned Type;
728 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000729 StringRef COMDAT = KeySym ? KeySym->getName() : "";
730
731 if (KeySym)
732 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000733
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000734 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000735 if (IsCtor) {
736 Type = ELF::SHT_INIT_ARRAY;
737 Name = ".init_array";
738 } else {
739 Type = ELF::SHT_FINI_ARRAY;
740 Name = ".fini_array";
741 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000742 if (Priority != 65535) {
743 Name += '.';
744 Name += utostr(Priority);
745 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000746 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000747 // The default scheme is .ctor / .dtor, so we have to invert the priority
748 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000749 if (IsCtor)
750 Name = ".ctors";
751 else
752 Name = ".dtors";
Martin Storsjo04b68442017-11-28 08:07:18 +0000753 if (Priority != 65535)
754 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
Rafael Espindolac4b42532014-09-04 23:03:58 +0000755 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000756 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000757
Rafael Espindolaba31e272015-01-29 17:33:21 +0000758 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000759}
760
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000761MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000762 unsigned Priority, const MCSymbol *KeySym) const {
763 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
764 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000765}
766
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000767MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000768 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000769 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
770 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000771}
772
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000773const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000774 const GlobalValue *LHS, const GlobalValue *RHS,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000775 const TargetMachine &TM) const {
776 // We may only use a PLT-relative relocation to refer to unnamed_addr
777 // functions.
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000778 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000779 return nullptr;
780
781 // Basic sanity checks.
782 if (LHS->getType()->getPointerAddressSpace() != 0 ||
783 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
784 RHS->isThreadLocal())
785 return nullptr;
786
787 return MCBinaryExpr::createSub(
Tim Northoverb64fb452016-11-22 16:17:20 +0000788 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000789 getContext()),
Tim Northoverb64fb452016-11-22 16:17:20 +0000790 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000791}
792
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000793void
794TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
795 UseInitArray = UseInitArray_;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000796 MCContext &Ctx = getContext();
797 if (!UseInitArray) {
798 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
799 ELF::SHF_ALLOC | ELF::SHF_WRITE);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000800
Rafael Espindola46fa2312016-08-29 12:33:42 +0000801 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
802 ELF::SHF_ALLOC | ELF::SHF_WRITE);
803 return;
804 }
805
806 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
807 ELF::SHF_WRITE | ELF::SHF_ALLOC);
808 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
809 ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000810}
811
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000812//===----------------------------------------------------------------------===//
813// MachO
814//===----------------------------------------------------------------------===//
815
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000816TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
817 : TargetLoweringObjectFile() {
818 SupportIndirectSymViaGOTPCRel = true;
819}
820
Rafael Espindola46fa2312016-08-29 12:33:42 +0000821void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
822 const TargetMachine &TM) {
823 TargetLoweringObjectFile::Initialize(Ctx, TM);
Rafael Espindola412a5292016-08-29 12:47:22 +0000824 if (TM.getRelocationModel() == Reloc::Static) {
Rafael Espindola46fa2312016-08-29 12:33:42 +0000825 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
826 SectionKind::getData());
827 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
828 SectionKind::getData());
829 } else {
830 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
831 MachO::S_MOD_INIT_FUNC_POINTERS,
832 SectionKind::getData());
833 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
834 MachO::S_MOD_TERM_FUNC_POINTERS,
835 SectionKind::getData());
836 }
Reid Klecknerfce7f732018-08-09 22:24:04 +0000837
838 PersonalityEncoding =
839 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
840 LSDAEncoding = dwarf::DW_EH_PE_pcrel;
841 TTypeEncoding =
842 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000843}
844
Eric Christopheraadbabc2018-04-20 19:07:57 +0000845void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
846 Module &M) const {
Daniel Dunbar95856122013-01-18 19:37:00 +0000847 // Emit the linker options if present.
Peter Collingbourne89061b22017-06-12 20:10:48 +0000848 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000849 for (const auto &Option : LinkerOptions->operands()) {
Daniel Dunbar95856122013-01-18 19:37:00 +0000850 SmallVector<std::string, 4> StrOptions;
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000851 for (const auto &Piece : cast<MDNode>(Option)->operands())
852 StrOptions.push_back(cast<MDString>(Piece)->getString());
Daniel Dunbar95856122013-01-18 19:37:00 +0000853 Streamer.EmitLinkerOptions(StrOptions);
854 }
Bill Wendling06df7722012-02-14 21:28:13 +0000855 }
856
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000857 unsigned VersionVal = 0;
858 unsigned ImageInfoFlags = 0;
859 StringRef SectionVal;
Peter Collingbourne89061b22017-06-12 20:10:48 +0000860
861 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000862
Bill Wendling734909a2012-02-15 22:36:15 +0000863 // The section is mandatory. If we don't have it, then we don't have GC info.
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000864 if (SectionVal.empty())
865 return;
Bill Wendling06df7722012-02-14 21:28:13 +0000866
Bill Wendling734909a2012-02-15 22:36:15 +0000867 StringRef Segment, Section;
868 unsigned TAA = 0, StubSize = 0;
869 bool TAAParsed;
870 std::string ErrorCode =
871 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
872 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000873 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000874 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000875 report_fatal_error("Invalid section specifier '" + Section + "': " +
876 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000877
Bill Wendling734909a2012-02-15 22:36:15 +0000878 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000879 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000880 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000881 Streamer.SwitchSection(S);
882 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000883 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000884 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000885 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000886 Streamer.AddBlankLine();
887}
888
David Majnemerdad0a642014-06-27 18:19:56 +0000889static void checkMachOComdat(const GlobalValue *GV) {
890 const Comdat *C = GV->getComdat();
891 if (!C)
892 return;
893
894 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
895 "' cannot be lowered.");
896}
897
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000898MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000899 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000900 // Parse the section specifier and create it if valid.
901 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000902 unsigned TAA = 0, StubSize = 0;
903 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000904
Peter Collingbourne67335642016-10-24 19:23:39 +0000905 checkMachOComdat(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000906
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000907 std::string ErrorCode =
Peter Collingbourne67335642016-10-24 19:23:39 +0000908 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000909 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000910 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000911 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000912 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000913 "' has an invalid section specifier '" +
Peter Collingbourne67335642016-10-24 19:23:39 +0000914 GO->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000915 }
916
917 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000918 MCSectionMachO *S =
919 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000920
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000921 // If TAA wasn't set by ParseSectionSpecifier() above,
922 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000923 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000924 TAA = S->getTypeAndAttributes();
925
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000926 // Okay, now that we got the section, verify that the TAA & StubSize agree.
927 // If the user declared multiple globals with different section flags, we need
928 // to reject it here.
929 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000930 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000931 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000932 "' section type or attributes does not match previous"
933 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000934 }
935
936 return S;
937}
938
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000939MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000940 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
941 checkMachOComdat(GO);
Bill Wendling25b61db2013-11-17 10:53:13 +0000942
943 // Handle thread local data.
944 if (Kind.isThreadBSS()) return TLSBSSSection;
945 if (Kind.isThreadData()) return TLSDataSection;
946
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000947 if (Kind.isText())
Peter Collingbourne67335642016-10-24 19:23:39 +0000948 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000949
950 // If this is weak/linkonce, put this in a coalescable section, either in text
951 // or data depending on if it is writable.
Peter Collingbourne67335642016-10-24 19:23:39 +0000952 if (GO->isWeakForLinker()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000953 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000954 return ConstTextCoalSection;
Steven Wud0804aa2018-04-10 20:16:35 +0000955 if (Kind.isReadOnlyWithRel())
956 return ConstDataCoalSection;
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000957 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000958 }
959
960 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000961 if (Kind.isMergeable1ByteCString() &&
Peter Collingbourne67335642016-10-24 19:23:39 +0000962 GO->getParent()->getDataLayout().getPreferredAlignment(
963 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000964 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000965
Chris Lattneref2f8042010-03-07 04:28:09 +0000966 // Do not put 16-bit arrays in the UString section if they have an
967 // externally visible label, this runs into issues with certain linker
968 // versions.
Peter Collingbourne67335642016-10-24 19:23:39 +0000969 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
970 GO->getParent()->getDataLayout().getPreferredAlignment(
971 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000972 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000973
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000974 // With MachO only variables whose corresponding symbol starts with 'l' or
975 // 'L' can be merged, so we only try merging GVs with private linkage.
Peter Collingbourne67335642016-10-24 19:23:39 +0000976 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000977 if (Kind.isMergeableConst4())
978 return FourByteConstantSection;
979 if (Kind.isMergeableConst8())
980 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000981 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000982 return SixteenByteConstantSection;
983 }
984
985 // Otherwise, if it is readonly, but not something we can specially optimize,
986 // just drop it in .const.
987 if (Kind.isReadOnly())
988 return ReadOnlySection;
989
990 // If this is marked const, put it into a const section. But if the dynamic
991 // linker needs to write to it, put it in the data segment.
992 if (Kind.isReadOnlyWithRel())
993 return ConstDataSection;
994
995 // Put zero initialized globals with strong external linkage in the
996 // DATA, __common section with the .zerofill directive.
997 if (Kind.isBSSExtern())
998 return DataCommonSection;
999
1000 // Put zero initialized globals with local linkage in __DATA,__bss directive
1001 // with the .zerofill directive (aka .lcomm).
1002 if (Kind.isBSSLocal())
1003 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +00001004
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001005 // Otherwise, just drop the variable in the normal data section.
1006 return DataSection;
1007}
1008
Mehdi Amini5c0fa582015-07-16 06:04:17 +00001009MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +00001010 const DataLayout &DL, SectionKind Kind, const Constant *C,
1011 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001012 // If this constant requires a relocation, we have to put it in the data
1013 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +00001014 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001015 return ConstDataSection;
1016
1017 if (Kind.isMergeableConst4())
1018 return FourByteConstantSection;
1019 if (Kind.isMergeableConst8())
1020 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +00001021 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001022 return SixteenByteConstantSection;
1023 return ReadOnlySection; // .const
1024}
1025
Rafael Espindola15b26692014-02-09 14:50:44 +00001026const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001027 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1028 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001029 // The mach-o version of this method defaults to returning a stub reference.
1030
Anton Korobeynikov31a92122010-02-21 20:28:15 +00001031 if (Encoding & DW_EH_PE_indirect) {
1032 MachineModuleInfoMachO &MachOMMI =
1033 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1034
Eric Christopher4367c7f2016-09-16 07:33:15 +00001035 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +00001036
1037 // Add information about the stub reference to MachOMMI so that the stub
1038 // gets emitted by the asmprinter.
Rafael Espindola712f9572016-05-17 16:01:32 +00001039 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +00001040 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001041 MCSymbol *Sym = TM.getSymbol(GV);
Chris Lattner2ea586b2010-03-15 20:37:38 +00001042 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +00001043 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001044
1045 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +00001046 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +00001047 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001048 }
1049
Eric Christopher4367c7f2016-09-16 07:33:15 +00001050 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1051 MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001052}
1053
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001054MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001055 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +00001056 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +00001057 // The mach-o version of this method defaults to returning a stub reference.
1058 MachineModuleInfoMachO &MachOMMI =
1059 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1060
Eric Christopher4367c7f2016-09-16 07:33:15 +00001061 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Rafael Espindola08704342011-04-27 23:08:15 +00001062
1063 // Add information about the stub reference to MachOMMI so that the stub
1064 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +00001065 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +00001066 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001067 MCSymbol *Sym = TM.getSymbol(GV);
Rafael Espindola08704342011-04-27 23:08:15 +00001068 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1069 }
1070
1071 return SSym;
1072}
1073
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001074const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1075 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
1076 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001077 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001078 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1079 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1080 // computation of deltas to final external symbols. Example:
1081 //
1082 // _extgotequiv:
1083 // .long _extfoo
1084 //
1085 // _delta:
1086 // .long _extgotequiv-_delta
1087 //
1088 // is transformed to:
1089 //
1090 // _delta:
1091 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1092 //
1093 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1094 // L_extfoo$non_lazy_ptr:
1095 // .indirect_symbol _extfoo
1096 // .long 0
1097 //
1098 MachineModuleInfoMachO &MachOMMI =
1099 MMI->getObjFileInfo<MachineModuleInfoMachO>();
1100 MCContext &Ctx = getContext();
1101
1102 // The offset must consider the original displacement from the base symbol
1103 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1104 Offset = -MV.getConstant();
1105 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1106
1107 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1108 // non_lazy_ptr stubs.
1109 SmallString<128> Name;
1110 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +00001111 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001112 Name += Sym->getName();
1113 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +00001114 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001115
1116 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1117 if (!StubSym.getPointer())
1118 StubSym = MachineModuleInfoImpl::
1119 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
1120
1121 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +00001122 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001123 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +00001124 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001125
1126 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +00001127 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001128
1129 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +00001130 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1131 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +00001132}
1133
Peter Collingbourne94d77862015-11-03 23:40:03 +00001134static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1135 const MCSection &Section) {
1136 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1137 return true;
1138
1139 // If it is not dead stripped, it is safe to use private labels.
1140 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
1141 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
1142 return true;
1143
1144 return false;
1145}
1146
1147void TargetLoweringObjectFileMachO::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001148 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001149 const TargetMachine &TM) const {
Peter Collingbourne67335642016-10-24 19:23:39 +00001150 bool CannotUsePrivateLabel = true;
1151 if (auto *GO = GV->getBaseObject()) {
1152 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1153 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1154 CannotUsePrivateLabel =
1155 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1156 }
Eric Christopher4367c7f2016-09-16 07:33:15 +00001157 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
Peter Collingbourne94d77862015-11-03 23:40:03 +00001158}
1159
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001160//===----------------------------------------------------------------------===//
1161// COFF
1162//===----------------------------------------------------------------------===//
1163
Chris Lattner87cffa92010-05-07 17:17:41 +00001164static unsigned
Renato Golinef3eb062016-06-27 14:42:20 +00001165getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
Chris Lattner87cffa92010-05-07 17:17:41 +00001166 unsigned Flags = 0;
Renato Golinef3eb062016-06-27 14:42:20 +00001167 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
Chris Lattner87cffa92010-05-07 17:17:41 +00001168
Anton Korobeynikove4152302010-07-06 15:24:56 +00001169 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +00001170 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +00001171 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +00001172 else if (K.isText())
1173 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +00001174 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +00001175 COFF::IMAGE_SCN_MEM_READ |
Renato Golinef3eb062016-06-27 14:42:20 +00001176 COFF::IMAGE_SCN_CNT_CODE |
1177 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
David Majnemerb8dbebb2014-09-20 07:31:46 +00001178 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +00001179 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +00001180 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1181 COFF::IMAGE_SCN_MEM_READ |
1182 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001183 else if (K.isThreadLocal())
1184 Flags |=
1185 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1186 COFF::IMAGE_SCN_MEM_READ |
1187 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +00001188 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +00001189 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +00001190 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1191 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +00001192 else if (K.isWriteable())
1193 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +00001194 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1195 COFF::IMAGE_SCN_MEM_READ |
1196 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +00001197
1198 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001199}
1200
Benjamin Kramer6cbe6702014-07-07 14:47:51 +00001201static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +00001202 const Comdat *C = GV->getComdat();
1203 assert(C && "expected GV to have a Comdat!");
1204
1205 StringRef ComdatGVName = C->getName();
1206 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1207 if (!ComdatGV)
1208 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1209 "' does not exist.");
1210
1211 if (ComdatGV->getComdat() != C)
1212 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +00001213 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +00001214
1215 return ComdatGV;
1216}
1217
1218static int getSelectionForCOFF(const GlobalValue *GV) {
1219 if (const Comdat *C = GV->getComdat()) {
1220 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1221 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1222 ComdatKey = GA->getBaseObject();
1223 if (ComdatKey == GV) {
1224 switch (C->getSelectionKind()) {
1225 case Comdat::Any:
1226 return COFF::IMAGE_COMDAT_SELECT_ANY;
1227 case Comdat::ExactMatch:
1228 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1229 case Comdat::Largest:
1230 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1231 case Comdat::NoDuplicates:
1232 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1233 case Comdat::SameSize:
1234 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1235 }
1236 } else {
1237 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1238 }
David Majnemerdad0a642014-06-27 18:19:56 +00001239 }
1240 return 0;
1241}
1242
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001243MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001244 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001245 int Selection = 0;
Renato Golinef3eb062016-06-27 14:42:20 +00001246 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Peter Collingbourne67335642016-10-24 19:23:39 +00001247 StringRef Name = GO->getSection();
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001248 StringRef COMDATSymName = "";
Peter Collingbourne67335642016-10-24 19:23:39 +00001249 if (GO->hasComdat()) {
1250 Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001251 const GlobalValue *ComdatGV;
1252 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
Peter Collingbourne67335642016-10-24 19:23:39 +00001253 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001254 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001255 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001256
1257 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001258 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001259 COMDATSymName = Sym->getName();
1260 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1261 } else {
1262 Selection = 0;
1263 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001264 }
Reid Kleckner97837b72016-05-02 23:22:18 +00001265
1266 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +00001267 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001268}
1269
Reid Kleckner13c9ee62018-06-21 20:27:38 +00001270static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001271 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001272 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +00001273 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001274 return ".bss";
1275 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +00001276 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +00001277 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1278 return ".rdata";
1279 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001280}
1281
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001282MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001283 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +00001284 // If we have -ffunction-sections then we should emit the global value to a
1285 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +00001286 bool EmitUniquedSection;
1287 if (Kind.isText())
1288 EmitUniquedSection = TM.getFunctionSections();
1289 else
1290 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001291
Peter Collingbourne67335642016-10-24 19:23:39 +00001292 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
Reid Kleckner13c9ee62018-06-21 20:27:38 +00001293 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1294
Renato Golinef3eb062016-06-27 14:42:20 +00001295 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Chris Lattner02844932010-05-07 21:49:09 +00001296
Daniel Dunbar329d2022010-07-01 20:07:24 +00001297 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Peter Collingbourne67335642016-10-24 19:23:39 +00001298 int Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001299 if (!Selection)
1300 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1301 const GlobalValue *ComdatGV;
Peter Collingbourne67335642016-10-24 19:23:39 +00001302 if (GO->hasComdat())
1303 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001304 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001305 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001306
Reid Kleckner97837b72016-05-02 23:22:18 +00001307 unsigned UniqueID = MCContext::GenericSectionID;
1308 if (EmitUniquedSection)
1309 UniqueID = NextUniqueID++;
1310
David Majnemerdad0a642014-06-27 18:19:56 +00001311 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001312 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001313 StringRef COMDATSymName = Sym->getName();
Reid Kleckner2ef48662018-06-21 23:06:33 +00001314
1315 // Append "$symbol" to the section name when targetting mingw. The ld.bfd
1316 // COFF linker will not properly handle comdats otherwise.
1317 if (getTargetTriple().isWindowsGNUEnvironment())
1318 raw_svector_ostream(Name) << '$' << COMDATSymName;
1319
David Majnemerdad0a642014-06-27 18:19:56 +00001320 return getContext().getCOFFSection(Name, Characteristics, Kind,
Reid Kleckner97837b72016-05-02 23:22:18 +00001321 COMDATSymName, Selection, UniqueID);
David Majnemer7db449a2015-03-17 23:54:51 +00001322 } else {
1323 SmallString<256> TmpData;
Peter Collingbourne67335642016-10-24 19:23:39 +00001324 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +00001325 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
Reid Kleckner97837b72016-05-02 23:22:18 +00001326 Selection, UniqueID);
David Majnemerdad0a642014-06-27 18:19:56 +00001327 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001328 }
1329
1330 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +00001331 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001332
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001333 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +00001334 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001335
David Majnemer597be2d2014-09-22 20:39:23 +00001336 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +00001337 return ReadOnlySection;
1338
David Majnemera9bdb322014-04-08 22:33:40 +00001339 // Note: we claim that common symbols are put in BSSSection, but they are
1340 // really emitted with the magic .comm directive, which creates a symbol table
1341 // entry but not a section.
1342 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +00001343 return BSSSection;
1344
1345 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001346}
1347
David Majnemer7db449a2015-03-17 23:54:51 +00001348void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001349 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001350 const TargetMachine &TM) const {
1351 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +00001352 if (GV->hasPrivateLinkage() &&
1353 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1354 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1355 CannotUsePrivateLabel = true;
1356
Eric Christopher4367c7f2016-09-16 07:33:15 +00001357 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
David Majnemer7db449a2015-03-17 23:54:51 +00001358}
1359
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001360MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001361 const Function &F, const TargetMachine &TM) const {
Rafael Espindolaab447e42015-03-11 19:58:37 +00001362 // If the function can be removed, produce a unique section so that
1363 // the table doesn't prevent the removal.
1364 const Comdat *C = F.getComdat();
1365 bool EmitUniqueSection = TM.getFunctionSections() || C;
1366 if (!EmitUniqueSection)
1367 return ReadOnlySection;
1368
1369 // FIXME: we should produce a symbol for F instead.
1370 if (F.hasPrivateLinkage())
1371 return ReadOnlySection;
1372
Tim Northoverb64fb452016-11-22 16:17:20 +00001373 MCSymbol *Sym = TM.getSymbol(&F);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001374 StringRef COMDATSymName = Sym->getName();
1375
1376 SectionKind Kind = SectionKind::getReadOnly();
Reid Kleckner13c9ee62018-06-21 20:27:38 +00001377 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001378 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001379 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Reid Kleckner97837b72016-05-02 23:22:18 +00001380 unsigned UniqueID = NextUniqueID++;
Rafael Espindolaab447e42015-03-11 19:58:37 +00001381
Reid Kleckner13c9ee62018-06-21 20:27:38 +00001382 return getContext().getCOFFSection(
1383 SecName, Characteristics, Kind, COMDATSymName,
1384 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001385}
1386
Eric Christopheraadbabc2018-04-20 19:07:57 +00001387void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1388 Module &M) const {
Peter Collingbourne89061b22017-06-12 20:10:48 +00001389 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001390 // Emit the linker options to the linker .drectve section. According to the
1391 // spec, this section is a space-separated string containing flags for
1392 // linker.
1393 MCSection *Sec = getDrectveSection();
1394 Streamer.SwitchSection(Sec);
1395 for (const auto &Option : LinkerOptions->operands()) {
1396 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1397 // Lead with a space for consistency with our dllexport implementation.
1398 std::string Directive(" ");
1399 Directive.append(cast<MDString>(Piece)->getString());
1400 Streamer.EmitBytes(Directive);
1401 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001402 }
1403 }
Saleem Abdulrasool4c474342017-06-05 21:26:39 +00001404
1405 unsigned Version = 0;
1406 unsigned Flags = 0;
1407 StringRef Section;
1408
Peter Collingbourne89061b22017-06-12 20:10:48 +00001409 GetObjCImageInfo(M, Version, Flags, Section);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +00001410 if (Section.empty())
1411 return;
1412
1413 auto &C = getContext();
1414 auto *S = C.getCOFFSection(
1415 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1416 SectionKind::getReadOnly());
1417 Streamer.SwitchSection(S);
1418 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1419 Streamer.EmitIntValue(Version, 4);
1420 Streamer.EmitIntValue(Flags, 4);
1421 Streamer.AddBlankLine();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001422}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001423
Rafael Espindola46fa2312016-08-29 12:33:42 +00001424void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1425 const TargetMachine &TM) {
1426 TargetLoweringObjectFile::Initialize(Ctx, TM);
1427 const Triple &T = TM.getTargetTriple();
1428 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1429 StaticCtorSection =
1430 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1431 COFF::IMAGE_SCN_MEM_READ,
1432 SectionKind::getReadOnly());
1433 StaticDtorSection =
1434 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1435 COFF::IMAGE_SCN_MEM_READ,
1436 SectionKind::getReadOnly());
1437 } else {
1438 StaticCtorSection = Ctx.getCOFFSection(
1439 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1440 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1441 SectionKind::getData());
1442 StaticDtorSection = Ctx.getCOFFSection(
1443 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1444 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1445 SectionKind::getData());
1446 }
1447}
1448
Martin Storsjo04b68442017-11-28 08:07:18 +00001449static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1450 const Triple &T, bool IsCtor,
1451 unsigned Priority,
1452 const MCSymbol *KeySym,
1453 MCSectionCOFF *Default) {
1454 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
1455 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1456
1457 std::string Name = IsCtor ? ".ctors" : ".dtors";
1458 if (Priority != 65535)
1459 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1460
1461 return Ctx.getAssociativeCOFFSection(
1462 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1463 COFF::IMAGE_SCN_MEM_READ |
1464 COFF::IMAGE_SCN_MEM_WRITE,
1465 SectionKind::getData()),
1466 KeySym, 0);
1467}
1468
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001469MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001470 unsigned Priority, const MCSymbol *KeySym) const {
Martin Storsjo04b68442017-11-28 08:07:18 +00001471 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1472 Priority, KeySym,
1473 cast<MCSectionCOFF>(StaticCtorSection));
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001474}
1475
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001476MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001477 unsigned Priority, const MCSymbol *KeySym) const {
Martin Storsjo04b68442017-11-28 08:07:18 +00001478 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1479 Priority, KeySym,
1480 cast<MCSectionCOFF>(StaticDtorSection));
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001481}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001482
1483void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001484 raw_ostream &OS, const GlobalValue *GV) const {
Bob Haarmandd4ebc12017-02-02 23:00:49 +00001485 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
Peter Collingbourneaef36592015-06-29 22:04:09 +00001486}
Dan Gohman18eafb62017-02-22 01:23:18 +00001487
Saleem Abdulrasool99f479a2018-01-20 00:28:02 +00001488void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1489 raw_ostream &OS, const GlobalValue *GV) const {
1490 emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1491}
1492
Reid Kleckner98117a42018-06-12 18:56:05 +00001493const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1494 const GlobalValue *LHS, const GlobalValue *RHS,
1495 const TargetMachine &TM) const {
1496 const Triple &T = TM.getTargetTriple();
1497 if (!T.isKnownWindowsMSVCEnvironment() &&
1498 !T.isWindowsItaniumEnvironment() &&
1499 !T.isWindowsCoreCLREnvironment())
1500 return nullptr;
1501
1502 // Our symbols should exist in address space zero, cowardly no-op if
1503 // otherwise.
1504 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1505 RHS->getType()->getPointerAddressSpace() != 0)
1506 return nullptr;
1507
1508 // Both ptrtoint instructions must wrap global objects:
1509 // - Only global variables are eligible for image relative relocations.
1510 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1511 // We expect __ImageBase to be a global variable without a section, externally
1512 // defined.
1513 //
1514 // It should look something like this: @__ImageBase = external constant i8
1515 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1516 LHS->isThreadLocal() || RHS->isThreadLocal() ||
1517 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1518 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1519 return nullptr;
1520
1521 return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1522 MCSymbolRefExpr::VK_COFF_IMGREL32,
1523 getContext());
1524}
1525
1526static std::string APIntToHexString(const APInt &AI) {
1527 unsigned Width = (AI.getBitWidth() / 8) * 2;
1528 std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1529 unsigned Size = HexString.size();
1530 assert(Width >= Size && "hex string is too large!");
1531 HexString.insert(HexString.begin(), Width - Size, '0');
1532
1533 return HexString;
1534}
1535
1536static std::string scalarConstantToHexString(const Constant *C) {
1537 Type *Ty = C->getType();
1538 if (isa<UndefValue>(C)) {
1539 return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1540 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1541 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1542 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1543 return APIntToHexString(CI->getValue());
1544 } else {
1545 unsigned NumElements;
1546 if (isa<VectorType>(Ty))
1547 NumElements = Ty->getVectorNumElements();
1548 else
1549 NumElements = Ty->getArrayNumElements();
1550 std::string HexString;
1551 for (int I = NumElements - 1, E = -1; I != E; --I)
1552 HexString += scalarConstantToHexString(C->getAggregateElement(I));
1553 return HexString;
1554 }
1555}
1556
1557MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1558 const DataLayout &DL, SectionKind Kind, const Constant *C,
1559 unsigned &Align) const {
Martin Storsjo9dafd6f2018-07-26 10:48:20 +00001560 if (Kind.isMergeableConst() && C &&
1561 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1562 // This creates comdat sections with the given symbol name, but unless
1563 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1564 // will be created with a null storage class, which makes GNU binutils
1565 // error out.
Reid Kleckner98117a42018-06-12 18:56:05 +00001566 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1567 COFF::IMAGE_SCN_MEM_READ |
1568 COFF::IMAGE_SCN_LNK_COMDAT;
1569 std::string COMDATSymName;
1570 if (Kind.isMergeableConst4()) {
1571 if (Align <= 4) {
1572 COMDATSymName = "__real@" + scalarConstantToHexString(C);
1573 Align = 4;
1574 }
1575 } else if (Kind.isMergeableConst8()) {
1576 if (Align <= 8) {
1577 COMDATSymName = "__real@" + scalarConstantToHexString(C);
1578 Align = 8;
1579 }
1580 } else if (Kind.isMergeableConst16()) {
1581 // FIXME: These may not be appropriate for non-x86 architectures.
1582 if (Align <= 16) {
1583 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1584 Align = 16;
1585 }
1586 } else if (Kind.isMergeableConst32()) {
1587 if (Align <= 32) {
1588 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1589 Align = 32;
1590 }
1591 }
1592
1593 if (!COMDATSymName.empty())
1594 return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1595 COMDATSymName,
1596 COFF::IMAGE_COMDAT_SELECT_ANY);
1597 }
1598
1599 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1600}
1601
1602
Dan Gohman18eafb62017-02-22 01:23:18 +00001603//===----------------------------------------------------------------------===//
1604// Wasm
1605//===----------------------------------------------------------------------===//
1606
Sam Cleggea7cace2018-01-09 23:43:14 +00001607static const Comdat *getWasmComdat(const GlobalValue *GV) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001608 const Comdat *C = GV->getComdat();
1609 if (!C)
Sam Cleggea7cace2018-01-09 23:43:14 +00001610 return nullptr;
Dan Gohmand934cb82017-02-24 23:18:00 +00001611
Sam Cleggea7cace2018-01-09 23:43:14 +00001612 if (C->getSelectionKind() != Comdat::Any)
1613 report_fatal_error("WebAssembly COMDATs only support "
1614 "SelectionKind::Any, '" + C->getName() + "' cannot be "
1615 "lowered.");
1616
1617 return C;
Dan Gohmand934cb82017-02-24 23:18:00 +00001618}
1619
Sam Clegge1694f92017-12-07 02:55:51 +00001620static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1621 // If we're told we have function data, then use that.
1622 if (K.isText())
1623 return SectionKind::getText();
1624
1625 // Otherwise, ignore whatever section type the generic impl detected and use
1626 // a plain data section.
1627 return SectionKind::getData();
1628}
1629
Dan Gohman18eafb62017-02-22 01:23:18 +00001630MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1631 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Sam Clegg277f8982018-06-14 18:48:19 +00001632 // We don't support explict section names for functions in the wasm object
1633 // format. Each function has to be in its own unique section.
1634 if (isa<Function>(GO)) {
1635 return SelectSectionForGlobal(GO, Kind, TM);
1636 }
1637
Sam Clegg759631c2017-09-15 20:54:59 +00001638 StringRef Name = GO->getSection();
Sam Cleggea7cace2018-01-09 23:43:14 +00001639
Sam Clegge1694f92017-12-07 02:55:51 +00001640 Kind = getWasmKindForNamedSection(Name, Kind);
Sam Cleggea7cace2018-01-09 23:43:14 +00001641
1642 StringRef Group = "";
1643 if (const Comdat *C = getWasmComdat(GO)) {
1644 Group = C->getName();
1645 }
1646
1647 return getContext().getWasmSection(Name, Kind, Group,
1648 MCContext::GenericSectionID);
Dan Gohman18eafb62017-02-22 01:23:18 +00001649}
1650
Sam Clegg2176a9f2017-09-12 18:31:24 +00001651static MCSectionWasm *selectWasmSectionForGlobal(
1652 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1653 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001654 StringRef Group = "";
Sam Cleggea7cace2018-01-09 23:43:14 +00001655 if (const Comdat *C = getWasmComdat(GO)) {
1656 Group = C->getName();
1657 }
Dan Gohmand934cb82017-02-24 23:18:00 +00001658
1659 bool UniqueSectionNames = TM.getUniqueSectionNames();
1660 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1661
1662 if (const auto *F = dyn_cast<Function>(GO)) {
1663 const auto &OptionalPrefix = F->getSectionPrefix();
1664 if (OptionalPrefix)
1665 Name += *OptionalPrefix;
1666 }
1667
1668 if (EmitUniqueSection && UniqueSectionNames) {
1669 Name.push_back('.');
1670 TM.getNameWithPrefix(Name, GO, Mang, true);
1671 }
1672 unsigned UniqueID = MCContext::GenericSectionID;
1673 if (EmitUniqueSection && !UniqueSectionNames) {
1674 UniqueID = *NextUniqueID;
1675 (*NextUniqueID)++;
1676 }
Sam Clegg12fd3da2017-10-20 21:28:38 +00001677 return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
Dan Gohmand934cb82017-02-24 23:18:00 +00001678}
1679
Dan Gohman18eafb62017-02-22 01:23:18 +00001680MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1681 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Dan Gohmand934cb82017-02-24 23:18:00 +00001682
1683 if (Kind.isCommon())
1684 report_fatal_error("mergable sections not supported yet on wasm");
1685
1686 // If we have -ffunction-section or -fdata-section then we should emit the
1687 // global value to a uniqued section specifically for it.
1688 bool EmitUniqueSection = false;
Dan Gohman18eafb62017-02-22 01:23:18 +00001689 if (Kind.isText())
Dan Gohmand934cb82017-02-24 23:18:00 +00001690 EmitUniqueSection = TM.getFunctionSections();
1691 else
1692 EmitUniqueSection = TM.getDataSections();
1693 EmitUniqueSection |= GO->hasComdat();
1694
1695 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
Sam Clegg2176a9f2017-09-12 18:31:24 +00001696 EmitUniqueSection, &NextUniqueID);
Dan Gohman18eafb62017-02-22 01:23:18 +00001697}
1698
1699bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1700 bool UsesLabelDifference, const Function &F) const {
1701 // We can always create relative relocations, so use another section
1702 // that can be marked non-executable.
1703 return false;
1704}
1705
1706const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1707 const GlobalValue *LHS, const GlobalValue *RHS,
1708 const TargetMachine &TM) const {
1709 // We may only use a PLT-relative relocation to refer to unnamed_addr
1710 // functions.
1711 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1712 return nullptr;
1713
1714 // Basic sanity checks.
1715 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1716 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1717 RHS->isThreadLocal())
1718 return nullptr;
1719
1720 return MCBinaryExpr::createSub(
1721 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1722 getContext()),
1723 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1724}
1725
Sam Cleggb2b019f2017-10-03 11:20:28 +00001726void TargetLoweringObjectFileWasm::InitializeWasm() {
1727 StaticCtorSection =
Sam Clegg12fd3da2017-10-20 21:28:38 +00001728 getContext().getWasmSection(".init_array", SectionKind::getData());
Sam Cleggbafe6902017-12-15 00:17:10 +00001729}
1730
1731MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1732 unsigned Priority, const MCSymbol *KeySym) const {
1733 return Priority == UINT16_MAX ?
1734 StaticCtorSection :
1735 getContext().getWasmSection(".init_array." + utostr(Priority),
1736 SectionKind::getData());
1737}
1738
1739MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1740 unsigned Priority, const MCSymbol *KeySym) const {
1741 llvm_unreachable("@llvm.global_dtors should have been lowered already");
1742 return nullptr;
Dan Gohman18eafb62017-02-22 01:23:18 +00001743}